Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Annotation grouping in a queryset
order_list = Order.objects.filter( is_deleted=0, order_status__in=[4], order_type=0) order_list_data = order_list.annotate( customer_gross_sum=F('invoice__original_amount') - F('invoice__discount_amount')+F('invoice__tax_amount'), dcount=Count('user_id'),customer_transactions=F('invoice__transaction_invoice__transaction_amount')) print(order_list_data.values()) from the table above, the customer_transactions in the queryset is called in the column payment in the table. The second and third in the table is of the same bill with two transactions. Is it possible to bring that under one data. -
How can I get date,year and month from this created_date: "2021-09-27T06:10:07.972531Z" in react js?
I'am getting response from backend with date in this fromat created_date: "2021-09-27T06:10:07.972531Z", but I want to show such as 31 December,2020 in the UI. So is there any way to get only year,month and the day? -
Django - Does Django know the number of instances of each model?
everybody. I was wondering... Since Django does not execute the query to the database until the Queryset is evaluated : QuerySets are lazy – the act of creating a QuerySet doesn’t involve any database activity. You can stack filters together all day long, and Django won’t actually run the query until the QuerySet is evaluated. Then how MODEL.objects.get(pk=1), for example, raises DoesNotExist exception when there is no MODEL instance with pk=1, even if I stored it in a variable without printing it for example ? -
conversion of python dictionary to json types in django rest framework
This is a question of comprehension rather than code issue. I am using DRF for a year. When I learnt about serializers, it says there are two steps. For get request what serializer class do is: Converting complex datatypes like queryset into python datatype like the dictionary. Converting dictionary into json format which is sent to the api as response. I use print commands to see everything what is happening or using the shell. I can see the first step happening ie I can see the complex queryset and after serialization can see the dictionary of the queryset. But nowhere in the code I can see the second step happening. Although the json format isnt very different from the python dictionary. The only difference I see is the double quotes instead of single quote in json. But still, the conversion needs to happen. Is it happening automatically or am I missing something here?? My snippet: My prints of the queryset and serialized data: Here, the email printed is the complex data. After serialization it is converted to python dictionary. However, the JSON data coming into postman is like this. -
How to distribute self-created ads onto the django project?
In this project, I am trying to create an advertisement distribution website where users can upload their advertisements and after uploading, the back-end architecture will distribute the ads onto the website(the user does not need to do anything, automatically the ads will be distributed). I have created ad spaces in the HTML templates as you can see below. And I have stored sample ads to the table( refer Model Ad ). My question is how could I distribute those ads, saved in the table with target_url, into the ads spaces onto the whole project. I am working in Python with Django . Any suggestions would be appreciated. Thank You Below I have attached the code. HTML: <!-- Advanced CSS for displaying Ads --> <div style="background: #FFA92F; color: white; font-size: 14px; height: 75px; width: 300px;"> <marquee behavior="alternate" direction="left" scrollamount="2"><span style="float: left; font-family: Oswald, Arial; padding: 0 0 0 2px;">Order your dream blog or website design</span> </marquee> <marquee behavior="alternate" direction="right" scrollamount="2"><span style="float: right; padding: 0 2px 0 0;"> <a href="https://www.techprevue.com">CLICK HERE</a></span></marquee> <span style="background: #FFF; color: #ffa92f; float: left;">Order Now: +91-876567XXXX</span> <div style="float: right; font-size: xx-small;"> Ads by <span style="background: #FFF; color: #ffa92f;">techPrevue</span></div> </div> <br><br><br> <!-- Normalized CSS for displaying Ads --> <div … -
how to upload recorded audio by flutter_sound package to server using Dio in flutter?
I am building a chat application in Django and it has a mobile app (using Flutter) as well which consumes the RESTFUL API of the web app. The web app is completed but stuck with sending recorded audio by flutter_sound package to the server using Dio. -
django autocomplete returning empty for linked data
In my django admin app, I have a Site table with references to Countries, and to specific Regions(provinces/states). Currently, when trying to add a Site entry, the dropdown menus for countries and regions display all possible objects. I would like for the region dropdown to display only objects possible according to the previously selected Country option. For example, selecting Canada in the Country dropdown should result in only Canadian provinces being shown in the Region dropdown. To do this, I've tried the django-autocomplete-light library, according to the basic tutorials. Unfortunately, the Regions dropdown now shows the following error. Here are my model.py, form.py, and admin.py files. class Country(models.Model): country = models.CharField(max_length=200) class Region(models.Model): region = models.CharField(max_length=200) country = models.ForeignKey(Country, models.CASCADE, null=True, blank=True) class Site(models.Model): country = models.ForeignKey(Country, models.CASCADE, null=True, blank=True) region = models.ForeignKey(Region, models.CASCADE, null=True, blank=True) class TestForm(forms.ModelForm): class Meta: model = Site fields = '__all__' widgets = { 'region': autocomplete.ModelSelect2(url='sites/site', forward=('country',)) } @admin.register(Site) class SiteAdmin(autocomplete.Select2QuerySetView): form = TestForm -
How to process multiple objects at once in views.py
I'm making a function that adds the current user name by selecting the checkbox in the last column of each row and clicking the "Add Teacher" button. The code below works when only one checkbox is checked. How do I select multiple checkboxes? urls.py path('student/add_teacher/<int:id>/', views.add_teacher, name='add_teacher') views.py def add_teacher(request, id): student = Student.objects.get(pk=id) student.teacher = request.user.name student.save() return HttpResponseRedirect(f'/student_list/') student_list.html <table id="student-list" class="maintable"> <thead> <tr> <th>Name</th> <th>Age</th> <th>Sex</th> <th>Select</th> </tr> </thead> <tbody> {% for student in students %} <tr class="student"> <td>{{ student.name }}</td> <td>{{ student.age }}</td> <td>{{ student.sex }}</td> <td><input type="checkbox"></td> </tr> {% endfor %} </tbody> </table> <button type="button" class="btn btn-secondary addteacher">Update Teacher</button> student_list.js $('button.addteacher').click(function (e) { var elem = $(".maintable input:checked").parents("tr"); var studentID = elem.attr('student-id'); var updateTeacher = confirm("will you update?"); if (updateTeacher) { window.location.href = '/student/add_teacher/' + studentID + '/'; } }); The way I thought of is to create a list of selected ids with ajax and pass it to views.py . However, views.py cannot handle multiple objects because it uses object.get() . Through long-time search, we have confirmed that multiple objects can be processed at once by using a transaction. Can I use transactions? Haven't been able to fix it for several days. Please help. … -
Get the default value from a list django
I have a website with a list of status, how do I only retrieve the steps 1 when my form is submitted and store into the database? models.py class Photo(models.Model): STEP1 = "step 1" STEP2 = "step 2" STEP3 = "step 3" STEP4 = "step 4" STATUS = ( (STEP1, 'Received'), (STEP2, 'Cleaning'), (STEP3, 'Leak '), (STEP4, 'Loss Pressure Test'), ) Datetime = models.DateTimeField(auto_now_add=True) serialno = models.TextField() # serialno stand for serial number partno = models.TextField() # partno stand for part number reception = models.TextField() Customername = models.TextField() def __str__(self): return self.reception forms.py class AddForm(forms.Form): reception = forms.CharField(label='', widget=forms.TextInput( attrs={"class": 'form-control', 'placeholder': 'Enter reception number'})) partno = forms.CharField(label='', widget=forms.TextInput( attrs={"class": 'form-control', 'placeholder': 'Enter part number'})) serialno = forms.CharField(label='', widget=forms.TextInput( attrs={"class": 'form-control', 'placeholder': 'Enter Serial Number'})) Customername = forms.CharField(label='', widget=forms.TextInput( attrs={"class": 'form-control', 'placeholder': 'Enter customer name'})) class meta: model = Photo fields = ('reception', 'partno', 'serialno', 'Customername') views.py def addPhoto(request): msg = None if request.method == 'POST': form = AddForm(request.POST) if form.is_valid(): Datetime = datetime.now() reception = form.cleaned_data['reception'] partno = form.cleaned_data['partno'] serialno = form.cleaned_data['serialno'] Customername = form.cleaned_data['Customername'] # create a new MCO object with the form data form = Photo(Datetime=Datetime, reception=reception, partno=partno, serialno=serialno, Customername=Customername) form.save() context = {'form': form} return redirect('/gallery', … -
zombie django qcluster shows up as soon as I start redis broker
I am using redis request broker with django. When I run "$ python manage.py qinfo" I see a Cluster is running but Idle. I did not start this cluster. When I start a cluster I run "$ python manage.py qcluster" and I see 2 clusters with qinfo. I can kill the cluster I started with Ctrl+C but the zombie cluster remains. Power cycling dosn't help since the zombie cluster comes back to life as soon as I start redis. Any idea on how to kill the zombie cluster or remove it from redis memory so it does't come back to life? -
Is it possible to use subprocess to execute uploaded python file in django?
I want to allow my company users to upload a python script and execute it. I am using subprocess to execute script but I am getting errors saying "expected str, bytes or os.PathLike object, not InMemoryUploadedFile" def execute(request) if request.method == 'POST': if request.FILES.get('document'): file = request.FILES['document'] subprocess.run(['python', file], stdout=True) -
How to make forms to not be widespreaded in django?
I have been editing my forms, and like the idea of widget_tweaks, so tried few and like this one. But I got that my forms are widespread, apart from this I like it how it turned up. Can I make them not to be widespread? {% extends "base.html" %} {% load widget_tweaks %} {% block content %} <br/> <form method="post" novalidate> {% csrf_token %} {% for hidden_field in form.hidden_fields %} {{ hidden_field }} {% endfor %} {% if form.non_field_errors %} <div class="alert alert-danger" role="alert"> {% for error in form.non_field_errors %} {{ error }} {% endfor %} </div> {% endif %} {% for field in form.visible_fields %} <div class="form-group"> {{ field.label_tag }} {% if form.is_bound %} {% if field.errors %} {% render_field field class="form-control is-invalid" %} {% for error in field.errors %} <div class="invalid-feedback"> {{ error }} </div> {% endfor %} {% else %} {% render_field field class="form-control is-valid" %} {% endif %} {% else %} {% render_field field class="form-control" %} {% endif %} {% if field.help_text %} <small class="form-text text-muted">{{ field.help_text }}</small> {% endif %} </div> {% endfor %} <button type="submit" class="btn btn-primary">Download your template!</button> </form> <br/> {% endblock content %} -
Django IntegrityError at /accounts/signup/: NOT NULL constraint failed: accounts_subject.gender
Basically I am trying to create a user registration form with a few more fields than the default User model apparently brings. So I created another model with a 1 to 1 relationship with the Model User and this works (in django admin I can create Subjects (that's what I call this class "extended") related to some user). When I use my registration form, the idea is that a User is created (with its usual attributes: username, email, password) and also a Subject related to that User that has the rest of the attributes that I want to save (gender, level of studies, year of birth, etc) But, when using it only the User is saved in the database (the Subject is not saved) and I get the following error: IntegrityError at /accounts/signup/ NOT NULL constraint failed: accounts_subject.gender Here is my code: models.py: from django.db import models import uuid from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class Subject(models.Model): GENDER_CHOICES = ( ('M', 'Masculino'), ('F', 'Femenina'), ) EDUCATIONLEVEL_CHOICES = ( ('P', 'Primaria'), ('S', 'Secundaria'), ('T', 'Terciaria'), ('U', 'Universitaria'), ) id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=True) user = models.OneToOneField(User, on_delete=models.CASCADE) gender = models.CharField(max_length=20, choices=GENDER_CHOICES, default=None) education_level = models.CharField(max_length=20, … -
How to get the IP address from Channels (Django)?
I use Channels 3.0.4 and I use AsyncWebsocketConsumer from channels.generic.websocket import AsyncWebsocketConsumer class consumer (AsyncWebsocketConsumer): async def connect(self): ... async def disconnect(self, code): ... async def receive(self, text_data): ... How can I get the IP address in the connect function or disconnect function or receive function? -
Is it possible to return pandas null check (df.isnull().sum()) result in django and show on the screen?
I am building a website that shows the missing data statistic. I am using pandas in Django to show missing data statistics of excel files. My view.py file def missing_info(request): if request.method == 'POST': if request.FILES.get('document'): file = request.FILES['document'] df = pd.read_excel(file) missing_data = df.isnull().sum() dic_result = {'data': missing_data} return render(request, 'report.html', dic_result) return render(request, 'upload.html') Report.html file <h1> Missing Data Report </h1> {% for info in data %} {{info.0}} <br> {% endfor %} <p> I noticed that it is taking the displaying missing data space on the screen</p> I am able to return the missing data statistic to report.html but it isn't displayed on the screen. I noticed that missing data statistics displaying on the screen but blank data. website with blank data image -
Django IntegrityError manytomany field
I'm trying to implement hashtags in my django app I have a message model with a field like this hash_tags = models.ManyToManyField(HashTag, related_name='message_hash_tags') And this is the HashTag model hash_tag = models.CharField(max_length=140, primary_key=True) And I'm setting the hashtags to the message like this hash_tags_list = Functions.extract_hashtags(message["message"]) hash_tags = [HashTag.objects.get_or_create(hash_tag=ht) for ht in hash_tags_list] messageObj.hash_tags.set(hash_tags) messageObj.save() But this errors out django.db.utils.IntegrityError: insert or update on table "messaging_message_hash_tags" violates foreign key constraint "messaging_message_ha_hashtag_id_068959e9_fk_messaging" DETAIL: Key (hashtag_id)=((<HashTag: HashTag object (skills)>, True)) is not present in table "messaging_hashtag". Tho I can find the HashTag object (skills) in my messaging_hashtag table: SELECT * FROM messaging_hashtag; hash_tag ---------- skills -
How to filter ManyToManyField in serializer
In my code ServiceListSerializer(many=True, source='service_id') is giving all the services list, instead of services according to its category I have no idea how to retrieve and filter from manytomany field Heres my code: Models.py class Services(models.Model): service_id = models.AutoField(primary_key=True) parent_id = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True,related_name='sub_service') service_name = models.CharField(max_length=100) service_icon = models.CharField(max_length=500, null=True, blank=True) service_image = models.CharField(max_length=500, null=True, blank=True) service_description = models.CharField(max_length=5000, null=True, blank=True) category_id = models.ForeignKey(Category,on_delete=models.CASCADE) active_status = models.BooleanField(default=True) type = models.SmallIntegerField(blank=True, null=True) class Variant(models.Model): variant_id = models.AutoField(primary_key=True) service_id = models.ManyToManyField(Services) category_id = models.ManyToManyField(Category) variant_name = models.CharField(max_length=100) variant_icon = models.CharField(max_length=1000, null=True, blank=True) variant_image = models.CharField(max_length=1000, null=True, blank=True) variant_description = models.CharField(max_length=5000, null=True, blank=True) active_status = models.BooleanField(default=True) View.py class ServicesList(viewsets.ViewSet): def list(self, request): variant_id = request.data.get('variant_id') queryset = Category.objects.all() querysetSerializer = CategoryServiceListSerializer(queryset, many=True, context={'variant_id': variant_id}) return Response({"status": 200, "message": "Success", "data": querysetSerializer.data}) Serializer.py class CategoryServiceListSerializer(serializers.ModelSerializer): variant = serializers.SerializerMethodField() def get_variant(self, instance): variant_id = self.context.get('variant_id') if variant_id: variants = instance.variant_set.filter(pk=variant_id) else: variants = instance.variant_set.all() return VariantServiceSerializer(variants, many=True).data class Meta: fields = ("category_id", "category_name", "category_icon", "category_description", "variant") model = Category class ServiceListSerializer(serializers.ModelSerializer): class Meta: model = Services fields = "__all__" class VariantServiceSerializer(serializers.ModelSerializer): services = ServiceListSerializer(many=True, source='service_id') # services = serializers.SerializerMethodField() class Meta: model = Variant fields = "__all__" # def get_services(self, obj): # print(obj.service_id) … -
Understanding Django Forms
I am trying to learn server side development of websites. In particular I am looking at forms and acquiring user data. I am trying to learn Django but I am not sure my understanding of the flow with Django forms. Is the following correct? Django forms are a back end application which generates an html form. A user on the client side will click a button such as "Sign Up" which will then trigger a script involving Django forms. The forms module will generate an html form which will be including in the http response that is sent back to the user. Is this correct? Or do html and Django forms conflict? That is, we can only use one? I have tried reading the documentation but it is not helping me understand. TLDR: What is the flow diagram for a dynamic website where we generate forms using Django? -
Similar field to ArrayField in Django to use with SQL Server
I want to connect my Django backend to SQL Server but one of my models require a an array field like the one from PostgreSQL so is there an alternative? -
iterate horizontally through a Django QuerySet
I am working with a sql table and want to iterate through it horizontally. I am currently using the django Q library to create query sets: I am creating and filtering the QuerySets by doing : filtered_table = NewTables07.objects.filter(criterion_date & criterion_location) The model looks like: class NewTables07(models.Model): TestDate = models.CharField(max_length=200) Division = models.CharField(max_length=200) Library = models.CharField(max_length=200) ID = models.CharField(max_length=200) mono_full = models.CharField(max_length=200) mono_simple = models.CharField(max_length=200) mono_brief = models.CharField(max_length=200) mono_complex = models.CharField(max_length=200) mono_vendor = models.CharField(max_length=200) mono_asc = models.CharField(max_length=200) mono_added = models.CharField(max_length=200) class Meta: db_table = 'stat_cat1' I am aware that I can iterate through columns by doing something like: for i in filtered_table: print(i.<column title>) but if i wanted to iterate through the table horizontally, like through the headers for example : 'ID' then 'Library' 'mono_full' ... How would I go about doing that ? -
ValueError: I/O operation on closed file. when saving the qr code to database in Django
Here i want save my qr_code to database but i am facing the following error ValueError: I/O operation on closed file. def qr_code_file_name(instance, filename): return '%s/qr_codes/%s/' % (instance.client_id, filename) class ProductItems(models.Model): item_name = models.CharField(max_length=512) qr_code = models.ImageField(upload_to=qr_code_file_name, blank=True, null=True) def __unicode__(self): return self.item_name def save(self, *args, **kwargs): qrcode_img = qrcode.make(self.item_name) canvas = Image.new('RGB',(90,90),'white') draw = ImageDraw.Draw(canvas) canvas.paste(qrcode_img) fname = File('qrcode-code1.png') buffer = BytesIO() canvas.save(buffer,'PNG') self.qr_code.save(fname,File(buffer),save=False) canvas.close() -
how to verify the csrf token is working well in the browser while using django and react
I am sorry in advance if the question is more a beginner one but i have built an application with django backend and react frontend, now i am trying to implement the csrf token for the post request on the create endpoint with the codes below. getCookie.js import React from 'react'; const getCookie = (name) => { let cookieValue = null; if (document.cookie && document.cookie !== '') { const cookies = document.cookie.split(';'); for (let i = 0; i < cookies.length; i++) { const cookie = cookies[i].trim(); // Does this cookie string begin with the name we want? if (cookie.substring(0, name.length + 1) === (name + '=')) { cookieValue = decodeURIComponent(cookie.substring(name.length + 1)); break; } } } return cookieValue; } export default getCookie; CsrfToken.js import React from 'react'; import getCookie from './getCookie'; var csrftoken = getCookie('csrftoken'); const CSRFToken = () => { return ( <input type="hidden" name="csrfmiddlewaretoken" value={csrftoken} /> ); }; export default CSRFToken; Create.js import React from 'react'; import axios from "axios"; import CsrfToken from './CsrfToken'; const Create = () => { ... const options = { headers: { 'Content-Type': 'application/json', } }; const handleSubmit = (e) => { e.preventDefault(); axios.post("http://xyz/create/", fields, options) .then(response => { ... }; return ( … -
Django update_or_create raises IntegrityError within Serializer
I have the following ModelSerializer with a create method. In this method I call the model's update_or_create method. But when I do this, the serializer's validation raises the error rest_framework.exceptions.ValidationError: [{'non_field_errors': [ErrorDetail(string='The fields user_id, capacity_id must make a unique set.', code='unique')]}, {}]. I thought that since I'm using update_or_create, it would find the row that matches validated data's user_id and capacity_id, and then update that row. But the validation runs before create, and the data is not valid because of the unique constraint. So how do I ignore this constraint? class ActivatedCapacitySerializer(serializers.ModelSerializer): user_id = serializers.IntegerField(required=False) capacity_id = serializers.IntegerField(required=False) class Meta: model = ActivatedCapacity fields = ('user_id', 'capacity_id', 'active') def create(self, validated_data): activated_capacity = ActivatedCapacity.objects.update_or_create( user_id=validated_data['user_id'], capacity_id=validated_data['capacity_id'], defaults = { 'active': validated_data['active'] } ) return activated_capacity Models.py class ActivatedCapacity(models.Model): user_id = models.IntegerField() capacity_id = models.IntegerField() active = models.BooleanField(default=False) class Meta: unique_together = ('user_id', 'capacity_id',) -
dj-rest-auth, email expiration time less than one day
As title says, it's possible to set email confirmation link expire time less than one day? Specifically for dj-rest-auth so far I only found ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 90. Django password has such https://docs.djangoproject.com/en/3.2/ref/settings/#password-reset-timeout for password reset. But I cannot find anything related to email expiration from both official docs/Githubs for this simple task. -
Nginx Static Files doesn't load Django
Nginx won't load Django static files. Nginx config: upstream backend { server localhost:8000; } server { server_name wavera.ru www.wavera.ru; location / { include proxy_params; proxy_pass http://backend; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/www.wavera.ru/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/www.wavera.ru/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot location /static/ { alias /root/labelEngine/labelApp/static/; } location /media/ { alias /root/labelEngine/media/; } } server { if ($host = wavera.ru) { return 301 https://$host$request_uri; } if ($host = www.wavera.ru) { return 301 https://$host$request_uri; } listen 80 ; server_name wavera.ru www.wavera.ru; return 404; } settings.py of static files: STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, "media") MEDIA_URL = "/media/" And also urls have: + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Otherwords, i just want to turn off debug mode and make sure my website and static / media files work correctly. I try to do this by whitenoise, but its didnt support media files, so i try to set up nginx config. What i am doing wrong?