Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to export local postgres db with schema and contents to production db
I have a local Postgres db, I would like to use this Db along with the contents in a production db for app. How do I migrate the local db to my nginx production server? -
Django on_delete parameter exists on local code but not on server code
For example, here is my actual code. category = models.ForeignKey(Category, verbose_name=_("Category"), blank=True, null=True, on_delete=models.CASCADE) But on the server (I use pythonanywhere to deploy my code) it has some kind of application error. The error messages are: 2020-04-15 07:12:30,651: Error running WSGI application 2020-04-15 07:12:30,669: TypeError: __init__() missing 1 required positional argument: 'on_delete' 2020-04-15 07:12:30,670: File "/var/www/misterfish_pythonanywhere_com_wsgi.py", line 34, in <module> 2020-04-15 07:12:30,672: application = get_wsgi_application() 2020-04-15 07:12:30,673: 2020-04-15 07:12:30,673: File "/home/misterfish/.virtualenvs/myenv/lib/python3.8/site-packages/django/core/wsgi.py", line 12, in get_wsgi_application 2020-04-15 07:12:30,673: django.setup(set_prefix=False) 2020-04-15 07:12:30,673: 2020-04-15 07:12:30,673: File "/home/misterfish/.virtualenvs/myenv/lib/python3.8/site-packages/django/__init__.py", line 24, in setup 2020-04-15 07:12:30,673: apps.populate(settings.INSTALLED_APPS) 2020-04-15 07:12:30,673: 2020-04-15 07:12:30,674: File "/home/misterfish/.virtualenvs/myenv/lib/python3.8/site-packages/django/apps/registry.py", line 114, in populate 2020-04-15 07:12:30,674: app_config.import_models() 2020-04-15 07:12:30,674: 2020-04-15 07:12:30,674: File "/home/misterfish/.virtualenvs/myenv/lib/python3.8/site-packages/django/apps/config.py", line 211, in import_models 2020-04-15 07:12:30,674: self.models_module = import_module(models_module_name) 2020-04-15 07:12:30,674: 2020-04-15 07:12:30,674: File "/home/misterfish/.virtualenvs/myenv/lib/python3.8/site-packages/quiz/models.py", line 45, in <module> 2020-04-15 07:12:30,675: class SubCategory(models.Model): 2020-04-15 07:12:30,675: 2020-04-15 07:12:30,675: File "/home/misterfish/.virtualenvs/myenv/lib/python3.8/site-packages/quiz/models.py", line 51, in SubCategory 2020-04-15 07:12:30,675: category = models.ForeignKey( Clearly the server didnt recognize there is a on_delete method. It took me some time to figure out there might be something wrong with the server code. So I look into it. quiz = models.ManyToManyField(Quiz, verbose_name=_("Quiz"), blank=True) category = models.ForeignKey(Category, verbose_name=_("Category"), blank=True, null=True) sub_category = models.ForeignKey(SubCategory, verbose_name=_("Sub-Category"), blank=True, null=True) figure = models.ImageField(upload_to='uploads/%Y/%m/%d', … -
django how to perform query on two models?
i have two models 'Post' and 'Like' which are in foreignkey relation. if i want to list all post(published=True) with number of likes of each post how to do in django query. Post.objects.filter(published=True).?.....join(count likes) -
Django CRUD - create and update view doesn't work
I'm really new to Django and I want to teach myself by making a simple note. I maked a simple form for creating a new note but I don't know how to make this just for the user is logged in. What I mean is that I want the user field from the creationNoteForm to be removed and the note to be sumbitted automatically for the person who is logged in. Hope that I was clear enough. Here is my "view.py": from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm from django.contrib.auth.models import User from django.contrib.auth import authenticate, login, logout from .forms import CreateUserForm, CreateNoteForm from django.contrib import messages from django.contrib.auth.decorators import login_required from .models import * # Create your views here. def loginPage(request): if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect('home') else: messages.info(request, 'Username or pasword is incorrect') context = {} return render(request, 'accounts/login.html', context) def registerPage(request): form = CreateUserForm() if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for '+ user) return redirect('home') context = {'form': form} return render(request, 'accounts/register.html', context) def logoutUser(request): logout(request) … -
making proxy authentication server in Django
I want to make a proxy server in python django (3.0) like the one at the following link: https://blogs.oracle.com/wssfc/handling-proxy-server-authentication-requests-in-java -
Converting HTML to Draft-JS ContentState in Python/Django
I'm migrating from using a html wysiwyg editor (CKEditor) to using Draft-JS and want to be able to convert existing HTML data into Draft-JS ContentState in a Django Migration but I've been unable to find a way to do this. Is this possible? Or is this even the correct approach? -
Choose SendGrid Template in Django
I'm Trying to send email using sendgrid and its sent successfully but when I tried to create template in sendgrib and I use there test to send email I received that email with correct template, I dont know how to select template_id in django mail = EmailMultiAlternatives( subject="Your Subject", from_email="from email", to=["to email"], headers={} ) and i added this line mail.template_id = 'template_id' mail.send() I received empty email , how can i select he template id in django ? many thanks -
Django - Not found error with Daphne and Nginx
I'm trying to deploy a Django/Django-Channels application a VPS. My environment is: django django-channels venv gunicorn nginx My project is called WaitingRoom and it is located at: WaitingRoomVenv |->WaitingRoomEnv |->WaitingRoom (here are the Django files) To deploy my project, i followed this tutorial. Here is my nginx configuration file: upstream app_server { server unix:/tmp/daphne.sock fail_timeout=0; } server { listen 443 ssl http2; server_name 54.39.20.155; client_max_body_size 20M; # this is optionally, I usually put it very big in nginx and do proper size checks in the application location /static/ { sendfile on; location ~* \.(?:ico|css|js|gif|jpe?g|png|svg|woff|bmp)$ { expires 7d; } alias /WaitingRoomVenv/WaitingRoom/WaitingRoom/static; } location / { proxy_pass http://54.39.20.155; proxy_set_header Host $host; proxy_set_header X-Forwarded-Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header Upgrade $http_upgrade; proxy_set_header X-Forwarded-Proto "https"; proxy_set_header Connection "upgrade"; add_header Referrer-Policy "no-referrer-when-downgrade"; } } And here is my Daphne service: [Unit] Description=daphne service to run Channels on WaitingRoom After=network.target After=nginx.service [Service] Type=simple RuntimeDirectory=daphne PIDFile=/run/daphne/pid User=root Group=www-data WorkingDirectory=/WaitingRoomVenv/WaitingRoom ExecStart=/WaitingRoomVenv/WaitingRoomEnv/bin/daphne -u /tmp/daphne.sock WR.asgi:application ExecStop=/WaitingRoomVenv/WaitingRoomEnv/bin/kill -s TERM $MAINPID [Install] WantedBy=multi-user.target The problem with my actual code is that whenever i try to reach any part of the site, i get a 404 Not Found Error. Here is how i did it: I uploaded my project to the VPS, … -
Python 3 Django Rest Framework - how to add a custom manager to this M-1-M model structure?
I have these models: Organisation Student Course Enrollment A Student belongs to an Organisation A Student can enrol on 1 or more courses So an Enrollment record basically consists of a given Course and a given Student from django.db import models from model_utils.models import TimeStampedModel class Organisation(TimeStampedModel): objects = models.Manager() name = models.CharField(max_length=50) def __str__(self): return self.name class Student(TimeStampedModel): objects = models.Manager() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True) organisation = models.ForeignKey(to=Organisation, on_delete=models.SET_NULL, default=None, null=True) def __str__(self): return self.email class Course(TimeStampedModel): objects = models.Manager() language = models.CharField(max_length=30) level = models.CharField(max_length=2) def __str__(self): return self.language + ' ' + self.level class Meta: unique_together = ("language", "level") class EnrollmentManager(models.Manager): def org_students_enrolled(self, organisation): return self.filter(student__organisation__name=organisation).all() class Enrollment(TimeStampedModel): objects = EnrollmentManager() course = models.ForeignKey(to=Course, on_delete=models.CASCADE, default=None, null=False) student = models.ForeignKey(to=Student, on_delete=models.CASCADE, default=None, null=False) enrolled = models.DateTimeField() last_booking = models.DateTimeField() credits_total = models.SmallIntegerField(default=10) credits_balance = models.DecimalField(max_digits=5, decimal_places=2) Notice the custom EnrollmentManager that allows me to find all students who are enrolled from a given organisation. How can I add a custom Manager to retrieve all the courses from a given organisation whose students are enrolled? class EnrollmentManager(models.Manager): def org_courses_enrolled(self, organisation): return self.filter ... ? -
Python 3 Django-Rest-Framework - how to create a custom manager for a M-1-M relation?
I have these models: Organisation Student Course Enrollment A Student belongs to an Organisation A Student can enrol on 1 or more courses So an Enrollment record basically consists of a given Course and a given Student class Organisation(TimeStampedModel): objects = models.Manager() name = models.CharField(max_length=50) def __str__(self): return self.name class Student(TimeStampedModel): objects = models.Manager() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True) organisation = models.ForeignKey(to=Organisation, on_delete=models.SET_NULL, default=None, null=True) def __str__(self): return self.email class Course(TimeStampedModel): objects = models.Manager() language = models.CharField(max_length=30) level = models.CharField(max_length=2) def __str__(self): return self.language + ' ' + self.level class Meta: unique_together = ("language", "level") class Enrollment(TimeStampedModel): objects = models.Manager() course = models.ForeignKey(to=Course, on_delete=models.CASCADE, default=None, null=False) student = models.ForeignKey(to=Student, on_delete=models.CASCADE, default=None, null=False) enrolled = models.DateTimeField() last_booking = models.DateTimeField() credits_total = models.SmallIntegerField(default=10) credits_balance = models.DecimalField(max_digits=5, decimal_places=2) Given an Organisation name I would like to add a custom manager for Enrollments, like this: class EnrollmentManager(models.Manager): def org_student_count(self, organisation): return self.filter(student__organisation__name=organisation).count() So I can query like this: Enrollment.objects.org_student_count('AEKI') <- returns 100 The problem is that I always get the same result, regardless of what I pass in: Enrollment.objects.org_student_count('TRUMP') <- returns 100 but should be 0 -
Django get_or_create causing database error
Using get_or_create in Django causes the following error: Traceback (most recent call last): File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 323, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\management\base.py", line 364, in execute output = self.handle(*args, **options) File "C:\Users\sande\Documents\projects\sbbetting\football\management\commands\scrape.py", line 12, in handle sofa.get_matches() File "C:\Users\sande\Documents\projects\sbbetting\football\common\sofascore.py", line 21, in get_matches country = Country.objects.get_or_create(sofascore_id=country_id, name=country_name, defaults={"sofascore_id": country_id, "name": country_name})[0] File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py", line 538, in get_or_create return self.get(**kwargs), False File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py", line 402, in get num = len(clone) File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py", line 256, in __len__ self._fetch_all() File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py", line 1242, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py", line 55, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\compiler.py", line 1098, in execute_sql cursor = self.connection.cursor() File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 256, in cursor return self._cursor() File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 233, in _cursor self.ensure_connection() File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 217, in ensure_connection self.connect() File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 197, in connect self.init_connection_state() File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\mysql\base.py", line 231, in init_connection_state if self.features.is_sql_auto_is_null_enabled: File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\utils\functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\mysql\features.py", line 81, in is_sql_auto_is_null_enabled with self.connection.cursor() as cursor: File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 256, in cursor return self._cursor() File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 235, in _cursor return self._prepare_cursor(self.create_cursor(name)) File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 225, in _prepare_cursor self.validate_thread_sharing() File "C:\Users\sande\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\base\base.py", line 547, … -
renaming file when uploading with django modelform
I'm new to django and currently following a tutorial where it uses a ModelForm for a User Profile where a user can upload an avatar. I want to be able to update the file that they upload to a generated id. I'm just not sure where and how to do capture and update the file. My Model class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) avatar = models.ImageField(default='avatar_default.jpg', upload_to='profile_images') def save(self,*args, **kwargs): super().save() img = Image.open(self.avatar.path) if img.height > 300 or img.width > 300: output_size = (300,300) img.thumbnail(output_size) img.save(self.avatar.path) def __str__(self): return f'{self.user.username} Profile' Form class ProfileUpdateForm(forms.ModelForm): class Meta: model = Profile fields = ['avatar'] View @login_required def user_profile(request): if request.method == 'POST': user_form = UserUpdateForm(request.POST, instance=request.user) profile_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if user_form.is_valid() and profile_form.is_valid(): user_form.save() profile_form.save() messages.success(request, f'Your profile has been updated') return redirect('users_profile') else: user_form = UserUpdateForm(instance=request.user) profile_form = ProfileUpdateForm(instance=request.user.profile) context = { 'user_form': user_form, 'profile_form': profile_form } return render(request, "users/profile.html", context) I tried to apply some recommendations online where you do a Commit=False when saving the form and store that in a variable and renaming the file, it was a whole lot of confusion in the end. -
Datetimepicker plus DJANGO not loading correctly
I have been going crazy in order to understand what's going on but I can't seem to figure out what is the problem. It only happens in production, not in dev server. Here is my config: Settings.py STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static") STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] base.html (the layout im extending) <!DOCTYPE html> <html lang="en"> {% load static %} {% load bootstrap4 %} <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content=""> <meta name="author" content=""> <title>WHARFY</title> {% bootstrap_javascript jquery='full' %} {% bootstrap_css %} <!-- Custom fonts for this template--> <link href='{% static "vendor/fontawesome-free/css/all.min.css"%}' rel="stylesheet" type="text/css"> <link href="https://fonts.googleapis.com/css?family=Nunito:200,200i,300,300i,400,400i,600,600i,700,700i,800,800i,900,900i" rel="stylesheet"> <!-- Custom styles for this template--> <link href='{% static "css/sb-admin-2.min.css" %}' rel="stylesheet"> model_update.html (Im using UpdateView) {% extends 'base.html' %} {% load bootstrap4 %} {% block content %} {{ form.media }} <form method="post">{% csrf_token %} {% bootstrap_form form %} <input type="submit" value="Save"> </form> {% endblock %} While in dev I do not have any problems, in production i get this error from the console Failed to load resource: the server responded with a status of 404 (Not Found) datepicker-widget.css:1 Failed to load resource: the server responded with a status of 404 (Not Found) … -
Python 3 & Django Rest Framework - how to query M-1-M models?
I have these models: Organisation Student Course Enrollment A Student belongs to an Organisation A Student can enrol on 1 or more courses So an Enrollment record basically consists of a given Course and a given Student class Organisation(TimeStampedModel): objects = models.Manager() name = models.CharField(max_length=50) def __str__(self): return self.name class Student(TimeStampedModel): objects = models.Manager() first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=50) email = models.EmailField(unique=True) organisation = models.ForeignKey(to=Organisation, on_delete=models.SET_NULL, default=None, null=True) def __str__(self): return self.email class Course(TimeStampedModel): objects = models.Manager() language = models.CharField(max_length=30) level = models.CharField(max_length=2) def __str__(self): return self.language + ' ' + self.level class Meta: unique_together = ("language", "level") class EnrollmentManager(models.Manager): def org_student_count(self, organisation): return self.filter(student__organisation__name="AEKI").count() class Enrollment(TimeStampedModel): objects = EnrollmentManager() course = models.ForeignKey(to=Course, on_delete=models.CASCADE, default=None, null=False) student = models.ForeignKey(to=Student, on_delete=models.CASCADE, default=None, null=False) enrolled = models.DateTimeField() last_booking = models.DateTimeField() credits_total = models.SmallIntegerField(default=10) credits_balance = models.DecimalField(max_digits=5, decimal_places=2) Given an Organisation ID, I understand that I can get the enrollments for a single student, like so: o=Organisation.objects.get(id=1) o.student_set.all()[0].enrollment_set.all() but how can I retrieve ALL Enrollments for a given Organisation? For example, if I wanted to count how many students from a given organisation have enrolled on courses? Something like this: o.student_set.enrollment_set.count() -
error handling Django and Wordpress together in a single apache server
I have a website that runs on django, say www.foo.com. Now I want to host wordpress blog.foo.com on the same server. Problem is I am able to load www.foo.com but not blog.foo.com. blog site is responding with 400 bad request. Here are my foo.com.conf and blog.foo.com.conf settings. foo.com.conf: WSGIDaemonProcess foo python-home=/home/ubuntu/foo/env python-path=/home/ubuntu/foo/foo/ WSGIProcessGroup foo WSGIScriptAlias / /home/ubuntu/foo/foo/foo/wsgi.py <VirtualHost *:80> ServerName foo.com ServerAlias www.foo.com ServerAdmin webmaster@localhost ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/ubuntu/foo/foo/static <Directory /home/ubuntu/foo/foo/static> Require all granted </Directory> <Directory /home/ubuntu/foo/foo/foo> <Files wsgi.py> Require all granted </Files> </Directory> RewriteEngine on RewriteCond %{SERVER_NAME} =foo.com [OR] RewriteCond %{SERVER_NAME} =www.foo.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> blog.foo.conf: <VirtualHost *:80> ServerName blog.foo.com ServerAdmin webmaster@localhost DocumentRoot /var/www/html/blog.foo.com ErrorLog ${APACHE_LOG_DIR}/blog.foo.com/error.log CustomLog ${APACHE_LOG_DIR}/blog.foo.com/access.log combined <Directory /var/www/html/blog.foo.com> Order allow,deny Allow from all Options Indexes FollowSymLinks AllowOverride All Require all granted </Directory> </VirtualHost> LOG ERROR: [Wed Apr 15 16:31:54.081583 2020] [authz_core:error] [pid 20804] [client 5.101.0.209:42716] AH01630: client denied by server configuration: /home/ubuntu/foo/foo/foo/wsgi.py -
Django 2.2 multiples schemas en postgresql
Estimados buenos días. Les hago una consulta. Tengo un sistema el cual da servicio a muchos negocios iguales y cada negocio tiene su schema en postgresql. El tema es que tengo la tabla users donde le agrego un campo que se llama schema que es donde detallo a que schema tiene que ir cada usuario. Este campo lo levantaría en session y cuando llamo al modelo quiero decirle que me traiga los objetos pero de tal o cual schema. Esto seria en tiempo real. Otra cosa en settings.py solo tendría la conexión a la única DB que es donde tendría todos los schemas. Se les ocurre como puedo hacer?, como le digo al medelo que traiga por ejemplo a contactos pero de tal o cual schema Gracias -
How to display ComboBox in React Frontend with Django Backend
I am new to react js and I have an application with react frontend and django backend. -
Django Listview classmethod
In django >2 .0 have Handler class ListView my code: from django.urls import path from . import views urlpatterns = [ # post views path('', views.post_list, name='post_list'), # path('', views.PostListView.as_view(), name='post_list'), In source code django: @classonlymethod def as_view(cls, **initkwargs): """Main entry point for a request-response process.""" ........... def view(request, *args, **kwargs): self = cls(**initkwargs) ........................... update_wrapper(view, cls.dispatch, assigned=()) return view views.post_list - simple function in module views views.PostListView.as_view() - module(views)-> class inherited from ListView(PostList)-> class method from ListView - as_view() Why is it written with brackets ? -
Failing to display Image from Django admin
I am trying to view/display the image that I have uploaded in the products model. This is he product view code. This is the product model code. This is the Html code where I'm viewing the products but image not being displayed. -
Django retrieve data from three tables
Question i am using django last version.I have three table models named like this Class MCH(): Name= models.CharField() Class Staff(): Name=models.CharField() Mch=models.ForeignKey(MCH,,on_delete=models.CASCADE) location=models.CharField(..) Class Patients(): Name=models.CharField() Staff=models.ForeingKey(Staff,on_delete=models.CASCADE) Phone=models.CharField() I want to to join the tree table using Django method and filter data by MCH I tried this ServedPatients=Patients.objects. select_related(Staff__MCH='mch1') -
whitenoise.storage.MissingFileError: The file 'ecommerce/fonts/icofont.eot
I am trying to deploy my application on Heroku. It was uploaded successfully before, however, I made some changes and I tried re-uploading but it hasn't been responding since then. I keep getting this error: whitenoise.storage.MissingFileError: The file 'ecommerce/fonts/icofont.eot' could not be found with . What can I do about this? This is the traceback: whitenoise.storage.MissingFileError: The file 'ecommerce/fonts/icofont.eot' could not be found with <whitenoise.storage.CompressedManifestStaticFilesStorage object at 0x7f73c4861320>. remote: The CSS file 'ecommerce/css/icofont.css' references a file which could not be found: remote: ecommerce/fonts/icofont.eot remote: Please check the URL references in this CSS file, particularly any remote: relative paths which might be pointing to the wrong location. remote: Sentry is attempting to send 0 pending error messages remote: Waiting up to 2 seconds remote: Press Ctrl-C to quit I have this in my settings.py file STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_URL = '/static/' -
NoReverseMatch at /display_maintenance 'example' is not a registered namespace
I keep staring at this and no joy. My urls.py file. All of the files are displaying except 'display_maintenance.html' from django.contrib import admin from django.urls import path, include from example import urls as example_urls from example import views as example_views urlpatterns = [ path('admin/', admin.site.urls), path('', example_views.home, name="home"), path('add_location', example_views.add_location, name='add_location'), path('add_device', example_views.add_device, name='add_device'), path('add_maintenance', example_views.add_maintenance, name='add_maintenance'), path('display_maintenance', example_views.display_maintenance, name='display_maintenance'), path('device_list', example_views.device_list, name='device_list'), path('search_device', example_views.search_device, name='search_device') ] Here's the views.py where the error is hanging on the return render: def display_maintenance(request): maintenance = Maintenance.objects.all() context = {"maintenance": maintenance} for item in maintenance: item.devices = Devices.objects.filter(maintenance=item) return render(request, 'example/display_maintenance.html', context) And finally, the html file. I'm baffled: def display_maintenance(request): maintenance = Maintenance.objects.all() context = {"maintenance": maintenance} for item in maintenance: item.devices = Devices.objects.filter(maintenance=item) return render(request, 'example/display_maintenance.html', context) -
What method to choose for designing the study on Amazon Mechanical Turk?
I would like to choose a method for psychological study design, which I want to implement in Amazon Mechanical Turk. The experiment requires dragging and dropping images and some specific randomization, so I can't use platforms like Qualtrics or SurveyMonkey (I think I can't). So I want to create my own experiment and put it on a server. I would use Django and PsychoPy package, but I'm afraid Django is overcomplicated for such a project (I want to have just a csv or a json file with participants' data as output). The second idea is just a javascript, but I feel more comfortable in python. What is your advice? Maybe there is a better option? Thanks for answers. -
Why am I not being able to save my addresses?
Hi I'm trying to develop an e-commerce website with django. I want to use ajax to handle my checkout form. When I added Ajax, after filling out the form and clicking the submit button, I am seeing that my form and data is not getting saved by going into my admin. It's also not being redirected to return HttpResponseRedirect(reverse(str(redirect))+"address_added=True"), rather it's being redirected to http://127.0.0.1:8000/checkout/?csrfmiddlewaretoken=u6hDPBVuOZbDmoHvRFWb2PvfK1YamCIKGSaDkKdVTviWvJODgY5lM6rKppoW1oeP&address=123+Main+Street&address2=&state=MA&country=USA&zipcode=55525&phone=%28877%29+314-0742&billing=on.Can anyone please help me out with what's actually wrong? My accounts.views.py: from django.shortcuts import render, HttpResponseRedirect, Http404 from django.contrib.auth import logout, login, authenticate from django.contrib import messages from .forms import LoginForm, RegistrationForm, UserAddressForm from django.urls import reverse def add_user_address(request): try: redirect = request.GET.get("redirect") except: redirect = None if request.method == "POST": form = UserAddressForm(request.POST) if form.is_valid(): new_address = form.save(commit=False) new_address.user = request.user new_address.save() if redirect is not None: return HttpResponseRedirect(reverse(str(redirect))+"address_added=True") else: raise Http404 My urls.py: path('ajax/add_user_address/', accounts_views.add_user_address, name='ajax_add_user_address') My checkout.html: <div class="content-section"> <form method="POST" action='{% url "ajax_add_user_address" %}?redirect=checkout'> {% csrf_token %} <fieldset class="form-group"> {{ address_form|crispy }} <input type="submit" class="btn btn-dark" value="Place Order"/> </fieldset> </form> </div> My orders.views.py: from accounts.forms import UserAddressForm from accounts.models import UserAddress @login_required() def checkout(request): try: the_id = request.session['cart_id'] cart = Cart.objects.get(id=the_id) except: the_id = None return redirect(reverse("myshop-home")) try: new_order = Order.objects.get(cart=cart) … -
How to use Django's include without a string literal?
I just started up with django. Following this tutorial, I ended up with the following urls.py: from django.contrib import admin from django.urls import include, path urlpatterns = [ path('polls/', include('polls.urls')), path('admin/', admin.site.urls), ] This links to polls.urls.py which has its own router. The part I don't like is the string literal 'polls.urls' which is, well... a string literal. I would like to somehow reference the file directly using some of python's power, and have AT LEAST my IDE protect me. What happens if I want to move that polls.urls.py file, or rename it, or rename polls? Should I trust my IDE to catch a reference from a string literal? This is almost like doing this monstrosity, and is very hard for me to accept as the best practice. It just seems odd to me. Is there a way to use something less prone to errors than string literals in django's routers?