Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Postgres database empty when deploy updates using caprover and wagtail
I'm having an issue that whenever I deploy an update I find my database is empty. I'm using wagtail and any post I created is gone when I deploy an update. I'm running caprover on a VPS on which I deploy my django/wagtail project and have a hosted postgres database that the django project connects to. Also using S3 for static and media storage. I'm finding when I deploy an update every change I have made to the site is gone. I cant quite figure out why. Caprover uses my dockerfile to rebuild the container, perhaps this flushes and rebuilds the datbase? When I connect my dev environment to the same database I don't see the same database items (blog posts) that I created on the production environment side. Obviously I'd like to keep the database entries I create and for them not to get erased when I deploy. I also don't understand why the dev & production environments have their own data, I would have thought if I create a post on one then it'd show on the other. What's gone wrong? -
What is the problem if str:slug is used in django urls?
Hey guys I am building a website with django and I have to use slugs. Model and URL look like this Model slug = models.SlugField(null=False, allow_unicode=True, unique=True) URL urlpatterns = [ path('selectlanguage', views.selectlanguage, name='selectlanguage'), path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path(_('product/<str:slug>/'), views.product_detail, name='product_detail'), prefix_default_language=False, )+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When I used slug:slug in urls it doesn't let me change language between slugs it gives me "Reverse" error. But str:slug gives me no problem. My question is, is there any problem of using str:slug over slug:slug that can cause SEO or other problem to the website? I want to know if it causes any issue. Thank you in advance! -
Commit SQL even inside atomic transaction (django)
How can I always commit a insert even inside an atomic transaction? In this case I need just one point to be committed and everything else rolled back. For example, my view, decorator contains with transaction.atomic() and other stuffs: @my_custom_decorator_with_transaction_atomic def my_view(request): my_core_function() return ... def my_core_function(): # many sql operations that need to rollback in case of error try: another_operation() except MyException: insert_activity_register_on_db() # This needs to be in DB, and not rolled back raise MyException() I would not like to make another decorator for my view without transaction atomic and do it manually on core. Is there a way? -
"GET /store/hello/ HTTP/1.1" 405 0 with Class-Based-Views (Django)
I use Class-Based-Views with "post" method as shown below: # "store/views.py" from django.shortcuts import render from django.views import View class Hello(View): # Here def post(self, request): return render(request, 'store/index.html') Then, this is "urls.py" below: # "store/urls.py" from django.urls import path from . import views app_name = "store" urlpatterns = [ path("hello/", views.Hello.as_view(), name="hello"), ] Then, I got this error below: Method Not Allowed (GET): /store/hello/ Method Not Allowed (GET): /store/hello/ Method Not Allowed: /store/hello/ Method Not Allowed: /store/hello/ [03/Aug/2022 22:18:45] "GET /store/hello/ HTTP/1.1" 405 0 So, are there any ways to solve this error? -
How to close connection websocket where user going to another url
So, I Have django app with traffic.py to send data to client (traffic.html) class ClientTraffic(WebsocketConsumer): def connect(self): self.accept() # LOOP here for send traffic when current url is x output = item.generateTraffic() u = float(output['tx-bits-per-second'])/1000000, d = float(output['rx-bits-per-second'])/1000000, self.send(json.dumps({ 'upload': '{:.2f}'.format(u[0]), 'download': '{:.2f}'.format(d[0]), })) sleep(1) My Question is, how I can loop send message to client while the client is in that current url (ex: /traffic/), so when client is change current page (close or go to another path) the websocket connection is close. -
Unable to retrieve Category name using templates in Django
I am working on a Django project and I want to retrieve the category name in my template like Adventure, Hiking.. but instead, it's displaying ids of the category like 1,2,3. Instead of displaying the name of the category, it's displaying me the id of that category. Can someone help me out with this? {% for data in tourData %} {{data.category}} {% endfor %} models.py class Tour(models.Model): category_choices=[('1','Adventure'),('2','Trekking'),('3','Hiking')] category=models.CharField(max_length=1,choices=category_choices,default='1') view.py def recommendations(request): if request.method=='POST': contents=Tour.objects.all() category1= request.POST['category'] #Retrieves the category entered by the user category2=request.POST['place'] tourData = Tour.objects.all().filter(category=category1,place=category2).order_by('-rating').values() context={ 'tourData':tourData } return render(request,"base/recommendations.html",context) else: tourData=Tour.objects.all().order_by('-rating').values() context={'tourData':tourData } return render(request,"base/recommendations.html",context) -
How do I read file data from a method of a FileField subclass in Django?
I'm making a custom field in Django: from mysite.data_parsers import get_csv_data_as_dict from mysite.validators import csv_file_validator from django.db import models class CSVFileField(models.FileField): default_validators = [csv_file_validator] def get_data_as_dict(self): # How do I read the file data here? data = self.? return get_csv_data_as_dict(data) How do I read the filedata in the method? -
unexpected keyword argument 'timeout' on Celery/Redis run on Django
I'm trying to set a environment on AWS (identical to another env I have that runs Celery perfectly) but I'm having this issue when I run celery -A core worker --loglevel=INFO [2022-08-03 12:59:06,633: CRITICAL/MainProcess] Unrecoverable error: TypeError("wrapped_func() got an unexpected keyword argument 'timeout'") I've already tried to upgrade and downgrade celery/redis/kumbu versions and nothing works. I oppened a python shell on this EC2 and tested the Redis connection and its working redis_client = redis.Redis(host=settings.REDIS_URL, port=6379) redis_client.set('key', 'value', nx=True, ex=5) I don't know what am I missing here.. My versions are celery==5.2.7 Django==3.1 django-celery-beat==2.3.0 kombu==5.2.4 redis==4.3.4 pip==22.1.2 setuptools==58.0.0 -
django - track data in formset which haven't been changed
I've created UpdateView with formset. The point is one of field in each formset should be filled after post. this field is calculated in function based on values from main form and some from formset but only when user clicks specific button in template. The user doesn't have to change anything in formset. It's not allowed. I've got code as folows: class DocUpdateView(UpdateView): model = Doc form_class = NewDocForm template_name = 'addatts.html' def get_success_url(self): return reverse('doc_detail', kwargs={'pk': self.object.doc_pk}) def get_context_data(self, **kwargs): context = super(DocUpdateView, self).get_context_data(**kwargs) if self.request.POST: context['form'] = NewDocForm(self.request.POST, instance=self.object) context['formset'] = MyModelFormSet(self.request.POST, instance=self.object) else: context['form'] = NewDocForm(instance=self.object) context['formset'] = MyModelFormSet(instance=self.object) return context def post(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) formset = MyModelFormSet(self.request.POST, instance=self.object) print(f'formset valid: {formset.is_valid()}') if form.is_valid() and formset.is_valid(): return self.form_valid(form, formset) else: return self.form_invalid(form, formset) def form_valid(self, form, formset): self.object = form.save(commit=False) self.object.save() instances = formset.save(commit=False) print(instances) if 'sub_butt_1' in self.request.POST: for instance in instances: # here I wanted do logic with calculations instance.save() return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form, formset): return self.render_to_response(self.get_context_data(form=form,formset=formset)) Howewer every time I print 'intances' there is only emply list. What am Idoing wrong? -
Redis SADD multiple workers
I am using Redis server version 7.0.0 with Django-Redis. I have multiple workers in production and plan to use Django Redis's get_redis_connection.sadd to add values to a Set() in Redis. When multiple workers do that in Production, will data be lost due to two workers executing simultaneously? I read that Redis's I/O is single-threaded before version 6.0; since I am using 7.0 (I/O multi-threaded), can concurrency issues/race conditions exist? -
Access Django ModelChoiceField form field value inside __init__
I would like to make the certain field in my formset read-only once the value has been chosen. Kind of like this: class MyModelForm(forms.ModelForm): class Meta: model = MyModel fields = '__all__' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.fields["my_field"].value is not None: self.fields["my_field"].disabled == True Except ModelChoiceField object doesn't have an arguement value and I am not even sure __init__ it is the right place to try access value of a formmset form's field. -
I want to Compare two tables Column (Table1 - Balance_sheet, Table2- Account_list) (Column-split,column-account) and get the similar data in django
class Balance_Sheet(models.Model): #name of the table # date = models.DateField() # Name of the column # transaction_type = models.CharField(max_length=100,blank=False) # num = models.IntegerField() name = models.CharField(max_length=100,blank=True) # description = models.CharField(max_length=100,blank=True) split = models.CharField(max_length=100,blank=False) # class Meta: # abstract : True class Account_List(models.Model): account = models.CharField(max_length=100,blank=True,null=True) type = models.CharField(max_length=100,blank=True, null=True) split =models.ForeignKey(Balance_Sheet,null=False, default=True,on_delete=models.CASCADE) def str(self): return 'Account : {0} Type : {1} '.format(self.account,self.type) def DisplayUVL(request): # Excel page changes Ven_list = Balance_Sheet.objects.filter(account_list__isnull=True).values_list('split', flat=True) print("SQL Query:",Ven_list.query) context = { 'items': Ven_list # 'header': 'Vendor List' } return render(request, 'services2.html', context) -
how to convert and save String to float field without rounding it in Django
I have a value of the string that is like 30.72044543304425 and am saving it to a FloatField as a float. example my_string = "30.72044543304425" object = something.objects.get(id=123) object.myFloatField = float(my_string ) object.save() but the result is 30.7204454330443 As you see the number has been rounded ..how to avoid this? -
Azure Batch OutputFiles upload from all compute nodes
I have a mpi-based task, where each thread writes files on 'working-directory' for each compute node on Azure-Batch. The task is configured to upload result (files) to my storage account. But only the files on the master node are uploaded to storage. I want to know, how can I make all the nodes to upload files to my storage account ? Is there any intermediate way to copy the files on to the files from the slave nodes to the master node and upload to storage account ? -
Can I use the current logged in user in models.py?
What I have: The default django User model with an attached Profile model that, amongst others, contains a ForeignKey to an Office model. So every user in my application is tied to a specific office. And in each office there are several Shifts. models.py: class Profile(models.Model): id = models.AutoField(primary_key=True) user = models.OneToOneField(User, on_delete=models.CASCADE) office = models.ForeignKey(Office, on_delete=models.RESTRICT) class Office(models.Model): id = models.AutoField(primary_key=True) short_name = models.CharField(max_length=3, default='FRA', null=True, unique=True) long_name = models.CharField(max_length=10, default='Frankfurt', null=True, unique=True) class Shift(models.Model): id = models.AutoField(primary_key=True) office = models.ForeignKey(Office, on_delete=models.RESTRICT) short_name = models.CharField(max_length=5, default="") long_name = models.CharField(max_length=20, default="") What I am trying to do: Now, in my CreateView I want to limit the available choices in the "shift" field to the ones attached to the office of the current logged in user. I thought about using the limit_choices_to option of ForeignKey, but I can't get my head around how to access the user information within a model? Something like class Shift(models.Model): id = models.AutoField(primary_key=True) office = models.ForeignKey(Office, on_delete=models.RESTRICT, limit_choices_to={'office': ???}) short_name = models.CharField(max_length=5, default="") long_name = models.CharField(max_length=20, default="") -
Error with Next.js getStaticPaths or getStaticProps in docker build process
I'm trying to launch my first devPortfolio site with Next.js and django. Basically, I have getStaticPaths or getStaticProps in my pages/__ files with such export const getStaticPaths = async () => { // prefetch the routes const res = await fetch("http://backend:8000/api/project/projects"); const project = await res.json(); const paths = projects.data.map((project) => ({ params: { slug: project.slug, }, })); return { paths, fallback: "blocking", }; }; and this works when I 'npm run build' in my local system but when I 'docker compose build' it throws an error #0 15.46 > Build error occurred #0 15.46 FetchError: request to http://backend:8000/api/blog/posts failed, reason: getaddrinfo EAI_AGAIN backend #0 15.46 at ClientRequest.<anonymous> (/frontend/node_modules/next/dist/compiled/node-fetch/index.js:1:64142) #0 15.46 at ClientRequest.emit (node:events:527:28) #0 15.46 at Socket.socketErrorListener (node:_http_client:454:9) #0 15.46 at Socket.emit (node:events:527:28) #0 15.46 at emitErrorNT (node:internal/streams/destroy:157:8) #0 15.46 at emitErrorCloseNT (node:internal/streams/destroy:122:3) #0 15.46 at processTicksAndRejections (node:internal/process/task_queues:83:21) { #0 15.46 type: 'system', #0 15.46 errno: 'EAI_AGAIN', #0 15.46 code: 'EAI_AGAIN' #0 15.46 } I'm assuming that during the build process, it has to fetch data from my django backend but I have no idea how, since running it as usual 'py manage.py runserver' would only be in my local desktop network, NOT accessible for docker. HOW can I … -
Django Rest Framework: Unit testing SyntaxError: invalid syntax [closed]
I want to implement a Unit test using APITestCase for the application API's. I've tried to do testing but I'm not sure whether I'm on the right track. It is giving me error: ERROR: myapp.tests (unittest.loader._FailedTest) ImportError: Failed to import test module: myapp.tests Traceback (most recent call last): File "/usr/lib/python3.8/unittest/loader.py", line 436, in _find_test_path module = self._get_module_from_name(name) File "/usr/lib/python3.8/unittest/loader.py", line 377, in _get_module_from_name import(name) File "/home/naveen.p@ah.zymrinc.com/Desktop/drf/otb/myapp/tests.py", line 14 User.objects.create(email:"naveen@example.com",name:"Naveen",contact_number:"9090909098",gender:"0",address:"jaipur",state:"Rajasthan",city:"Jaipur",country:"India",pincode:"302016",dob:"07-07-1920",password:"123456",password2:"123456") ^ SyntaxError: invalid syntax Ran 1 test in 0.000s FAILED (errors=1) models.py import email from pyexpat import model from django.db import models from django.conf import settings from django.db.models.signals import post_save from django.dispatch import receiver from django.contrib.auth.models import ( BaseUserManager, AbstractBaseUser) GENDER_CHOICES = ( (0, 'male'), (1, 'female'), (2, 'not specified'),) class UserManager(BaseUserManager): def create_user(self, email, name,contact_number,gender,address,state,city,country,pincode,dob ,password=None, password2=None): """ Creates and saves a User with the given email, name and password. """ if not email: raise ValueError('User must have an email address') user = self.model( email=self.normalize_email(email), name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, pincode=pincode, dob=dob, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, email, name,contact_number,gender,address,state,city,country,pincode,dob , password=None): """ Creates and saves a superuser with the given email, name and password. """ user = self.create_user( email, name=name, contact_number=contact_number, gender=gender, address=address, state=state, city=city, country=country, … -
Django model inheritance - creating child objects based on parent instance
I am using Django 4.0 I have the following models: class Parent(models.Model): # fields ommitted for the sake of brevity pass class Child(Parent): child_only_field = models.CharField(max_length=64) code p = Parent.objects.create(**fields_dict) c1 = Child.objects.create(child_only_field='Hello 123', p) # Obviously won't work # c2 = ... Is there a way to create child objects from an instance of a parent (without manually "unpacking" the fields of the parent)? -
Confirmation button on save button like delete already has
I want to modify Django admin interface. There is delete button already has a confirmation page. But I want to add this confirmation to save or change buttons. Actually not exactly the same delete button. I want to change default admin buttons like this JS or I want to add JS to admin buttons. <input type="submit" onclick="linkSubmit('http://www.google.com')" value="Submit"> <p id="demo"></p> <script> function linkSubmit(link) { let text = "Press a button!\nEither OK or Cancel."; if (confirm(text) == true) { window.location.href = link; } else { } document.getElementById("demo").innerHTML = text; } </script> -
How replace webpack on Esbuild?
I have a project on React and Django. And we using Webpack. I read that Esbuild is really faster that Webpack. Which way do I need to go to make the right substitution? What clarifying questions should I ask to solve this kind of problem? Thanks! -
Cannot Render in Template from Django Database
i cannot render information in my template from django database. i want to get Slider Image With Text but it's not rendering on my template. Views.Py def slider(request): Slider_item = Slider.objects.get() context = { 'SS' : Slider_item } return render(request, 'base.html', context=context) base.html <p>{{ SS.Slider_Ttitle }} </p> models.py class Slider(models.Model): Slider_Image = models.ImageField(upload_to='static/images/sliders/', default='') Slider_Ttitle = models.CharField(max_length=50, default='Slider Text') def __str__(self): return self.Slider_Ttitle class Meta: managed = True verbose_name = 'სლაიდერი' verbose_name_plural = 'სლაიდერები' -
Recommend way and maximum byte size for requests in a data-intensive Django application
I am working on an application that handles datasets with varyiing sizes. For POST requests I do a check on the attached .csv-File for byte size like and if its over 10mb, I return a BAD_REQUEST response: MAX_FILESIZE_BYTES = 10485760 # 10mb csvFile = request.data["file"] if(csvFile.size > MAX_FILESIZE_BYTES): raise Exception("File size over "+str(MAX_FILESIZE_BYTES)) except Exception as e: return Response("Uploaded File bigger than maximum filesize", status=BAD_REQUEST, exception=True) Is this the recommend way of handling files too big? And is 10mb a reasonable size, or could my application handle much bigger sizes? I use rest_framework, atomic transactions with postgresql and I dont expect to have more much than 50 users at the same time. -
I want to remove case insensitivity in search functionality jquery
const query = $(this).val(); console.log(query); $('.wilipedia-item').each(function () { let title = $(this).find('.wilipedia-item__title h5').text().toLowerCase(); let description = $(this).find('.wilipedia-item__desc').text().toLowerCase(); if (title.includes(query) || description.includes(query)) { title = title.replace(query, '<span class="highlight">' + query + '</span>'); description = description.replace(query, '<span class="highlight">' + query + '</span>'); $(this).find('h5').html(title); $(this).find('.wilipedia-item__desc').html(description); } $(this).toggle($(this).find('h5, .wilipedia-item__desc').text().includes(query)) }); }); I have this code I applied search functionality on title and description but its like I have to convert it in small or capital letter then it works but I want to remove case insensitivity using index of but i am confused how to do that? Is there any one can help me -
Django variable doesn't get passed to template
Basically, what happens here, the list user_data doesn't get passed to the template, I can't figure out why. Does anyone have any ideas please? When I use the search bar I just get the else condition from the template, and it never shows any variable. I also tried to create different variables to pass to the template, but none of them got passed for some reason... Thank you very much! This is in my views.py @login_required(login_url='login_user') def profiles(request): context = {} if request.method == "POST": data = request.POST.get('search_input') if len(data) > 0: username_result = NewUser.objects.filter(username__icontains=data).distinct() email_result = NewUser.objects.filter(email__icontains=data).distinct() user_data = [] for account in username_result: user_data.append((account, False)) context['usernames'] = user_data return render(request, "profiles/search_user.html", context) else: return render(request, "profiles/profiles.html") return render(request, "profiles/profiles.html") Then my template look like this: {% extends 'profiles/base.html' %} {% block title %}One For All{% endblock %} {% load static %} <!-- importing css file --> {% block style %}<link rel="stylesheet" type="text/css" href="{% static 'css/search_user.css' %}">{% endblock %} {% block content %} <!-- navigation bar --> <div class="navBar"> <!-- logo and logo spacers --> <div class="logo_spacer"></div> <div class="logo"></div> <!-- Sign Up Button --> <a class="homeBtn" href="{% url 'profiles' %}">Home</a> {% if is_self %} <a class="settingsBtn" href="{% url 'settings' … -
Design users with multiple accounts i.e (Instagram) in Django
Im Preplanning for project where users have multiple accounts each same as like instagram users with multiple accounts. I need to select any of the account after login token received from JWT. and when i calling api my views should display data based on the particular account. My question is, 1.How to store the choice of the user in backend after login? 2.If i store using sessions then is that data will be private to the particular user or if i login with other user on the same tab, same session data from previous user is still visible to this user also right? Please help on this. Thanks in advance.