Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
getting cannot convert to male error in django?
I am trying to export the list of customers using django. class Gender(models.IntegerChoices): FEMALE = 1, female_label MALE = 2, male_label gender = models.PositiveSmallIntegerField( db_column="Gender", verbose_name=gender_label, choices=Gender.choices, blank=True, null=True, ) and I am calling in the export row like this: customer.gender_label and I am getting such an error Cannot convert 'Male' to Excel do you have any idea why this error is showing up? -
CSS file not found when trying to load with django
My CSS file i'snt being found I try to load it in and ive tried so many different solutions online in order to fix it and cant seem to figure out why and I also have my static and templates both in the same file as the project along with my manage.py file. For my Setting file 'django.contrib.staticfiles' STATIC_URL = '/static/' Inside my base html I have {% load static %} <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- The css file can be modified for every template if required --> {% block style_css %} <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}" /> {% endblock %} <title>Website Homepage Design Prototype #1</title> -
How to use wavesurfer.js with django
I would like to know how to create multiple wavesurfer audio tracks with django. I created one audio track with wavesurfer and I would like to know how to integrate it with django to create multiple tracks dinamically. Thanks in advance for any tips or helped provided. Here is the audio player in the HTML file: <div class="container"> <div class="row"> <div class="col-lg-6"> <div class="container-audio"> <img src="static/assets/img/perfil.png" alt="" /> <div class="track-name"> <h2>O nome da música</h2> <p>O nome do álbum</p> <div id="audio1" class="audio-track"></div> <div class="controls"> <img class="icones" id="playBtn" src="static/assets/img/play.png" alt="" /> <img class="icones" id="stopBtn" src="static/assets/img/stop.png" alt="" /> <img class="icones" id="volumeBtn" src="static/assets/img/volume-up.png" alt="" /> </div> </div> </div> <!--col--> </div> <!--row--> </div> <!--container--> Here is the wavesurfer code in javascript: var audioTrack = WaveSurfer.create({ container: '.audio-track', waveColor: '#dde5ec', progressColor: '#03cebf', height: 90, responsive: true, hideScrollbar: true, fillParent: false, minPxPerSec: 1.5, }); audioTrack.load('../static/assets/audio/acontecer.mp3'); const playBtn = document.getElementById('playBtn'); const stopBtn = document.getElementById('stopBtn'); const volumeBtn = document.getElementById('volumeBtn'); playBtn.onclick = function (){ audioTrack.playPause(); if(playBtn.src.includes('play.png')){ playBtn.src = 'static/assets/img/pause.png'; } else { playBtn.src = 'static/assets/img/play.png'; } } stopBtn.onclick = function (){ audioTrack.stop(); playBtn.src = 'static/assets/img/play.png'; } volumeBtn.onclick = function (){ audioTrack.toggleMute(); if(volumeBtn.src.includes('volume-up.png')){ volumeBtn.src = 'static/assets/img/mute.png'; } else { volumeBtn.src = 'static/assets/img/volume-up.png'; } } audioTrack.on('finish', function () { playBtn.src = 'static/assets/img/play.png'; … -
Django testing class of models.py contain error
I am testing the testing the models.py file which contain two class one is Farm and another one is Batch and Batch has a foreign key related to farm while testing the batch I have tested all the other columns but not sure how should I test the foreign key column of batch class models.py file lopoks like import sys from datetime import datetime from dateutil.relativedelta import relativedelta from django.apps import apps from django.conf import settings from django.core.exceptions import ValidationError from django.core.validators import MaxValueValidator, MinValueValidator from django.db import models from django.db.models.signals import post_save, post_delete from django.dispatch import receiver from django_google_maps import fields as map_fields from django_mysql.models import ListTextField from simple_history.models import HistoricalRecords from farm_management import config from igrow.utils import get_commodity_name, get_region_name, get_farmer_name, get_variety_name db_config = settings.USERS_DB_CONNECTION_CONFIG class Device(models.Model): id = models.CharField(max_length=100, primary_key=True) fetch_status = models.BooleanField(default=True) last_fetched_on = models.DateTimeField(auto_now=True) geolocation = map_fields.GeoLocationField(max_length=100) device_status = models.CharField(max_length=100, choices=config.DEVICE_STATUS, default='new') is_active = models.BooleanField(default=True) history = HistoricalRecords() class Farm(models.Model): farmer_id = models.PositiveIntegerField() # User for which farm is created irrigation_type = models.CharField(max_length=50, choices=config.IRRIGATION_TYPE_CHOICE) soil_test_report = models.CharField(max_length=512, null=True, blank=True) water_test_report = models.CharField(max_length=512, null=True, blank=True) farm_type = models.CharField(max_length=50, choices=config.FARM_TYPE_CHOICE) franchise_type = models.CharField(max_length=50, choices=config.FRANCHISE_TYPE_CHOICE) total_acerage = models.FloatField(help_text="In Acres", null=True, blank=True, validators=[MaxValueValidator(1000000), MinValueValidator(0)]) farm_status = models.CharField(max_length=50, default="pipeline", choices=config.FARM_STATUS_CHOICE) assignee_id … -
Insert data Into Another Table on post_save in model updated field Django
I am using ModelForms to update data. I need to track which user has updated the fields in "MyModel" by saving username, field name, and DateTime of update in the UpdateFieldLog table. I learned that it can be done by signals, but don't know how to do it. Can someone help Model class MyModel(models.Model): a = models.CharField(max_length=20, null=True) b = models.CharField(max_length=25, null=True) c = models.CharField(max_length=10, null=True) d = models.CharField(max_length=20, null=True) e = models.BigIntegerField(null=True) f = models.CharField(max_length=15, null=True) g = models.DateField(null=True) class UpdateFieldLog(models.Model): field_name = models.CharField(max_length=20, null=False) updated_by = models.ForeignKey(User, on_delete=models.DO_NOTHING) updated_on = models.DateTimeField(auto_now_add=True) @receiver(post_save, sender=MyModel) def post_save_MyModel(sender, instance, **kwargs): if not instance._state.adding: for item in iter(kwargs.get('update_fields')): if item == 'field_name' and instance.field_name == "some_value": print(item) print(instance.field_name) else: print ('this is an insert') -
How do I resolve a Bad Request 400 error using send_mail function?
I'm using a React frontend to send data from a react rendered contact form to a Django backend; which sends the data as an email. However, I keep getting a 400 Bad Request error. I tried to use the send_mail function in a shell, but I get this error: "socket.gaierror: [Errno 11001] getaddrinfo failed" Contact.js const sendEmail = () => { const csrfCookie = Cookies.get('csrftoken'); console.log(formValue); axios.post("contact/", formValue, { headers: { 'X-CSRFTOKEN': csrfCookie, }, }) .then(response => { console.log(response); }) .catch(error => { console.log(error); }); }; const handleSubmit = (event) => { event.preventDefault(); sendEmail(); setFormValue({ name: "", email: "", message: "", }); }; urls.py from django.urls import path from django.views.generic import TemplateView from .views import Contact app_name = "core" urlpatterns = [ path("", TemplateView.as_view(template_name="core/home.html"), name="home"), path("contact/", Contact.as_view(), name="contact"), ] views.py class Contact(APIView): def post(self, request): serializer = ContactSerializer(data=request.data) if serializer.is_valid(): form = serializer.data subject = "Website Inquiry" body = { "name": form["name"], "email": form["email"], "message": form["message"], } message = "\n".join(body.values()) try: send_mail( subject, message, settings.EMAIL_HOST_USER, [settings.RECIPIENT_ADDRESS], ) return Response(serializer.data, status=status.HTTP_201_CREATED) except: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) settings.py env = environ.Env() environ.Env.read_env() EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend" EMAIL_HOST = "EMAIL_HOST" EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = env("EMAIL_HOST_USER") EMAIL_HOST_PASSWORD = env("EMAIL_HOST_PASSWORD") RECIPIENT_ADDRESS = env("RECIPIENT_ADDRESS") -
How to get user id in the serializer for the token authenticated user in DRF
How can I get the user from token in serializer? I am getting the id in views but I need in serializer for applying a filter in queryset of nested queryset. views.py class UserListAPIView(generics.ListAPIView): permission_classes = (permissions.IsAuthenticated, jwtPermissions.IsSSOAdminOrReadOnly,) queryset = userModels.User.objects.all() serializer_class = serializers.UserSerializers def get_queryset(self): return self.queryset.filter(id=self.request.user.id) serializers.py class UserSerializers(serializers.ModelSerializer): class Meta: model = userModel.User fields = ('id','email','name','contact_no','address','is_active','solutions') def to_representation(self, instance): rep = super().to_representation(instance) rep['component'] = ComponentUserSerializers(instance.component.all(), many=True).data return rep class ComponentUserSerializers(serializers.ModelSerializer): user_devices = serializers.SerializerMethodField() def get_user_devices(self, obj): #self.context['request'].user.id <-- getting null user_devices_queryset = sensorModel.UserSensorDevice.objects.filter(sensor_type=obj.id, user = self.context['request'].user.id) user_devices_serializer = sensorSerializers.UserSensorDeviceSerializer(user_devices_queryset, many=True) return user_devices_serializer.data class Meta: model = coreModel.Component fields = ('id','comp_code','part_no', 'user_devices') I need to apply a filter in ComponentUserSerializer in get_user_devices API. And I am not getting user_id of the token authenticated user. -
Django - Update one fields value automatically after a value change
I am new to django and I have a simple question. I have two model: Model RegisterLogin and Model OtpEmailVerify. I wanna make 'is_verified' field of Model OtpEmailVerify 'True' as long as 'otp_no' provided matches with the 'otp' field of model LoginRegister. models.py class RegisterLogin(AbstractUser): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created_date = models.DateTimeField(auto_now_add=True) updated_date = models.DateTimeField(auto_now_add=True) email = models.EmailField(unique=True) first_name = models.CharField(max_length=100, blank=False) last_name = models.CharField(max_length=100, blank=False) phone_regex = RegexValidator(regex=r'\+?1?\d{9,15}$', message="Phone number must be entered in the format: '+999-999999'. Up to 15 digits allowed.") phone_number = models.CharField(validators=[phone_regex], max_length=15, blank=False, unique=True) sign_up_for_newspaper = models.BooleanField(default=False) allow_remote_shopping_assistance = models.BooleanField(default=False) otp = models.CharField(null=False, unique=False, max_length=5) username = None USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name', 'phone_number'] def __str__(self): return self.email def save(self, *args, **kwargs): otp_choice = '1234567890' for i in range(5): self.otp += str(random.choice(otp_choice)) super(RegisterLogin, self).save() class OtpEmailVerify(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4) otp_no = models.IntegerField(default=0, help_text='Please enter the Otp that has been sent for ' 'verification ') user = models.OneToOneField(RegisterLogin, null=False, on_delete=models.CASCADE) is_verified = models.BooleanField(default=False, help_text='if it is true, that means can now validate otp for verification') def __str__(self): return self.otp_no def save(self, *args, **kwargs): if self.otp_no == self.user.otp: return not self.is_verified else: return ValidationError('Wrong Otp Provided.') views.py class OtpVerifyView(generics.CreateAPIView): queryset = OtpEmailVerify.objects.all() serializer_class = … -
Unable to install Misaka
I tried installing wheels and again ran pip install misaka but I'm ending up with the same error. Misaka installation error! -
How to access the dictionary keys and values in django templates
I have created a dictionary of message senders which is updating dynamically. If I print the dictionary keys in the python console window, I am getting the expected output but when I try to access the values in the Django template, I am getting nothing here is my python code; views.py def home(request): senders = {} chatting =Message.objects.filter(seen=False) for msg in chatting: user = User.objects.get(id=msg.sender.id) if user != request.user and user not in senders.values(): senders.update({user.id : user}) return render(request, 'home.html', senders) template Home.html <div> {% for key, val in senders %} <div> <a href="#">{{val}}</a> </div> {% endfor %} </div> -
Auto generate classes in python
I want to create a new subclass of a base class after creating an object in my django admin project. Auto creation of class that I want is something like django migration when createmigration is execute. How can I do it? -
How to pass serializer.data into create function in views django
views.py def productslist(request): products = Products.objects.all() context = {'products':products} return render(request,'productslist.html',context) def productsform(request): return render(request,'productscreate.html') @api_view(['GET','POST']) def products_list(request): if request.method == 'GET': product = Products.objects.all() serializer = Productserialize(product,many=True) return Response(serializer.data) elif request.method == 'POST': serializer = Productserialize(data=request.data) if serializer.is_valid(): def create(serializer): return Products.objects.create(serializer) return Response(serializer.data) return Response(serializer.errors) @api_view(['GET','PUT']) def products_detail(request, pk): products = Products.objects.get(pk=pk) if request.method == 'GET': serializer = Productserialize(products) return Response(serializer.data) elif request.method == 'PUT': serializer = Productserialize(products, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors) In views.py I have done create function but it is not working not saving data I want to save serializer data using create function I want to pass serializer.data into create function in post method api Please help me to solve this Thanks in advance serializer.py from rest_framework import serializers from .models import Products class Productserialize(serializers.Serializer): id = serializers.IntegerField(read_only=True) title = serializers.CharField(required=False, allow_blank=True, max_length=100) description = serializers.CharField(required=False, allow_blank=True, max_length=100) image = serializers.FileField() def create(self, validated_data): """ Create and return a new `Snippet` instance, given the validated data. """ return Products.objects.create(**validated_data) -
Django keep open tab
Is there any way to redirect home and keep the open tab. views.py from django.views.decorators.http import require_http_methods @require_http_methods(["POST"]) def reply(request,messageID): print(messageID) parent = Messages.objects.get(id=messageID) reply = Messages.objects.create(text=request.POST['text'], receiver=parent.sender, sender=request.user, parent=parent) print(parent) print(reply) print(request.POST) return redirect('home') html: {% block content %} <div class="col-md-3" style="float:left"> <h1>Hi {{ user.username }}!</h1> <img class="avatar" src="{{user.get_profile_pic_url}}" > <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#editProfile">+</button> <ul class="nav nav-tabs flex-column" id="myTab" role="tablist"> <li class="nav-item" role="presentation"> <a class="nav-link active" id="home-tab" data-bs-toggle="tab" href="#home" role="tab" aria-controls="home" aria-selected="true">Dashboard</a> </li> <li class="nav-item dropdown" role="presentation"> <a class="nav-link dropdown-toggle" id="messages-tab" data-bs-toggle="dropdown" aria-expanded="false">Messages</a> <ul class="dropdown-menu"> <li><a class="dropdown-item" id="messages-send-tab" data-bs-toggle="tab" href="#messagesSend" role="tab" aria-controls="messagesSend" aria-selected="false">Send</a></li> <li><a class="dropdown-item" id="messages-inbox-tab" data-bs-toggle="tab" href="#messagesInbox" role="tab" aria-controls="messagesInbox" aria-selected="false">Inbox</a></li> </ul> </li> </ul> </div> <div class="col-md-9" style="float:right"> <div class="tab-content" id="myTabContent"> <div class="tab-pane fade show active" id="home" role="tabpanel" aria-labelledby="home-tab"> {% include 'dashboard.html' %} </div> <div class="tab-pane fade" id="messagesSend" role="tabpanel" aria-labelledby="messages-send-tab"> {% include 'sendMessageForm.html' %} </div> <div class="tab-pane fade" id="messagesInbox" role="tabpanel" aria-labelledby="messages-inbox-tab"> {% include 'inbox.html' %} </div> </div> </div> {% endblock %} -
How to send Django model object's details as answer according to the user's choice of InlineKeyboardButton?
I'm new to creating telegram bots with Django. I selected python-telegram-bot library for creating bots with Django. I've created a Django model, named as category: class category(models.Model): name = models.CharField(max_length=250) category_id = models.IntegerField() def __str__(self): return self.name and product: class product(models.Model): product_category = models.ForeignKey(category, on_delete=models.SET_NULL, blank=True, null=True) name = models.CharField(max_length=250) cost = models.FloatField() img = models.ImageField() def __str__(self): return self.name Successfully created InlineKeyboardButtons and placed id of each product model object to each button, with these functions: def product(update: Update, context: CallbackContext): query = update.callback_query.data product_button_list = [] for each in product.objects.select_related().filter(product_category_id = query): product_button_list.append(InlineKeyboardButton(each.name, callback_data=each.id)) reply_markup = InlineKeyboardMarkup(build_menu(product_button_list,n_cols=2)) update.callback_query.message.edit_text("Mahsulotni tanlang!", reply_markup=reply_markup) def build_menu(buttons,n_cols,header_buttons=None,footer_buttons=None): menu = [buttons[i:i + n_cols] for i in range(0, len(buttons), n_cols)] if header_buttons: menu.insert(0, header_buttons) if footer_buttons: menu.append(footer_buttons) return menu When the user selects a button named as the name of the product model object, I am receiving the correct id of the product model object, tested with printing the query: def product_info(update: Update, context: CallbackContext): query = update.callback_query.data print(query) obj = albus_product.objects.filter(pk=query) print(obj) Question: How to reply Django product model object's fields including its image to the user according to the user's chosen product? Like: You have chosen a product: Image of the product Name … -
Django, assigning a composite value to one field depending upon values entered in other fields in same model?
I am new to django. What I am currently trying to do is set a value which is a primary key and non-editable automatically generated depending upon the values entered in the same model to some other fields. Here is an example: class Student(models.Model): student_id = models.CharField(max_length=100, primary_key=true) name = models.CharField(max_length=100) class = models.CharField(max_length=200) roll_no = models.CharField(max_length=500) So, what I am trying to achieve is if someone enters following information : name = Haris class = 8th roll_no = 104011 The automatically generated primary key that would be non-editable for field "student_id" would be: student_id = Haris_8th_104011 Does anyone have an idea how to achieve this? Hope my example made the query clear though. -
ERROR: Command errored out with exit status -11
I ran this command in a virtual environment with Python3.6.7: pip3 install -r requirements.txt --use-deprecated=legacy-resolver Then I got this error: ERROR: Command errored out with exit status -11: command: /home//venv/bin/python /home//venv/lib/python3.6/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-dm6prya6/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'poetry-core>=1.0.0' cwd: None Complete output (0 lines): ERROR: Command errored out with exit status -11: /home//venv/bin/python /home//venv/lib/python3.6/site-packages/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-dm6prya6/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'poetry-core>=1.0.0' Check the logs for full command output. -
Django pass back some data on post
if not request.user.is_doctor and not request.user.is_staff: bookAppointment = BookAppointmentForm() bookAppointment.fields['doctors'].queryset = Profile.objects.filter(Q(is_active=True)&Q(is_doctor=True)) context['bookAppointment'] = bookAppointment I would like to add data to the page if a dropdown was selected with the above no redirects since I am using the below to pass a table back. d = get_date(request.GET.get('day', None)) print(d) # Instantiate our calendar class with today's year and date cal = Calendar(d.year, d.month) html_cal = cal.formatmonth(withyear=True) # Figure how to pass this context['calendar'] = mark_safe(html_cal) html: <form method = "POST" action='/displayCalendar' enctype="multipart/form-data"> {% csrf_token %} {{ bookAppointment.as_p }} <button type="submit" name='bookAppointment'>Check availability</button> </form> {{calendar}} forms.py class BookAppointmentForm(forms.ModelForm): class Meta: model = Calendar fields = ('doctors',) -
Unauthorized User Error in Django Unit test
Hello! I am writing a unit test case for a website, The website has a basic function of address update, the address update requires an authentic user login, so I am using the temporary token for that purpose in query-param (as a part of website functionality) from django.test import TestCase from accounts.models import Address, User, Business, Employment from accounts.controllers import AddressController class Test_Cases_AddressController(TestCase): user= User.objects.create_user( birth_year=1996, birth_month= 8, birth_day = 15, marital_status= "married", \ reset_password_token = "xxxxy", confirmation_token = "xxxx", password_reset_at= "2022-01-12 13:12:13", \ confirmed_at= "2022-01-12 13:12:13", email= "testuser@example.com", username = "testuser123") def test_update_address(self): address1 = Address.objects.create(street_1="abc abc abc", city="lahore", state="punjab", zip="54000", type="abcdef") API_LOGIN_URL = '/addresses/1/?_t=xxxx/' response= self.client.put(API_LOGIN_URL, {"street_1": "xyz xyz xyz"}, content_type='application/json' ) self.assertEquals(response.status_code, 201) def test_get_address(self): API_LOGIN_URL = '/addresses/1/?_t=xxxx/' response= self.client.get(API_LOGIN_URL) self.assertEquals(response.status_code, 200) but I am still getting the same unauthorized error PS C:\Users\Lenovo\web> docker-compose run --rm api sh -c "python manage.py test accounts" Creating web_api_run ... done Creating test database for alias 'default'... System check identified some issues: WARNINGS: accounts.User.privacy: (postgres.E003) JSONField default should be a callable instead of an instance so that it's not shared between all field instances. HINT: Use a callable instead, e.g., use `dict` instead of `{}`. main.NonProfit.website: (fields.W340) null has no effect … -
django create object using nested serializer and model
Hi i am try to create 3 model objects in single post request from flutter to django restframework but i don't know how to use serializer to create object so I'm implemented many lines of code to done this but it's working fine. It's correct or not View.py from rest_framework.views import APIView from .models import Booking, FromAddress, Product, ToAddress from .serializers import BookingSerializer, FromAddressSerializer from rest_framework.response import Response from rest_framework import status # Create your views here. class BookingView(APIView): def get(self,req): bookings = Booking.objects.all() serializer = BookingSerializer(bookings,many=True) return Response(serializer.data) def post(self,req): user = self.request.user fromAddressData = req.data['from_address'] toAddressData = req.data['to_address'] productData = req.data['product'] from_address = FromAddress.objects.create(name=fromAddressData['name'],phone=fromAddressData['phone'],address=fromAddressData['address'],) to_address = ToAddress.objects.create(name=toAddressData['name'],phone=toAddressData['phone'],address=toAddressData['address'],pincode=toAddressData['pincode'],) product = Product.objects.create(title = productData['title'],weight = productData['weight'],nature_of_content=productData['nature_of_content'],breakable=productData['breakable'],) from_address.save() fadrs = FromAddress.objects.get(id= from_address.id) print(FromAddressSerializer(fadrs)) to_address.save() product.save() booking = Booking.objects.create(user=req.user,from_address=fadrs,to_address=to_address,product= product, price=req.data['price'], payment_id=req.data['payment_id']) booking.save() return Response('Success') Model.py from django.db import models from django.contrib.auth.models import User import uuid # Create your models here. class FromAddress(models.Model): name = models.CharField(max_length=50) phone = models.CharField(max_length=10) address = models.TextField(max_length=200) def __str__(self): return self.name class ToAddress(models.Model): name = models.CharField(max_length=50) phone = models.CharField(max_length=10) address = models.TextField(max_length=200) pincode = models.CharField(max_length=6) def __str__(self): return self.name class Product(models.Model): title = models.CharField(max_length=50) weight = models.DecimalField(max_digits=5,decimal_places=2) nature_of_content = models.CharField(blank=True,null=True,max_length=100) breakable = models.BooleanField(default=False) def __str__(self): return f'{self.title} … -
displaying None instead of data in the form of table
Here, select machine name and operation number, after select and save, It is displaying none instead of data like machine name and operation number in the form of table. Please help me out to solve this. I am new in Django. urls.py: urlpatterns = [ path('upload/',views.upload,name='upload'), path('save',views.save_machine,name='save_machine') ] views.py: def upload(request): machines = Machine.objects.all() return render(request,'usermaster/upload.html',{'machines':machines}) def save_machine(request): if request.method == "POST": machine_name = request.POST.get('machine_name', '') operation_no = request.POST.get('operation_no') choiced_machine = Machine.objects.get(machine_name=machine_name, operation_no=operation_no) machines = Machine.objects.all() return render(request,'usermaster/upload.html',{'machines':machines,'choiced_machine':choiced_machine}) models.py: class Machine(models.Model): machine_name = models.CharField(max_length=200) operation_no = models.IntegerField(null=True) def __str__(self): return self.machine_name upload.html: <form action="{% url 'save_machine' %}" method="post"> {% csrf_token %} <select> <option>Select Machine Name</option> {% for machine in machines %} <option name="machine_name">{{ machine.machine_name }}</option> {% endfor %} </select> <br> <br> <select> <option>Select Operation Number</option> {% for machine in machines %} <option name="operation_no">{{ machine.operation_no }}</option> {% endfor %} </select> <br> <br> <br> <input type="submit" value="Save"> </form> <tr> <td>{{choiced_machine.machine_name}}</td> <td>{{choiced_machine.operation_no}}</td> </tr> -
Adding criteria to Django DRF responsive map InBBoxFilter with viewsets.py, not views.py?
We've developed a responsive map using this tutorial where Django Rest Framework serves responses that populates the map. My viewsets.py: class MarkerViewSet(viewsets.ReadOnlyModelViewSet): """Marker view set.""" bbox_filter_field = "geom" filter_backends = (filters.InBBoxFilter,) queryset = Tablename.objects.all() serializer_class = MarkerSerializer pagination_class = GeoPaginator I'd like to add optional criteria to this filter if they are found in a GET value. The rest of my project uses views.py, which filters things differently. My simplified views.py which does this for something else: def EgFilterView(request): qs = Tablename.objects.all() date_min_query = request.GET.get('dmin') min_date = 1970 qs = qs.filter(date__gte=dt.datetime(int(date_min_query), 1, 1, tzinfo=pytz.UTC)) context = { 'queryset': qs, 'dmin': min_date, } return render(request, "main_page.html", context) But it looks like viewsets.py doesn't handle .get() values in this way, but instead uses .list() and .create(), which I don't understand. How can I include additional filters into my viewsets.py to further filter things with GET values? Would it be better to attempt to convert this viewsets.py / other complicated API stuff I don't understand into views.py? -
How can I restrict users to delete other's posts in django using class based views?
my views.py file: from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from django.contrib.auth.mixins import ( LoginRequiredMixin, UserPassesTestMixin, ) from .models import Post # Create your views here. class PostListView(ListView): model = Post template_name = "blog/index.html" context_object_name = "posts" ordering = ["-date_posted"] class PostDetailView(DetailView): model = Post class PostCreateView(CreateView, LoginRequiredMixin, UserPassesTestMixin): model = Post fields = ['title', 'genere', 'content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) class PostUpdateView(UpdateView, LoginRequiredMixin, UserPassesTestMixin): model = Post success_url = "blog-home" def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False class PostDeleteView(DeleteView, LoginRequiredMixin, UserPassesTestMixin): model = Post success_url = "/" def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) def test_func(self): post = self.get_object() if self.request.user == post.author: return True return False def about(request): return render(request, 'blog/about.html') My models.py: from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.urls import reverse # Create your models here. class Post(models.Model): title = models.CharField(max_length=200) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) genere = models.CharField(max_length=50, default='') def __str__(self): return f'{self.title} by {self.author}' def get_absolute_url(self): return reverse('blog-home') my urls.py url: from django.urls import path from .views import PostListView, … -
JWT authentication for Django rest framework --> error ={ "detail": "Authentication credentials were not provided." }
I'm using JWT for authentication and I can't make this error go away... HTTP 401 Unauthorized Allow: GET, OPTIONS Content-Type: application/json Vary: Accept WWW-Authenticate: Bearer realm="api" { "detail": "Authentication credentials were not provided." } Below are all my code files... I think the error is in the simple_jwt section in the settings file but can't figure out what. I looked up a few stackoverflow answers already but nothing seem to work out in my case. settings.py REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', # 'rest_framework.authentication.TokenAuthentication', ), } from datetime import timedelta from django.conf import settings SIMPLE_JWT = { 'ACCESS_TOKEN_LIFETIME': timedelta(minutes=30), # 'REFRESH_TOKEN_LIFETIME': timedelta(days=1), 'ROTATE_REFRESH_TOKENS': False, 'BLACKLIST_AFTER_ROTATION': False, 'UPDATE_LAST_LOGIN': False, 'ALGORITHM': 'HS256', 'SIGNING_KEY': settings.SECRET_KEY, 'VERIFYING_KEY': None, 'AUDIENCE': None, 'ISSUER': None, 'JWK_URL': None, 'LEEWAY': 0, 'AUTH_HEADER_TYPES': ('Bearer',), 'AUTH_HEADER_NAME': 'HTTP_AUTHORIZATION', 'USER_ID_FIELD': 'id', 'USER_ID_CLAIM': 'user_id', 'USER_AUTHENTICATION_RULE': 'rest_framework_simplejwt.authentication.default_user_authentication_rule', 'AUTH_TOKEN_CLASSES': ('rest_framework_simplejwt.tokens.AccessToken',), 'TOKEN_TYPE_CLAIM': 'token_type', 'JTI_CLAIM': 'jti', 'SLIDING_TOKEN_REFRESH_EXP_CLAIM': 'refresh_exp', 'SLIDING_TOKEN_LIFETIME': timedelta(minutes=5), 'SLIDING_TOKEN_REFRESH_LIFETIME': timedelta(days=1), } serializers.py from rest_framework import serializers from django.contrib.auth.models import User from rest_framework_simplejwt.tokens import RefreshToken, Token from .models import Book class UserSerializer(serializers.ModelSerializer): name = serializers.SerializerMethodField(read_only=True) _id = serializers.SerializerMethodField(read_only=True) isAdmin = serializers.SerializerMethodField(read_only=True) class Meta: model = User fields = ['id', '_id', 'email', 'username', 'name', 'isAdmin'] def get__id(self, obj): return obj.id def get_isAdmin(self, obj): return obj.is_staff def get_name(self, obj): … -
Django: Check at model level if anything in ManyToMany field before saving
There's a lot of questions worded similarly, but every single one I've seen is somebody trying to get some kind of data through a ManyToMany relationship before saving it. I'm not trying to use the relationship at all before saving, I just want to see if the user put anything there or not. My model has a ForeignKey field pointing to a parent model, and two ManyToMany fields pointing to other models, but I only want users to be able to use one M2M field or the other, not both. This model is being edited through the admin as an inline on its parent. models.py class ProductSpecial(models.Model): # name, slug, image, etc class ProductSpecialAmount(models.Model): special = models.ForeignKey(ProductSpecial, related_name='amounts', on_delete=models.CASCADE) amount = models.IntegerField() brands = models.ManyToManyField(ProductBrand, related_name='specials', blank=True) lines = models.ManyToManyField(ProductLine, related_name='specials', blank=True) admin.py class ProductSpecialAmountInline(admin.StackedInline): model = ProductSpecialAmount # fieldsets, etc @admin.register(ProductSpecial) class ProductSpecialAdmin(admin.ModelAdmin): inlines = [ProductSpecialAmountInline] # fieldsets, etc I only want users to be able to choose from brands or lines, but not both, and I would like to validate this before save and throw a validation error if necessary. My initial attempt was to just do... class ProductSpecialAmount(models.Model): # ... def clean(self): if self.brands and self.lines: raise … -
Given models relations nested 3 layers what query will return an object I can pass to Django Rest Framework model serializers
Given models related three levels deep how can I construct a query where I can pass the response to a Django Rest Framework model serializer? The code below with one layer of relationship works. Modles class SubArea(models.Model): label = models.CharField(max_length=20) fiber_switch = models.ForeignKey( 'FiberSwitch', related_name='sub_areas') class BackboneLine(models.Model): sub_area = models.ForeignKey( SubArea, related_name='backbone_lines') source = models.ForeignKey( Enclosure, related_name='backbone_lines_out') destination = models.OneToOneField( Enclosure, related_name='backbone_line_in') @property def label(self): return f'{self.source.box_number} - {self.destination.box_number}' Serializers class BackboneLineSerializer(ModelSerializer): class Meta: model = BackboneLine fields = ['label'] class SubAreaSerializer(ModelSerializer): backbone_lines = BackboneLineSerializer(many=True) class Meta: model = SubArea fields = ['label', 'backbone_lines'] Code sub_area = SubArea.objects.get(pk1) sub_area_serialzer = SubAreaSerializer(sub_area) But if I add the model BackboneLineSegments along with a serializer for it, and change the BackoneLineSerializer to handle it I get errors. Added Model class BackboneLineSegment(models.Model): location = models.LineStringField() buried = models.BooleanField(default=False) backbone_line = models.ForeignKey( BackboneLine, related_name='segments' ) New Serializer class BackboneLineSegmentSerializer(GeoFeatureModelSerializer): class Meta: model = BackboneLineSegment geo_field = 'location' fields = ['location', 'buried'] Updated BackboneLineSerializer class BackboneLineSerializer(ModelSerializer): segments = BackboneLineSegmentSerializer(many=True) class Meta: model = BackboneLine fields = ['label', 'segments'] Code sub_area = SubArea.objects.get(pk1) sub_area_serialzer = SubAreaSerializer(sub_area) This throws the following error. Got AttributeError when attempting to get a value for field segments on serializer BackboneLineSerializer. The serializer …