Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to stop a cascade delete causing a circular update error in Django?
I've got two models with an FK relationship between them. There is also a post_save and post_delete signal handler that updates some derived field based on the linked children. class Parent(models.Model): derived_field = models.CharField(...) class Child(models.Model): parent = models.ForeignKey(Parent, on_delete=CASCADE) def update_parent(sender, instance, **kwargs): instance.parent.derived_field = get_derived_field_value(instance) instance.parent.save() post_save.connect(update_parent, sender=Child) post_delete.connect(update_parent, sender=Child) This all works fine, until you delete a parent instance that has linked child instances. At which point we run into an IntegrityError since our post_delete signal handler tries to save an instance that is also being deleted in the same transaction. Worth noting: The derived field is being generated for performance reasons - and is actually a MultiPoint geo django field that is then used in later select queries both within and outside of the ORM, I don't want to remove it! One option is to have it not cascade delete, but make the parent field nullable and then somehow delete those instances separately. Any other options? -
Django dev server extremely slow
We have an app that works perfectly fine on production but very slow on the dev machine. Django==2.2.4 I'm using Ubuntu 20.04 but other devs are using macOS and even Windows. Our production server is a very small compared to the dev laptops (it works very slow on every dev environment, we are 5 developers). The app makes several request since it's a Single Page application that uses Django Rest Framework and React.js in the front-end. We have tried different databases locally (currently postgresql, tried MySQL and sqlite3), using docker, no docker, but it does not change the performance. Each individual request takes a few seconds to execute, but when they go all toghether the thing gets very slow. As more request are executed, the performance starts to drop. It takes the app between 2/3 minutes to load in the dev environment and in any production or staging environment it takes little above 10 seconds. Also tried disabling DEBUG in the back and front-end, nothing changes. It is my opinion that one of the causes is that the dev server is single thread and it does not process a request until the previous is finished. This makes the dev environemnt … -
Gunicorn/Django/Nginx - 502 Bad Gateway Error when uploading files above 100 MB
I have been stuck on this error for a week. I am officially at a loss with this one. I have a React/Django web app where users can upload audio files (.WAV) (Via react Dropzone). The React and Django is completely separated into a frontend/ and backend/ folder, communicating via fetch() calls. For some reason, I am able to upload files less than 100 MB, but if I upload a file larger, for example, 180 MB, Nginx errors with the following: 2020/07/14 02:29:18 [error] 21023#21023: *71 upstream prematurely closed connection while reading response header from upstream, client: 50.***.***.***, server: api.example.com, request: "POST /api/upload_audio HTTP/1.1", upstream: "http://unix:/home/exampleuser/AudioUploadApp/AudioUploadApp.sock:/api/upload_audio", host: "api.example.com”, referrer: "https://example.com/profile/audio/record" My Gunicorn error log does not show any errors. I can see each of the 5 workers starting, but there is no WORKER TIMEOUT errors or anything that I can see. My guniocorn.service file: [Unit] Description=gunicorn daemon After=network.target [Service] User=exampleuser Group=www-data WorkingDirectory=/home/exampleuser/AudioUploadApp/Backend ExecStart=/home/exampleuser/virtualenvs/uploadenv/bin/gunicorn --access-logfile "/tmp/gunicorn_access.log" --error-logfile "/tmp/gunicorn_error.log" --capture-output --workers 5 --worker-class=gevent --timeout=900 --bind unix/home/exampleuser/AudioUploadApp/AudioUploadApp.sock AudioUploadApp.wsgi:application --log-level=error [Install] WantedBy=multi-user.target server { server_name api.example.com; location / { include proxy_params; proxy_pass http://unix:/home/exampleuser/AudioUploadApp/AudioUploadApp.sock; client_max_body_size 200M; } location /static { autoindex on; alias /home/exampleuser/AudioUploadApp/Backend/static/; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # … -
MultiValueDictKeyError at /users/signup/ "password_1"
I am learning django, And while creating the user. I got this error MultiValueDictKeyError at /users/signup/ "password_1", Please help me views.py, The last defined function, at passwords1. This is the place where it is pointing the error. from django.shortcuts import render from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User from django.http import HttpResponseRedirect from django.urls import reverse # Create your views here. def userslogin(request): if request.method == "POST": username = request.POST["username"] password = request.POST["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return HttpResponseRedirect(reverse("index")) else: return render(request, "users/login.html", { "message": "Invalid credentials." }) else: return render(request, "users/login.html") def userlogout(request): logout(request) return render(request, 'users/logout.html',{ "message": "Succesfully logged out." }) def usersignup(request): if request.method == "POST": username = request.POST["username"] email = request.POST["email"] password_1 = request.POST["password_1"] password_2 = request.POST["password_2"] myuser = User.objects.create_superuser(username = username,password = password_1, email=email) if myuser is not None: myuser.save() return HttpResponseRedirect(reverse("main")) else: return render(request, "users/login.html", { "message": "Invalid credentials." }) else: return render(request, "users/signup.html") urls.py Nothings is wrong here, But still, I have included this file from django.urls import path, include from . import views import blog urlpatterns = [ path("", blog.views.main, name="index"), path('login/',views.userslogin, name = 'login'), path('logout/',views.userlogout, name = 'logout'), path('signup/',views.usersignup, name … -
Rest API query for Django and js
For example I am making a Instagram clone , if a user send me message how will I get it , I mean do I have to run a while True loop and make infinite fetch calls in it or is there any other way of getting stuff done ;btw using a REST_API in python And Django -
Problems with django types
When i want to save this django file: from django.urls import path import django.views urlpatterns = [ path('index/', views.index, name='main-view') I get an error : "Name 'views' is not defined" If i change "import django.views" for "from . import views" I get an error: "Attempted relative import with no known parent package" I have init.py file with command "import django.views". If I change this command for "import views" I get an error: "Unable to import "views"" What should I do with it? -
DJANGO - Detail View not finding objects - No "app-name" item found matching the query
I'm trying to create a Class-based Detail View of an inventory app. Problem is, when I search for the specific item I get back the following error from the browser: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/equipment/57/ Raised by: equipment.views.EquipmentType_DetailView No equipment item found matching the query You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. The strange thing is that if try directly "http://127.0.0.1:8000/equipment/57/update/", the app works perfectly and I get redirected to the update page of the corresponding object. But if I search "http://127.0.0.1:8000/equipment/57", I get the error I'm struggling to understand this. Here is my in app urls.py: from django.urls import path from .views import ( EquipmentType_ListView, EquipmentType_CreateView, EquipmentType_UpdateView, EquipmentType_DetailView,) urlpatterns=[ path('', EquipmentType_ListView.as_view(), name='equipmentType-home'), path('<int:pk>/', EquipmentType_DetailView.as_view(), name='equipmentType-detail'), path('new/', EquipmentType_CreateView.as_view(), name='equipmentType-create'), path('<int:pk>/update/', EquipmentType_UpdateView.as_view(), name='equipmentType-update'), ] my views.py: from django.shortcuts import render, redirect, get_object_or_404 from django.contrib.auth.models import User from django.views.generic import ( ListView, DetailView, CreateView, UpdateView, DeleteView ) from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from .models import EquipmentType, EquipmentItem from django.contrib.messages.views import SuccessMessageMixin # Create your views here. class EquipmentType_ListView(LoginRequiredMixin, ListView): model = EquipmentType template_name = 'equipment/equipment_type.html' # default … -
no such table: django_site [closed]
We are using kiwi tcms and it suddenly stopped working without any intervention from my side, here is the error message: Django Version: 2.1.15 Exception Type: OperationalError Exception Value: no such table: django_site Exception Location: /root/environments/Kiwi/lib64/python3.6/site-packages/django/db/backends/sqlite3/base.py in execute, line 298 Python Executable: /root/environments/Kiwi/bin/python Python Version: 3.6.8 Python Path: ['/root/environments/Kiwi', '/usr/lib64/python36.zip', When I run python manage.py migrate , Kiwi is back, but without data. Is there any chance to get the data back? Thanks -
Google Search Console wont accept Django Sitemap. Missing XML tag?
Im using the Django sitemap framework and the sitemap seems to be generated perfectly. But when submitted to google for indexing the search console gives the error 'Invalid file format'. They require XML or plaintext. But from everything I can tell the file is valid XML format. The only possible problem I could find is that the XML tag () is missing from the sitemap file that Django creates. Does anyone know why the Django Sitemap framework leaves this out and if there is a way to add it? Also, do you think this is the reason google flags it as an invalid file format? Any input would be appreciated! Thank you! Django's sitemap.py: from django.contrib.sitemaps import Sitemap from django.urls import reverse from blog.models import Post class StaticViewSitemap(Sitemap): changefreq = 'daily' priority = '0.5' def items(self): # Return list of url names for view to include in sitemap return ['home', 'contact', 'success', 'blog'] def location(self, item): return reverse(item) class BlogSitemap(Sitemap): changefreq = 'daily' priority = '0.5' def items(self): return Post.objects.all() sitemap.xml: <urlset xmlns="http://www.sitemaps.org/schemas/sitemap/0.9"> <url> <loc>https://swflreliefrealty.herokuapp.com/</loc> <changefreq>daily</changefreq> <priority>0.5</priority> </url> <url> <loc>https://swflreliefrealty.herokuapp.com/contact/</loc> <changefreq>daily</changefreq> <priority>0.5</priority> </url> <url> <loc>https://swflreliefrealty.herokuapp.com/success/</loc> <changefreq>daily</changefreq> <priority>0.5</priority> </url> <url> <loc>https://swflreliefrealty.herokuapp.com/blog/</loc> <changefreq>daily</changefreq> <priority>0.5</priority> </url> <url> <loc>https://swflreliefrealty.herokuapp.com/blog/post/this-is-the-first-test-post</loc> <changefreq>daily</changefreq> <priority>0.5</priority> </url> <url> <loc>https://swflreliefrealty.herokuapp.com/blog/post/this-is-the-second-post</loc> … -
I need some info on deploying a django site
I want to deploy my django site to the internet, however if i do this would i still have the ability to edit all to code/make migrations etc? If anyone has any tips for deploying a django site to the internet please leave a comment here thanks in advnace! -
Detecting / checking TLS version of a request
We have received the following email from Heroku. We have a django backend in heroku with a lot of request from browsers and other system. As Heroku says, we think we will not have any problem with browsers because even old browsers are compatible with TLS 1.2: https://caniuse.com/tls1-2 But, we don't know if other systems are connecting with our system with TLS 1.0 or TLS 1.1. Can we detect it from our code? Something like this? if request.getProtocolTLS() in ["TLS1.0", "TLS1.1"]: send_admin_mail('Alert old protocol of TLS', request.user, request.get_full_path()) Dear Heroku Customer, At Salesforce, our top priority is providing you with a trusted Heroku platform, and today we begin our migration off of older, less secure TLS versions with a plan to completely block TLS v1.0/v1.1 next year after July 31, 2021. While this restriction is generally not a problem for web browser clients, some old, non-browser clients may be affected. This notice gives you one full year to make whatever changes are necessary to ensure all clients use TLS v1.2, or greater (v1.2+). Heroku currently supports TLS v1.0/v1.1, as well as the latest, more secure TLS v1.2+ protocol on all apps. In April 2016, the PCI Council released version 3.1 … -
Getting issue with automatic handling rename migrations with django models and its field
I am getting issue with handling renaming automatically in Django models and its field # Generated by Django 2.2 on 2020-07-14 13:16 from django.conf import settings from django.db import migrations class Migration(migrations.Migration): dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('projectAPI', '0007_auto_20200713_1226'), ] operations = [ migrations.RenameModel( old_name='Store', new_name='Site', ), migrations.RenameModel( old_name='UserStore', new_name='UserSite', ), migrations.RenameField( model_name='installation', old_name='store', new_name='site', ), migrations.RenameField( model_name='site', old_name='store_name', new_name='site_name', ), migrations.RenameField( model_name='usersite', old_name='store', new_name='site', ), migrations.AlterUniqueTogether( name='installation', unique_together={('site', 'installation_name')}, ), migrations.AlterUniqueTogether( name='usersite', unique_together={('site', 'user')}, ), ] Getting issue with old model name store when python manage.py migrate python manage.py migrate projectAPI File "/home/chillmaster/chillmaster/chillmaster_env/lib/python3.6/site-packages/django/db/models/fields/related.py", line 604, in resolve_related_fields raise ValueError('Related model %r cannot be resolved' % self.remote_field.model) ValueError: Related model 'projectAPI.Store' cannot be resolved I have checked https://stackoverflow.com/a/33497027/7828402 but not get the solution I have tried to edit like in migration dependencies but not work for me ('projectAPI', '__first__') I know deleting migration and DB data it will work but I don't want to lose data in DB please help with solutions Thanks in advance -
Foreign key django - Database Relationships
I have a model for the Product Perfume, the product have different volume and prices. I need to render the volume and price for each but i get "'function' object has no attribute 'prices'" Any ideas? iam grateful for any suggestions View: from django.shortcuts import render from django.views.generic import View, TemplateView from products.models import Perfume, Pricing def getIndex(request): perfumes = Perfume.objects.all thePrice= perfumes.prices.all() return render(request, 'index.html', {'perfumes': perfumes, 'thePrice':thePrice}) Model from django.conf import settings from django.db import models from django.utils import timezone class Perfume(models.Model): genderChoice = ( ('unisex','unisex'), ('male', 'male'), ('female', 'female')) name = models.CharField(max_length=50, default='') brand = models.CharField(max_length=40, default='') gender = models.CharField(max_length=7, choices=genderChoice, default='unisex') description = models.TextField() image = models.ImageField(upload_to='images/product_image') created = models.DateField() author =models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) active = models.BooleanField(default=False) show_for_consumer = models.BooleanField(default=False) def __str__(self): return self.name class Pricing(models.Model): product =models.ForeignKey(Perfume, on_delete=models.CASCADE,related_name='prices') price= models.DecimalField(max_digits=10, decimal_places=2) volume= models.DecimalField(max_digits=10, decimal_places=2) def __str__(self): return 'Perfume {} - Price{} - Volume {}'.format(self.product.name,self.price, self.volume) -
How should I read specific data for the specific user from database by python django
For example, in my database, I have a table called BlackList which looks like this: What I want to do is something like this: if request.method == "POST": username = request.POST.get('username') # Get username input first password = request.POST.get('password') user = authenticate(request, username=username, password=password) # BLname = Read the username from the table # BLflag1 = read the Flag1 for the user # BLflag2 = read the Flag2 for the user if BLflag1 == True and BLflag2 == True: something will happen elif BLflag1 == True and BLflag2 == False: something will happen else: # set the Flag1 and Flag2 of this user to True. So, my questions are How to read the specific data for a specific user, for example, if the User 'aaa' try to log in, the application will read Flag1 for aaa is True and Flag2 for aaa is True. How to set the Flag for a specific user, for example, if user 'bbb' try to log in, the application will set Flag1 and Flag2 into True in the end. -
How do I create a URL in django?
I'm new to django and looking on how to create a url that targets a function instead of a view In Laravel I can do this Route::get('star/{property}/{user}', 'API\StarredPropertyController@star'); And I can return JSON or a view with that route. How do I do this in django -
Date formatting wrong when converting from JS to python Django
I'm working with a simple project where I have two JS date objects coming from the frontend. This is the format: Object { "closingTime": 2020-07-14T14:05:39.803Z, "latitude": 39.40969333805352, "longitude": -112.08057148382068, "openingTime": 2020-07-14T03:30:34.247Z, //... } Or, in the browser's DevTools: Tue Jul 14 2020 11:05:39 GMT-0300 (hora estándar de Argentina) As you can see, the timezone is GMT-0300. Now, when I recieve this in my Django backend (through a graphene-graphql API, if that's relevant) it gets wrote to the database like this: This is 3 hours after, even if I have the right timezone set in settings.py (TIME_ZONE = 'America/Buenos_Aires') which would be the same as GMT-0300 What am I missing here? -
Dynamically generate a form pressing a button in django
I have a form for collecting work experience of an employee. Currently I can add only one experience. I want that if I press a '+' icon or button, same form will be generated under the default form. models.py: class WorkExperience(models.Model): """ Stores employee previous work experiences """ employee = models.ForeignKey('Employee', related_name='we_employee', on_delete=models.CASCADE, null=True) previous_company_name = models.CharField(max_length=128, null=True) job_designation = models.CharField(max_length=128, null=True) from_date = models.DateField(null=True) to_date = models.DateField(null=True) job_description = models.CharField(max_length=256, null=True) forms.py: class WorkExperienceForm(forms.ModelForm): """ Creates a form for saving employee work experiences """ class Meta: model = WorkExperience fields = [ 'previous_company_name', 'job_designation', 'from_date', 'to_date', 'job_description', ] widgets = { 'from_date': DatePickerInput(), 'to_date': DatePickerInput(), } def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) This is my form. I want to add a '+' icon. Everytime user presses the icon, same fields will be generated alongside the default form. -
How to implement SSE for push notififiction using Django with postgresql for Database
I am working in project where frontend is implemnted in reactjs and backend in Django with postgresql. Now i need to implement push notification and i found SSE can be a way to do that.But i didn't find any proper example of SSE with django. Can anyone suggest me any documentation for that. -
django media url correct but not showing the picture
so i make a test Django project to fix the problem i have in my website is that the image wont display but when i see the url in the console its the correct MEDIA_URL that i set(the picture at the bottom) i know maybe the problem is in my urlpatterns but i can't seems to find what it is here is my code. urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path("",views.index,name="index"), path('callback/', views.callback, name='callback') ] + static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT) and sorry here is my model i edit class transaksi_user(models.Model): line_name = models.CharField(max_length=100) img_transaksi = models.ImageField(upload_to='image_transaksi') read_by_admin = models.BooleanField(default=False) def __str__(self): return self.line_name views.py STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR,"staticfiles") ] STATIC_ROOT = os.path.join(BASE_DIR,"assets") MEDIA_URL ='/media/' MEDIA_ROOT = os.path.join(BASE_DIR,'media') when i add the new image in django admin page it work and it locate the media file and save it there but when i try to view the image by click the url in django admin it show me error like this and in my console its the correct media url too -
Django signals for user log entry
I'm working on a function, in which I want to record the username of the user that is logged in and will update the order. If I try to login as a customer and try to update the order only the username of admin appears in the updated_by field in my template, not the customers username. models.py class Order(models.Model): Diagnosis_note = models.CharField(max_length=30, blank=True) memo = models.CharField(max_length=100, blank=True)ser = models.ForeignKey(User, null=True,on_delete=models.CASCADE) updated_by=models.ForeignKey(User, related_name='updated_by_user', on_delete=models.CASCADE) views.py def update_order(request, pk): order = Order.objects.filter(id=pk).first() form = OrderForm(request.POST or None, user=request.user,instance=order) if request.method == 'POST': form = OrderForm(request.POST or None, user=request.user,instance=order) if form.is_valid(): form.save() return redirect('/orderlist') context = {'form':form} t_form = render_to_string('update_form.html', context, request=request, ) return JsonResponse({'t_form': t_form}) signals.py @receiver(post_save, sender=Order) def log_audit(sender, instance, created, **kwargs): if not instance.updated_by: instance.updated_by = request.user -
How to filter Django model data using the logged-in users with multiple objects
I am new to Django and trying to figure out how to filter data using the logged-in users with multiple objects. When the user logged in, the user should be able to see the book which was authored by him, and also he is co-authored some books. Models.py class Book(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) co_authors = models.ManyToManyField(User, related_name='co_authored_by') views.py @login_required() def booklist(request): book=Book.objects.filter(author =request.user, co_authors =request.user) context = { 'book':book } return render(request, "contracts/booklist.html", context) Tried using Q and or logic not able pass both filters to the template. -
Heroku/Django - ImportError: No module named
I'm trying to deploy a site I made using Django to Heroku. Heroku says it's deploying but when I try to view it says "Application Error" and when I check my logs I'm seeing "ImportError: No module named restroomrater.wsgi". Procfile web: gunicorn restroomrater.wsgi --log-file - requirements.txt asgiref==3.2.10 cachetools==4.1.1 certifi==2020.6.20 chardet==3.0.4 dj-database-url==0.5.0 Django==3.0.8 django-heroku==0.3.1 django-storages==1.9.1 django-widget-tweaks==1.4.8 google-api-core==1.21.0 google-auth==1.19.0 google-cloud-core==1.3.0 google-cloud-storage==1.29.0 google-resumable-media==0.5.1 googleapis-common-protos==1.52.0 gunicorn==20.0.4 idna==2.10 protobuf==3.12.2 psycopg2==2.8.5 pyasn1==0.4.8 pyasn1-modules==0.2.8 pytz==2020.1 requests==2.24.0 rsa==4.6 six==1.15.0 sqlparse==0.3.1 urllib3==1.25.9 whitenoise==5.1.0 structure Structure <sorry, not sure how to get text version of the structure. Everything I've looked up points to this being problem but I'm not sure what I'm doing wrong? "restroomrater" is the name of my app. Let me know if there's more info I can provide. -
Filter workds, but exclude blows up
Django 3.0.8 Post.published.filter(tags__slug__in=[SPECIAL_TAGS.NEWS.value]) <QuerySet [<Post: 53: ffe0503b-c5c9-11ea-91fa-5404a66bf801>, <Post: 51: ff1cdf7b-c5c9-11ea-91fa-5404a66bf801>, <Post: 52: ffe0503a-c5c9-11ea-91fa-5404a66bf801>, <Post: 11: 6ffd0cc7-c4cb-11ea-b89d-5404a66bf801>, <Post: 44: ff1cdf74-c5c9-11ea-91fa-5404a66bf801>, <Post: 45: ff1cdf75-c5c9-11ea-91fa-5404a66bf801>, <Post: 46: ff1cdf76-c5c9-11ea-91fa-5404a66bf801>, <Post: 47: ff1cdf77-c5c9-11ea-91fa-5404a66bf801>, <Post: 48: ff1cdf78-c5c9-11ea-91fa-5404a66bf801>, <Post: 49: ff1cdf79-c5c9-11ea-91fa-5404a66bf801>, <Post: 50: ff1cdf7a-c5c9-11ea-91fa-5404a66bf801>, <Post: 38: 1a96e9f8-c519-11ea-9545-5404a66bf801>, <Post: 43: 1a96e9fd-c519-11ea-9545-5404a66bf801>]> Post.published.exclude(tags__slug__in=[SPECIAL_TAGS.NEWS.value]) Unable to get repr for <class 'django.db.models.query.QuerySet'> Could you tell me how can it be that filter workds, but exclude blows up? -
Django / Docker - Can't launch a project
everyone. I have a project: It has readme: pip install -r requirements.txt create local.py extract data from local_template.py create settings/firebase.json python manage.py makemigrations python manage.py migrate python manage.py collectstatic --noinput But makemigrations gives me the following: Is it because I don't use Docker to launch, or what should I do just to run it? Thanks -
Unable to create/write a file using fopen through django views in Linux server using apache2
My code on the Django view is as follows path = os.path.abspath(os.path.dirname("code")) parent = os.path.join(path, "code") file_name = os.path.join(parent, "new_script.py") f = open(file_name, "w+") f.write(new_code) f.close() the permission for the code folder is drwxrwxrw- 2 mano www-data 4096 Jul 14 13:48 code When I ran the server using python manage.py runserver on the server using the port 8000, everything is working as expected. But when I tried to run the same using the apache2, nothing is happening. Could you please help me with this? Thank you so much in advance:)