Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
502 bad gateway error with django , gonicorn in ubuntu server
i got these error 502 bad gateway when cheched error.log i got when i checked goicorn the nginex services is run but after check i got this error this is my code in nginx/site-avalable upstream keepalive-upstream { server 127.0.0.1:8000; keepalive 64; } server { listen 80; listen [::]:80; server_name qhse-erp.com www.qhse-erp.com; location / { proxy_http_version 1.1; proxy_set_header Connection ""; proxy_pass http://keepalive-upstream; proxy_redirect off; } } -
Django: objects.raw() resulting query but not records
I'm django newbie, I have one fundamental and one technical questions. I'm using Postgres DB. I used psycopg2 connection/cursor for fetching the data, there was some delay while establishing a connection. I read that, ORM takes care of low level activities such as establishing a connection, etc. If I use django, ORM will takes care of connection challenge ? 1.1. Can I expect same (low level activities) with raw() as well? objects.raw(sql) returning Query but not records from the table. I defined Student Model as below class Student(models.Model): firstname = models.CharField(max_length=100) surname = models.CharField(max_length=100) def __str__(self): return self.firstname While creating the view, def studentList(request): #posts = Student.objects.all() --> 1. working as expected (fetching all records firstname) cursor = connection.cursor() sql = "select * from api_student" cursor.execute(sql) posts = cursor.fetchone() --> 2. returning entire record #posts = Student.objects.raw(sql) --> 3. RETURNING SQL QUERY NOT RECORD FROM TABLE ??? print(posts) return render(request, 'output.html', {'posts':posts}) output: <QuerySet [<Student: Anil>]> <RawQuerySet: select * from api_student> --> this is the challenge, did I miss any ('Anil', 'kumar') -
Chart.js automatic background color selector on Django app
I'm working on a Django app with chart.js charts and I'm trying to use a function to automatically change the colors of all the labels. Although when I run the app it only colors one label and makes the other transparent. I tried changing it from labels to data and was getting the same result. It's difficult to share the code as it is pulling data from the app so I'll share what I can. Here is the random color generator code: const labels = ['Category Types']; const backgroundcolor = []; const bordercolor = []; for (i = 0; i < labels.length; i++) { const r = Math.floor(Math.random() * 255); const g = Math.floor(Math.random() * 255); const b = Math.floor(Math.random() * 255); backgroundcolor.push("rgba(" + r + ", " + g + ", " + b + ", 1)"); bordercolor.push("rgba(" + r + ", " + g + ", " + b + ", 1)"); } Here is the chart code: var categoryTypes = JSON.parse(document.getElementById('category_types').textContent) var transactionAmountSum = JSON.parse(document.getElementById('transactionAmountSum').textContent) console.log('categoryTypes', categoryTypes) console.log('transactionAmountSum', transactionAmountSum) $(document).ready(function() { var ctx = document.getElementById('myChart1').getContext('2d'); var myCategory = new Chart(ctx, { type: 'pie', data: { labels: categoryTypes, datasets: [{ label: 'Category Types', data: transactionAmountSum, backgroundColor: [backgroundcolor], borderColor: … -
Download TikTok mp4 on client-side in Django App
I am working on an app and want to download a TikTok video given a URL on the client's machine. I have tried the following to no avail. I would like to do this in as lightweight a manner as possible and with libraries that are popular and maintained, if possible. The issues I have gotten for the attempts are provided therein. Using https://github.com/davidteather/TikTok-Api While this works locally, it does not work when I deploy the application, as I get issues with the threading. I copied over the code from this library and messed around with the threading, but it still did not work fully. I would like to avoid this option as it is not super maintainable. Using requests/wget I get the following issue when trying to use wget: Error downloading video: 'ascii' codec can't decode byte 0xe2 in position 248: ordinal not in range(128) [11/Dec/2022 05:10:13] "GET /downloader/https://www.tiktok.com/@patrickzeinali/video/7143758925349784874?is_copy_url=1&is_from_webapp=v1&item_id=7143758925349784874&lang=en HTTP/1.1" 200 24 This is what the current files look like: downloader/urls.py from django.urls import re_path, path from . import views urlpatterns = [ path('<path:video_url>', views.download_video, name='download_video'), ]` downloader/views.py from django.http import HttpResponse import ENV_VARS import requests import wget def download_video(request, video_url): print(f'Received request for video at URL: {video_url}') # … -
getting Keyerror on updating nested serializer in DRF
I have two serializer AccountSerializer UserProfileSerializer. user in UserProfileSerializer is Foreingkey to AccountSerializer. When I try to update UserProfileSerializer I get key error confirm_password. That is actually validation in AccountSerializer. How to prevent this. #Serializer class AccountSerializer(ModelSerializer): confirm_password = CharField(write_only=True) class Meta: model = Account fields = ["first_name", "last_name", "email", "password", "confirm_password"] extra_kwargs = { "password": {"write_only": True}, } def validate(self, data): if data['password'] != data.pop("confirm_password"): raise ValidationError({"error": "Passwords donot match"}) return data def create(self, validated_data): user = Account.objects.create_user(**validated_data) return user class UserprofileSerializer(ModelSerializer): user = AccountSerializer() class Meta: model = UserProfile fields = "__all__" def update(self, instance, validated_data): user_data = validated_data.pop('user', None) print('user_data', user_data) account = instance.user account.first_name = user_data.get('first_name', account.first_name) account.last_name = user_data.get('last_name', account.last_name) account.email = user_data.get('email', account.email) account.save() return super().update(instance, validated_data) #Error -
How to declare type for related object in django
In views.py I am creating products based on queryset and I don't know how to assign type to wz_product to get hints of appropriate variables. product_qs: List[Product] = product.orderproduct_set.all() for product in product_qs: product_serializer = ProductModelSerializer( data={"og_product": product.wz_product.og_product.id}) In VSC it looks like this: (in the question, I changed the names of the variables to make it easier to understand) -
Django Channels await database_to_async method not working
I'm trying to build a notification application by using Django Channels. The problem I'm having is the following error: django.core.exceptions.SynchronousOnlyOperation: You cannot call this from an async context - use a thread or sync_to_async. consumers.py class NotificationConsumer(AsyncJsonWebsocketConsumer): @database_sync_to_async def get_notifications(self, user): new_messages = NotificationSerializer(Notification.objects.filter(content=1, users_notified__in=[user]), many=True) notifs = { "new_messages": new_messages } return notifs async def connect(self): user = self.scope["user"] if user: self.channel_name = user.username self.room_group_name = 'notification_%s' % self.channel_name # Error happens in the following line notification = await self.get_notifications(self.scope["user"]) print("Notification", notification) await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() await self.disconnect(401) async def disconnect(self, close_code): await self.channel_layer.group_discard( self.room_group_name, self.channel_name ) async def notify(self, event): await self.send_json(event["content"]) I have used the exact same approach when I developed a Django Channels chat application that saves messages to the database as well. When trying to convert my approach to the Notification system, it doesn't anymore. As soon as I don't await the self.get_notifications method anymore, it works but I only get back a <coroutine object SyncToAsync.__call__ at ...> -
Password field does not migrate to db
I have my user app with the following fields in its models.py file: from django.db import models from django import forms # Create your models here. class User (models.Model): name=models.CharField(max_length=50, verbose_name='Name') surname=models.CharField(max_length=50, verbose_name='Surname') username=models.CharField(max_length=50, unique=True, verbose_name='Username') password=forms.CharField(widget=forms.PasswordInput()) email=models.EmailField(unique=True, verbose_name='Email') When I do the migrations with python manage.py makemigrations does not migrate the password field, am I defining it wrong with form.CharField? -
Django - Get specific columns with get_object_or_404()
Is there a way to only get specific columns from the database using the get_object_or_404()? This is my query for getting the thesis information from my database. But I only want to return the title , author, and published date instead of all the columns from that specific thesis. details = get_object_or_404(thesisDB, slug=slug, published_status='Approved') -
scheduler library is not working with function-based view in django
`I am working on functional based view in django and I want to schedule a task for every few minutes. I am scheduling task using "schedule" library [pip install schedule]. when i am executing the task i am getting an error as : TypeError: home() missing 1 required positional argument: 'request'. If i try to pass some string in request parameter I get error as : AttributeError: 'bool' object has no attribute 'META' what shall i pass in "request" parameter ?` from django.shortcuts import render import requests import json import schedule import time def home(request): print("Scheduler working") res = requests.get("https://jsonplaceholder.typicode.com/posts").json() return render(request, "home.html", {'res':res}) schedule.every(5).seconds.do(home) #TypeError: home() missing 1 required positional argument: 'request' #schedule.every(5).seconds.do(home(request=True) #AttributeError: 'bool' object has no attribute 'META' (if try to pass some parameter such as string or bool or int) while True: schedule.run_pending() time.sleep(1) -
In django is there a way to access the selected ForeignKey field value in a ModelForm to filter another ForeignKey in the form?
In django 4.1.3 Trying to filter a ForeignKey field query using another selected ForeignKey field value in a ModelForm to limit the filter depending on the selected exhibitors corresponding id. from django import forms from .models import Entry, Exhibitor, Pen class EntryForm(forms.ModelForm): class Meta: fields = ('exhibitor', 'pen', 'class_id',) def __init__(self, *args, **kwargs): super(EntryForm, self).__init__(*args, **kwargs) # Can't figure out how to filter # Using the selected exhibitor field value self.fields['pen'].queryset = Pen.objects.filter(current_owner_id=1) # where 1 should be the exhibitor_id # using an int value for the current_owner_id works to filter the query # but don't know how to access selected field values, or would this work in a pre_save function? # tried self.fields['pen'].queryset = Pen.objects.filter(current_owner_id=self.fields['pen']) TypeError at /admin/exhibitors/entry/add/ Field 'id' expected a number but got <django.forms.models.ModelChoiceField object at 0x2b630a6b2100>. -
Django request issue - JSON parse error - Expecting value: line 1 column 1 (char 0)
I am trying to request an access token using the following function and calling to my Django backend. On the django interface I am able to get the access and refresh token. However when I try to call it through python I get the response: {'detail': 'JSON parse error - Expecting value: line 1 column 1 (char 0)'}. Also I am using the pre-built Django Token View and have not modified it. def get_authtoken(username, password): headers = {'content-type': 'application/json'} data = { "username": username, "password": password } response = requests.post('http://127.0.0.1:8000/api/token/', data=data, headers=headers) response = response.json() print(response) return response["access"], response['refresh'] At first I was getting another issue saying the content type is not allowed. I then added the headers to clear that up an now I am running into this problem. When I research the error the solutions either do not apply or do not work. Any help is appreciated. -
How to get username field automatically in Django
I am working on a Django project which is something similar to Fiverr in its working. I have used abstractuser where there is a buyer and seller. The seller creates a gig then the buyer will go through the gig before placing an order. My issue is how to get the seller and place him in the order that the buyer will create from reading the gig. Currently I am using the system whereby the buyer will have to manually choose a gig from a list, which I think is not effective. Here is my Models.py `class User(AbstractUser): is_buyer=models.BooleanField(default=False) is_seller=models.BooleanField(default=False) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='avatar.jpg', null=True, blank=True) about = models.CharField(max_length=100) def __str__(self): return self.user.username class Gig(models.Model): seller = models.ForeignKey(Profile, on_delete = models.CASCADE, null=False, blank=False) category = models.ForeignKey('Category', on_delete = models.CASCADE, null=False, blank=False) title = models.CharField(max_length=500, null=True, blank=True) description = models.CharField(max_length=500, null=True, blank=True) gig_id = models.UUIDField(default=uuid.uuid4, primary_key=True, unique=True, editable=False) created = models.DateTimeField(auto_now_add=True) def __str__(self): return self.title class Order(models.Model): buyer = models.ForeignKey(Profile, on_delete=models.CASCADE, null=False, blank=False) seller = models.ForeignKey(Gig, on_delete=models.CASCADE, related_name='+', null=False, blank=False) title = models.CharField(max_length=500, null=True, blank=True) description = models.CharField(max_length=500) amount = models.IntegerField(max_length=50, blank=False) is_ordered = models.BooleanField(default=False) order_id = models.UUIDField(default=uuid.uuid4, unique=True, db_index=True, editable=False) slug = models.SlugField(null=True) def __str__(self): … -
The right way to dynamically add Django formset instances and POST usign HTMX?
I'm making a form with a nested dynamic formset using htmx i (want to evade usign JS, but if there's no choice...) to instance more formset fields in order to make a dynamic nested form, however when i POST, only the data from 1 instance of the Chlid formset (the last one) is POSTed, the rest of the form POSTs correctly and the Child model gets the relation to the Parent model I read the django documentation on how to POST formset instances and tried to apply it to my code, also i got right how to POST both Parent and Child at the same time. For the formsets i'm making a htmx get request hx-get to a partial template that contains the child formset and that works great, the only problem is that this always returns a form-0 formset to the client side, so for the POST the data repeats x times per field and only takes the data placed in the last instance, however i tried to change the extra=int value on my formset to get more forms upright, this gave the expected result, one Child instance per form in extra=int, so my problem is up with htmx … -
Sum the values of a form and add that result to the database
I want to make a form that has 3 number radio values, supposedly look like this: And I'd like for those 3 values to sum and display the sum of those values to then save them into the database. forms.py: class FormTest(forms.Form): CHOICES = [ ('0', '0'), ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5'), ] num1 = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) num2 = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) num3 = forms.ChoiceField(widget=forms.RadioSelect, choices=CHOICES) total = num1 + num2 + num3 models.py: class Test(models.Model): num1 = models.IntegerField() num2 = models.IntegerField() num3 = models.IntegerField() class Dato(models.Model): dato = models.IntegerField() views.py: def formtest(request): """ if request.method == 'GET': return render(request, 'testform.html', { 'form': FormTest() }) else: Test.objects.create( num1=request.POST["num1"], num2=request.POST["num2"], num3=request.POST["num3"] ) return redirect('forms') """ if request.method == 'GET': return render(request, 'testform.html', { 'form': FormTest(), }) else: Dato.objects.create( dato=request.POST['dato'] ) return redirect('forms') testform.html: {% extends 'layouts/base.html' %} {% block content %} <h1>Test Form</h1> <form method="post"> {% csrf_token %} {{ form.as_p }} <button>Save</button> </form> {{ totalsum }} {% endblock %} urls.py: from django.urls import path from . import views urlpatterns = [ #path('', views.index), path('', views.index, name="index"), path('about/', views.about, name="about"), path('hello/<str:username>', views.hello, name ="hello"), path('projects/', views.projects, name="projects"), path('tasks/', views.tasks, name="tasks"), path('create_task/', views.create_tasks, name="create_task"), path('create_projects/', views.create_project, name="create_projects"), path('formtest', views.formtest, … -
How to update Django custom dashboard
I am building a custom dashboard that will only be accessible to the support team of a company. These support teams will receive complaints from a contact form but we want to be able to indicate each complaint that has been resolved from the dashboard as resolved after being attended to. Therefore, I created a field of choices (pending and resolved) which I named status. This field is not exposed to the user in the contact form and on the backend, it's 'pending' by default. See the contact model as shown below class Contact(models.Model): STATUS_CHOICE = ( ("1", "Pending"), ("2", "Resolved"), ) name = models.CharField(max_length=100) phone = models.CharField(max_length=15) email = models.EmailField(max_length=254) subject = models.CharField(max_length=100) status = models.CharField(choices=STATUS_CHOICE, default="1", max_length=50, null=True, blank=True) created = models.DateTimeField(auto_now_add=True) body = models.TextField() class Meta: ordering = ["-created"] verbose_name_plural = "Contacts" def __str__(self): return f"Message from: {self.name}" see my forms.py: class ContactForm(forms.Form): name = forms.CharField(max_length=100, required=True) phone = forms.CharField(max_length=15, required=True) email = forms.EmailField(max_length=100, required=True) subject = forms.CharField(max_length=100, required=True) body = forms.CharField(required=True, label='Message', widget=forms.Textarea()) class Meta: model = Contact fields = ['name', 'phone', 'email', 'subject', 'body'] captcha = ReCaptchaField(widget=ReCaptchaV2Checkbox) The intent of the view below is to ensure that all users that contact the company using the … -
Django DeleteView SuccessMessageMixin -- how to pass data to message?
I am using SuccessMessageMixin on a CreateView and DeleteView. In the CreateView, I can send the book title to the success_message, like so: success_message = "%(title)s added successfully" Which correctly flashes "Great Expectations added successfully" on the success url. But in DeleteView, I can't access the title. I can send a generic message saying "book deleted", but I can't send a message saying "Great Expectations has been deleted". Is there a way that I can pass info about what's being deleted to the success_message? -
Groupby using Django's ORM to get a dictionary of lists between two models
I have two models, User and Gift: class User(models.Model): name = models.CharField(max_length=150, null=True, blank=True) ... class Gift(models.Model): user = models.ForeignKey( "User", related_name="users", on_delete=models.CASCADE, ) ... Now I want to create a dictionary of lists to have a list of gifts for every user, so that I can lookup pretty fast the ids of gifts that some users have, in a for loop, without having to query the database many times. I came up with this: from itertools import groupby gifts_grouped = { key: [v.id for v in value] for key, value in groupby(gifts, key=lambda v: v.user_id) } Now every time I wish to lookup the gifts of a user, I can simply do: gifts_grouped[id_of_a_user] And it'll return a list with ids of gifts for that user. Now this feels like a Python solution to a problem that can easily be solved with Django. But I don't know how. Is it possible to achieve the same results with Django's ORM? -
Google chart not showing up on Django
so, I'm sending this data to the frontend from my view: data = [["Name", "Ammount"], ["x", 0], ["y", 2], ["z", 1]] And I'm trying to show this as a bar graph to my user, but nothing is showing up (literally, It's blank where the graphic was supposed to be). My html looks like this: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no" /> <meta name="description" content="" /> <meta name="author" content="" /> <!-- Favicon--> <link rel="icon" type="image/x-icon" href={% static "assets/icon.ico" %} /> <!-- Core theme CSS (includes Bootstrap)--> <link href={% static "css/styles.css" %} rel="stylesheet" /> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <script type="text/javascript"> google.charts.load('current', {'packages':['bar']}); google.charts.setOnLoadCallback(drawChart_decision_type); function drawChart_decision_type() { var data3 = google.visualization.arrayToDataTable({{ my_data|safe }}); var options3 = { chart: { title: 'Stuff', subtitle: 'Test', }, backgroundColor: '#FFFFFF', bars: 'horizontal' // Required for Material Bar Charts. }; var chart3 = new google.charts.Bar(document.getElementById('barchart_materia')); chart3.draw(data3, google.charts.Bar.convertOptions(options3)); } </script> </head> <body> <div class="card_view"> <div id="barchart_material" style="width: 700px; height: 300px;"></div> </div> <!-- Bootstrap core JS--> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js"></script> <!-- Core theme JS--> <script src={% static "js/scripts.js" %} ></script> </body> </html> There are other things on my html code, but nothing that comes to mind as important. Just some hyperlinks that … -
How can I authenticate a user in a FastAPI application using Django's user authentication?
I have a userbase in a Django application and I've created a separate FastAPI application that will live on another server. What I would like to do is have users authenticate on the FastAPI application with their Django credentials. I've followed the FastAPI security documentation to at least get the ground work setup for OAuth2. Looking in that documentation they explicitly provide tips that this setup allows for reading and verifying passwords created by Django (First tip in that link). However, I'm failing to find further resources on how to set that up in a complete loop. Do I need to configure my Django application to also utilize OAuth2 or is their default authentication sufficient? I assume the FastAPI app would have to send a request over to the Django app OR have access to the Django database in order to make the verification. But I'm not quite sure on the proper(secure) steps to implement. Any resources or guidance on how to implement this is greatly appreciated. -
Bootstrap-select not working with HTMX partials
I am trying to use Bootstrap-select with HTMX partials in Django. When a specific element is changed, htmx will return a partial html containing only the dropdown, such as: <select id="myDropdown" class="selectpicker"> <option>Mustard</option> <option>Ketchup</option> <option>Barbecue</option> </select> When loading the main page initially which contains the CDNs alongside myDropdown, selectpicker works fine. However, later when myDropdown gets returned by HTMX, selectpicker doesn't work, getting a display: None !important. This behaviour is exactly as if when rendering the partial html, the CDNs are not available for usage. If instead of using class="selectpicker I use $(function(){ $('#myDropdown').selectpicker();}); it does work. The problem now is that there is a second where myDropdown isn't styled at all, before the JS function kicks in. Does anyone know how to fix this problem or bypass it in a clever way? -
How to use RabbitMQ in production with Kubernetes?
the question may be very simple but still I couldn't find the answer. I am currently developing an application with Django. In this project, I have consumer.py and producer.py files. I need to run consumer.py separately. How can I handle this in production with Kubernetes? Do I need to create a separate service for the consumer? But that doesn't make much sense. Can someone provide information on this? -
Change field value in clean() after negative validation
I have a problem that I don't know how to solve. I don't know if that's even possible :( I have a form that has four fields for simplicity (check, select, time1, time2). When the checkbox is active, the time field is displayed, otherwise select (using JS). class Form(forms.Form): check = forms.BooleanField(required=False, initial=False, widget=forms.CheckboxInput(attrs={'style':'width:20px;height:20px;'})) select = forms.ChoiceField(choices=[], required=False) time1 = forms.TimeField(required=False) time2 = forms.TimeField(required=False) def __init__(self, *args, **kwargs): select = kwargs.pop('select', None) super(Form, self).__init__(*args, **kwargs) self.fields['select'].choices = select def clean(self): cleaned_data = super(Form, self).clean() time1 = cleaned_data.get("time1") time2 = cleaned_data.get("time2") select = cleaned_data.get("select") check = cleaned_data.get("check") if check: if time1 is None or time2 is None: raise forms.ValidationError( {'time1': ["error!", ], 'time2': ["error!", ]} ) else: if select is None: raise forms.ValidationError( {'select': ["error!", ]} ) I don't know how to change the value of the check field to True when the time fields are not filled.I can't use cleaned_data["check"] = True with return because it won't throw an exception -
Can't pass project ID to function
I have the below view: def gdpr_status(request, orgid, pid, status): user = request.user if people.objects.filter(orgid=org.objects.get(orgid=orgid), personid=user).count() > 0: t = project.objects.get(projectid=project.objects.get(projectid=pid), orgid=org.objects.get(orgid=orgid)) t.status = status t.save() url_to_redirect = '/projects/'+orgid return redirect(url_to_redirect) and the below URLs path('gdpr_status/<orgid>/<pid>/<status>', views.gdpr_status, name='gdpr_status'), when I pass the URL 'http://localhost:8082/gdpr_status/1/5/rejected', I get the below error: Field 'projectid' expected a number but got <project: project object (5)>. I don't understand because the project ID is project 5, i'm not passing an object, I am passing an ID for the record I want to update. Can anyone help me please? -
Factory-boy fuzzy DateTimeField always the same date when using create_batch
I am using factory-boy for creating instances of a Django model, and I am always getting the same value returned when using factory.fuzzy.FuzzyDateTime. Minimal example: # factory class class FooFactory(DjangoModelFactory): class Meta: # models.Foo has a dt_field that is a DateTimeField model = models.Foo # creation of object, in unit tests # I can't move the dt_field declaration # into the factory definition since different # unit tests use different start / end points # for the datetime fuzzer now = datetime.datetime.now(tz=pytz.timezone("America/New_York")) one_week_ago = now - datetime.timedelta(days=7) FooFactory.create_batch( 10, dt_field=factory.fuzzy.FuzzyDateTime( start_dt=one_week_ago, end_dt=now ) ) When inspecting the Foo models after factory creation, the dt_field has the same date: >>> [r.dt_field for r in Foo.objects.all()] >>> [datetime.datetime(2022, 12, 10, 20, 15, 31, 954301, tzinfo=<UTC>), datetime.datetime(2022, 12, 10, 20, 15, 31, 961147, tzinfo=<UTC>), datetime.datetime(2022, 12, 10, 20, 15, 31, 967383, tzinfo=<UTC>), ...]