Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unable to import models Django
I'm trying to download data to database from website using models. Structure of my project: -backdjango -app[folder] -__pycache__[folder] -templates[folder] -__init__.py -settings.py -urls.py -views.py -wsgi.py -drivers[folder] -__pycache__[folder] -management[folder] -commands[folder] -create_drivers.py -migrations[folder] -__init__.py -admin.py -apps.pyc -models.py -tests.py -views.py -node_modules[folder] -static[folder] -venv[folder] -.babelrc -.eslintrc.js -db.sqlite3 -manage.py -package-lock.json -package.json -Pipfile -Pipfile.lock -webpack.common.js -webpack.dev.js -webpack.prod.js -yarn.lock I'm using Django, Beautiful Soup and WebPack. I've downloaded ready configuration from this repo. In drivers->models.py I have one model: from django.db import models # Create your models here. class Driver(models.Model): name=models.CharField(max_length=150) In app->settings.py I've added to installed apps 'drivers'. My problem is in drivers->management->commands->create_driver.py: import re import requests from bs4 import BeautifulSoup from django.apps import apps import os os.environ['DJANGO_SETTINGS_MODULE'] = 'backdjango.settings' from drivers.models import Driver from django.core.management.base import BaseCommand, CommandError class Command(BaseCommand): def handle(self, *args, **options): self.save_to_db(name) def getDriver(self): r=requests.get( "http://www/formula1.com/en/drivers/lewis-hamilton.html") soup= BeautifulSoup(r.text, "html.parser") name= soup.find("h1",**{"class":"driver-name"}).contents[0] print(name) return Driver(name=name) def save_to_db(self,name): Driver.objects.name.save() In line with from drivers.models import Driver I have message Unable to import 'drivers.models'pylint(import-error) I've tried to solve this problem in many ways but nothing I' ve found on Internet helped. -
How do I filter a model in html django
I'm trying to filter a model in HTML I know that you can use eg. Model.objects.filter(bla=bloo, ...). I wanna do that in HTML not in my views.py. my model looks like this: class Like(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="likeUser") post = models.ForeignKey(NewPost, on_delete=models.CASCADE) heres my views.py: posts = NewPost.objects.all() like = Like return render(request, "network/index.html", { "posts": posts, "like": like )} heres what I'm trying to do in HTML: {% for post in posts %} {{ like.objects.filter(post=post) }} {% endfor %} I'm getting an error right now saying: Could not parse the remainder: '(post=post)' from 'like.objects.filter(post=post)' How can I make it work? -
Ajax form submit returns Bad Request error in Django
In a Django app I am trying to post (save data in related models) using Ajax. Hereunder, I am reproducing as much info about the scenario (in the process, the post has however become somewhat longish). With this arrangement (as narrated below) I keep getting Bad Request when trying to post. The same set of data get posted to the respective models without any error. Could somebody point me to the error that I have in my code/s. Models (models.py) class AudReqt(models.Model): aud_id = models.AutoField(primary_key=True, ...) aud_reqt_num = models.CharField(max_length=24, null=True, blank=True, ...) aud_doc_type = models.CharField(max_length=4, null=True, default='QLST', ...) short_text = models.CharField(max_length=55, verbose_name="Description") # REFERENCES TO FOREIGN KEY TABLES ********** aud_scope = models.ForeignKey(ScopeStd, related_name=...) aud_freqency = models.ForeignKey(Frequency, related_name=...) class Meta: # VALIDATION FOR UNIQUENESS *********** unique_together = [['aud_scope', ...],] class AudReqtItems(models.Model): aud_reqt_item_id = models.AutoField(primary_key=True, ...) header_reqt_id = models.ForeignKey(AudReqt, on_delete=models.CASCADE, ...) aud_reqt_sht_txt = models.CharField(max_length=55, ...) aud_factor = models.ForeignKey(AudFactor, related_name=...) aud_ext_text = models.CharField(max_length=255, ...) Forms (forms.py) class CreateAudReqtForm(forms.ModelForm): class Meta: model = AudReqt fields = ('aud_doc_type', 'aud_scope', 'aud_freqency', 'short_text') class CreateAudReqtItemsForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(CreateAudReqtItemsForm, self).__init__(*args, **kwargs) self.auto_id = True class Meta: model = AudReqtItems fields = ('aud_reqt_sht_txt', 'aud_factor', 'aud_ext_text) exclude = () CreateAudReqtFormset = inlineformset_factory( AudReqt, AudReqtItems, form = CreateAudReqtItemsForm, extra=1, … -
Can't connect to Website - Connection refused - Nginx - SSL
I'm working with Docker, Nginx and Django. I would like to secure my application with ssl but it won't work. I got a valid certificate using certbot This is my nginx.conf file: upstream app { server app:80; } server { listen 80; listen [::]:80; server_name mydomain.de; return 301 https://$server_name$request_uri; location ~ /.well-known/acme-challenge { allow all; root /var/www/certbot; } } server { listen 443 ssl; listen [::]:443 ssl; server_name mydomain.de; ssl_certificate /etc/nginx/ssl/live/mydomain.de/fullchain.pem; ssl_certificate_key /etc/nginx/ssl/live/mydomain.de/privkey.pem; location / { proxy_pass https://app; # proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # proxy_set_header Host $host; # proxy_redirect off; } location /staticfiles/ { alias /app/staticfiles/; add_header Access-Control-Allow-Origin *; location ~ /.well-known/acme-challenge { allow all; root /var/www/certbot; } } } That's my docker-compose file: version: '3.4' services: app: image: django build: context: ./app dockerfile: Dockerfile env_file: - ./.env volumes: - ./app/:/app/ - ./app/staticfiles/:/app/staticfiles command: gunicorn --bind 0.0.0.0:8000 --chdir /app/ Webserver.wsgi nginx: build: ./nginx ports: - 80:80 - 433:433 depends_on: - app volumes: - ./app/staticfiles/:/app/staticfiles - ./certbot/conf:/etc/nginx/ssl - ./certbot/data:/var/www/certbot db: image: postgres volumes: - postgres_data:/var/lib/postgresql/data/ environment: POSTGRES_DB_PORT: "5432" POSTGRES_DB_HOST: "myhost" POSTGRES_PASSWORD: "mypw" POSTGRES_USER: myname POSTGRES_DB: dev_db volumes: postgres_data: If I try to access my Website I just see the browser message "Connection refused" I renamed sensitive information like domain name and passwords -
Django Pagination & Filters appending to url rather than replacing
I have a Django page that has a table to display the data from my model. This table has pagination as well as multiple filters. I have manage to get the pagination and filters to work together to an extent, however the URL is all messed up. It looks like it is appending the new query string to the end of the URL. I have two main issues with this: If I use a single filter, it adds all the empty query strings in the URL for all filters. If I have filtered data in the table and try to change the page, It append the page query string on the end rather than replace it. Screenshot for issue 1: Screenshot for issue 2: filters.py: class SetFilter(django_filters.FilterSet): name = CharFilter(field_name='name', lookup_expr='icontains', label='', ) type = AllValuesFilter(field_name='type', choices=Set.objects.values_list('type', flat=True).distinct().order_by('type'), label='', empty_label="") nonfoil = AllValuesFilter(field_name='is_non_foil_only', choices=Set.objects.values_list('is_non_foil_only', flat=True).distinct().order_by('is_non_foil_only'), label='', empty_label="") foil = AllValuesFilter(field_name='is_foil_only', choices=Set.objects.values_list('is_foil_only', flat=True).distinct().order_by('is_foil_only'), label='', empty_label="") digital = AllValuesFilter(field_name='is_online_only', choices=Set.objects.values_list('is_online_only', flat=True).distinct().order_by('is_online_only'), label='', empty_label="") foreign = AllValuesFilter(field_name='is_foreign_only', choices=Set.objects.values_list('is_foreign_only', flat=True).distinct().order_by('is_foreign_only'), label='', empty_label="") class Meta: model = Set fields = '' views.py def sets_page(request): set_list = Set.objects.order_by('-id') last_modified = set_list[0].last_modified set_filter = SetFilter(request.GET, queryset=set_list) set_list = set_filter.qs paginator = Paginator(set_list, 22) is_paginated = True if … -
How to get data from model objects in django
I am using Tweepy to post a tweet from Django admin. How can I retrieve "title" and "image" from the model object as shown in the picture. whenever I click on the tweet button it should post a tweet on my Twitter account with title as text and image. Django Admin Form page # views.py def tweet(request): if request.method == "POST": twitter_auth_keys = { "consumer_key" : "XXX", "consumer_secret" : "XXX", "access_token" : "XXX", "access_token_secret" : "XXX" } auth = tweepy.OAuthHandler( twitter_auth_keys['consumer_key'], twitter_auth_keys['consumer_secret'] ) auth.set_access_token( twitter_auth_keys['access_token'], twitter_auth_keys['access_token_secret'] ) api = tweepy.API(auth) `Do something here` tweet = "New" post_result = api.update_status(status=tweet) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) -
Cannot assign "'navaradbe'": "Note.patient" must be a "Profile" instance. django form error
i have a foreign key field called patient in my models.py, i am trying to specify dynamic initials for the field in my views. but i keep getting this error. Exception Type: ValueError at /dashboard/addnotes/15 Exception Value: Cannot assign "'navaradbe'": "Note.patient" must be a "Profile" instance. also, navardbe is a my username. views.py def addnotes(request, id): profile = Profile.objects.get(user_id=id) if request.method == 'POST': form = PatientNotesForm(request.POST) if form.is_valid(): print(form.cleaned_data['illness'],form.cleaned_data['patient']) form.save() return redirect(f'/dashboard') else: form = PatientNotesForm(initial={'patient': profile}) return render(request, 'core/addnotes.html', {'form': form}) models.py class Note(models.Model): illness = models.CharField(max_length=1000, blank=True) patient = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='patientnote', null=True) doctor = models.CharField(max_length=100, blank=True) description = models.CharField(max_length=10000, blank=True) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.illness}" addnotes.html <li> <a href="{% url 'addnote' profile.user.pk %}"><img class="nav-items" src="{% static 'images/doctor.svg'%}" alt=""><span>Doctors</span> </a> </li> forms.py class PatientNotesForm(ModelForm): illness = forms.CharField(max_length=100, help_text='First Name') patient = forms.CharField(max_length=100, help_text='Last Name') doctor = forms.CharField(max_length=100, help_text='address') description = forms.CharField(max_length=100,widget=forms.Textarea) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['illness'].widget.attrs.update( {'placeholder': ('illness')}) self.fields['doctor'].widget.attrs.update( {'placeholder': ("Doctor's name")}) self.fields['patient'].widget.attrs.update( {'placeholder': ("Patient's name")}) self.fields['description'].widget.attrs.update( {'placeholder': ("Description")}) self.fields['illness'].widget.attrs.update({'class': 'log'}) self.fields['doctor'].widget.attrs.update({'class': 'log'}) self.fields['patient'].widget.attrs.update({'class': 'log'}) self.fields['description'].widget.attrs.update({'class': 'textarea'}) class Meta: model = Note fields = ('illness', 'patient', 'doctor', 'description') basically, i want each user to have notes so that i can be able to list … -
InvalidTemplateLibrary at /login/ apache2 error while starting patchman source code build
I am trying to setup patchman tool in ubuntu 18.01 (bionic) & I have been trying to build patchman from source. I followed similar steps as asked @ https://github.com/furlongm/patchman/blob/master/INSTALL.md#ubuntu-1804-bionic-1 Further, The installation is completed without any errors but when I hit URL as : http://<ip_address>/patchman I am getting below error: Request Method: GET http://10.177.209.84/patchman/login/?next=/patchman/dashboard/ 1.10 InvalidTemplateLibrary Invalid template library specified. ImportError raised when trying to load 'bootstrap3.templatetags.bootstrap3': No module named parse /usr/local/lib/python2.7/dist-packages/django/template/backends/django.py in get_package_libraries, line 130 /usr/bin/python 2.7.17 ['/srv/patchman', '/usr/lib/python2.7', '/usr/lib/python2.7/plat-x86_64-linux-gnu', '/usr/lib/python2.7/lib-tk', '/usr/lib/python2.7/lib-old', '/usr/lib/python2.7/lib-dynload', '/usr/local/lib/python2.7/dist-packages', '/usr/lib/python2.7/dist-packages'] Please pardon being novice to django & python, I am sure been making some silly mistake. Below is output for the command : "pip freeze" asn1crypto==0.24.0 beautifulsoup4==4.6.0 certifi==2018.1.18 chardet==3.0.4 colorama==0.3.7 cracklib==2.9.2 cryptography==2.1.4 defusedxml==0.5.0 Django==1.10 django-bootstrap3==12.1.0 django-extensions==1.8.1 django-filter==1.1.0 django-guardian==1.4.9 django-humanize==0.1.2 django-tagging==0.4.5 djangorestframework==3.7.7 dnspython==1.15.0 enum34==1.1.6 gyp==0.1 html5lib==0.999999999 humanize==0.5.1 idna==2.6 ipaddress==1.0.17 ipcalc==1.99.0 keyring==10.6.0 keyrings.alt==3.0 lxml==4.2.1 Markdown==2.6.9 progressbar==2.3 psycopg2==2.7.4 pycrypto==2.6.1 Pygments==2.2.0 pygobject==3.26.1 pygooglechart==0.4.0 pyOpenSSL==17.5.0 python-apt==1.6.5+ubuntu0.3 python-debian==0.1.32 python-magic==0.4.16 pytz==2018.3 pyxdg==0.25 PyYAML==3.12 requests==2.18.4 rpm==4.14.1 SecretStorage==2.3.1 six==1.11.0 sqlparse==0.2.4 urllib3==1.22 webencodings==0.5 -
How to configure price(different price when adding same products but it i don't want to change the original price) in django models
I'm building an inventory management software. Can anyone tell me how to do the following example: today I added stocks to my inventory product1 100 pieces and each cost $10 The next day I got another twenty stocks of product1 20 pieces but it cost only $9 I don't want to create new product. I only want to update the existing product. I want both $10 and $9 without changing a single product price and the total price of product1 must update automatically and I want the product log to show each instance -
Django: The model has two identical many-to-many relations through the intermediate model
I have seen this question: The model has two many-to-many relations through the intermediate model But I think my problem is slightly different: class Building(models.Model): name = models.CharField(max_length=64) prices = models.ManyToManyField('Resource', through='BuildingResourceRelation', related_name="prices") outputs = models.ManyToManyField('Resource', through='BuildingResourceRelation', related_name="outputs") inputs = models.ManyToManyField('Resource', through='BuildingResourceRelation', related_name="inputs") class Resource(models.Model): name = models.CharField(max_length=64) class BuildingResourceRelation(models.Model): building = models.ForeignKey('Building', on_delete=models.CASCADE) resource = models.ForeignKey('Resource', on_delete=models.CASCADE) amount = models.PositiveIntegerField() According to design there can be a different amount of prices, inputs, and outputs. I can create through model for each, but isn't there a better way? -
MySQLdb._exceptions.OperationalError: (1054, "Unknown column 'SOMEOBJECT_id' in 'field list'")
Before this python manage.py makemigrations - done, also python manage.py migrate - done I don't know what is happening, in the tutorial, that I follow, there is no such error- the syntax is the same in models.py: from django.db import models class Reporter(models.Model): first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) email = models.EmailField() def __str__(self): return self.first_name class Article(models.Model): headline = models.CharField(max_length=30) pub_date = models.DateField() reporter = models.ForeignKey(Reporter, on_delete=models.CASCADE) def __str__(self): return self.headline class Meta: ordering = ('headline',) Which are migrated, and in admin.py Article, and Publication is added **Python 3.6.12 (default, Aug 18 2020, 02:08:22) [GCC 5.4.0 20160609] on linux** Type "help", "copyright", "credits" or "license" for more information. (InteractiveConsole) >>> from MyApp.models import Article, Reporter >>> r = Reporter(first_name = 'John', last_name = Doe, e-mail = 'abc@gmail.com') File "<console>", line 1 SyntaxError: keyword can't be an expression >>> r = Reporter(first_name = 'John', last_name = 'Doe', e-mail = 'abc@gmail.com') File "<console>", line 1 SyntaxError: keyword can't be an expression >>> r = Reporter(first_name = 'John', last_name = 'Doe', email = 'abc@gmail.com') >>> r.save() >>> r1 = Reporter(first_name = 'Boris', last_name = 'Milanovic', email = 'xyz@gmail.com') >>> r1.save() >>> from datetime import date >>> a = Article(headline = 'this is … -
Can't connect to Django Channels consumer
I created a django-channels app that works without any problem in local. I'm now trying to deploy it to a DigitalOcean droplet. The whole Django WSGI part works, the only part not working is Django-Channels. If i try to connect to any consumer like below: ws://MYURL:9000/main I get the following error on my Chrome console: WebSocket connection to 'ws://MYURL:9000/main' failed: Error in connection establishment: net::ERR_CONNECTION_TIMED_OUT Daphne service: [Unit] Description=Daphne service After=network.target [Service] PIDFile=/run/daphne/pid User=root Group=root WorkingDirectory=/django-vue-mpa ExecStart=/django-vue-mpa/venv/bin/daphne --bind 0.0.0.0 --port 9000 --verbosity 0 django_vue_mpa.asgi:application ExecReload=/bin/kill -s HUP $MAINPID ExecStop=/bin/kill -s TERM $MAINPID Restart=on-abort PrivateTmp=true [Install] WantedBy=multi-user.target And here is my actual nginx conf: server { listen 80; server_name http://MYURL/; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /django-vue-mpa/django_vue_mpa; } location / { include proxy_params; proxy_pass http://unix:/django-vue-mpa/django-vue-mpa.sock; } } Again, this happens only when i try to access django channels from "outside", if i try to connect from local, it will work without any proble, which makes me think that the problem is Nginx or something else with the Digital Ocean VPS. Here is my Django Channels settings: ALLOWED_HOSTS = ['MYURL'] WSGI_APPLICATION = 'django_vue_mpa.wsgi.application' ASGI_APPLICATION = 'django_vue_mpa.routing.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels_redis.core.RedisChannelLayer', 'CONFIG': { … -
DoesNotExist at /accounts/profile/ balance matching query does not exist
I can successfully login with profile page displaying username but as soon as I add balance variable I am getting "balance matching query does not exist" error. Also the admin is not showing the model created "accounts" is name of the app I have added app name in settings.py models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class balance(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) balance = models.IntegerField(default = 0) views.py from django.shortcuts import render from django.contrib.auth import login, authenticate from django.contrib.auth.forms import UserCreationForm from django.shortcuts import redirect from .models import balance from django.contrib.auth.models import User def signup(request): if request.method == 'POST': form = UserCreationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') password = form.cleaned_data.get('password1') user = authenticate(username=username, password=password) login(request, user) instance = balance(user = request.user, balance = 0) instance.save() return redirect('profile') else: form = UserCreationForm() return render(request, 'registration/signup.html', {'form': form}) def profile(request): user = balance.objects.get(user=request.user) return render(request,'profile.html',{"balance":user.balance}) profile.html Hello {{request.user.username}} !! <br><br> Balance:{{balance}} <a href="{% url 'logout' %}">logout</a> -
Having issues in heroku Deployment of Django app
When I am deploying the Django shopping project on Heroku, it is showing everything but any content with images. There aren't any images and content related to it. I am using outside links to get images in the model. -
AWS Cloudfront Missing Key-Pair-Id query parameter or cookie value. Code runs fine as a separate script but fails in web server
I have set up a private streaming app using django (in ec2), s3, cloudfront, and hls.js. The web server I am using is apache httpd behind proxy server nginx. The issue I am facing is that the same code runs fine as a separate script and the response is 200, but when it runs in the web app even though the cookies are same I get the response as 403. And clicking on the link I get the aws cloudfront error: <Error> <Code>MissingKey</Code> <Message>Missing Key-Pair-Id query parameter or cookie value</Message> </Error> Below is the code in the web app: import datetime from cryptography.hazmat.backends import default_backend from cryptography.hazmat.primitives import hashes from cryptography.hazmat.primitives import serialization from cryptography.hazmat.primitives.asymmetric import padding import json, base64 class SomeDetailView(DetailView): model = SomeModel template_name = 'xxxxx/xxxx/detail.html' def get_queryset(self): qs = super(SomeDetailView, self).get_queryset() return qs.filter(someone__in=[self.request.user]) def get_context_data(self, **kwargs): context = super(SomeDetailView, self).get_context_data(**kwargs) # get some object some = self.get_object() if 'module_id' in self.kwargs and 'content_id' in self.kwargs: # get current module context['module'] = some.modules.get( id=self.kwargs['module_id']) content = get_object_or_404(Content, id=self.kwargs['content_id']) context['content'] = content else: # get first module context['module'] = some.modules.all()[0] context['content'] = context['module'].contents.all()[0] return context def render_to_response(self, context, **response_kwargs): response = super(SomeDetailView, self).render_to_response(context, **response_kwargs) exp_time = int((datetime.datetime.now() + datetime.timedelta(minutes=30)).replace(tzinfo=datetime.timezone.utc).timestamp()) … -
AttributeError at /notify/ 'User' object has no attribute 'get'
Here in views.py When i am creating a user object . it show me and error AttributeError at /notify/ 'User' object has no attribute 'get' How can i fix it out. from django.contrib.auth.models import User class NotifyView(TemplateView): template_name ='notify/home.html' def get(self,request,*args, **kwargs): print('oye',request.user) user = User.objects.get(username=request.user) user.notifications.mark_all_as_read(user) return user if more information is require than tell me in a comment session i will update my question with that information. Thank you! -
Why my Django application could not connect to postgres inside docker
I'm trying to launch my django app inside docker container docker-compose.yml version: '3.8' services: api: build: context: . dockerfile: ./Dockerfile-local ports: - "8000:8000" entrypoint: ./entrypoint-local.sh env_file: - .env-local links: - postgresql postgresql: image: postgres:12.4 restart: always environment: - POSTGRES_USER=postgres - POSTGRES_DB=frov_db - POSTGRES_PASSWORD=postgres - POSTGRES_HOST=postgresql - POSTGRES_PORT=5432 - PGDATA=/var/lib/postgresql/data/pgdata - C_FORCE_ROOT=true ports: - '5433:5432' Dockerfile-local FROM python:3.8-slim ENV PYTHONDONTWRITEBYTECODE 1 WORKDIR /usr/src/app COPY Pipfile.lock Pipfile ./ RUN pip install -U setuptools pip pipenv && pipenv install --system --deploy --ignore-pipfile --dev COPY . . RUN touch /var/log/filebeat.log && chmod 664 /var/log/filebeat.log \ && chmod +x ./entrypoint-local.sh entrypoint-local.sh #!/bin/bash python manage.py collectstatic --no-input --settings frov.settings.default python manage.py migrate --settings frov.settings.default python manage.py seed gunicorn -b 0.0.0.0:8000 --workers=1 --env DJANGO_SETTINGS_MODULE=frov.settings.default frov.wsgi:application .env-local DEBUG=True DJANGO_SETTINGS_MODULE=frov.settings.default DB_NAME=frov_db DB_USER=postgres DB_PASS=postgres DB_HOST=postgresql DB_PORT=5433 And now I have now idea, why do I get such error api_1 | psycopg2.OperationalError: could not connect to server: Connection refused api_1 | Is the server running on host "postgresql" (172.21.0.2) and accepting api_1 | TCP/IP connections on port 5433? Can anyone hepls me? I just can't figure out where the mistake can take place -
Django server error unresolved paths when DEBUG=False
I'm running an application built using Django cookie cutter (Django 2.1 but I also receive the same error on a similar Django 3.0 project) that works great when DEBUG = True. As soon as I turn DEBUG = False I receive this recursive error message followed by the server crashing saying A server error occurred. Please contact the administrator (this varies based on where I'm testing but basically saying the response was incomplete). WARNING 2020-11-01 08:36:43,217 loader_tags 17863 123145445117952 Exception raised while rendering {% include %} for template '404.html'. Empty string rendered instead. Traceback (most recent call last): File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response resolver_match = resolver.resolve(request.path_info) File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/urls/resolvers.py", line 523, in resolve raise Resolver404({'tried': tried, 'path': new_path}) django.urls.exceptions.Resolver404: {'tried': [[<URLResolver <URLResolver list> (None:None) 'en-us/'>], [<URLResolver <module 'config.api_router' from '/Users/kevin/projects/cdsso/config/api_router.py'> (api:api) 'api/'>]], 'path': 'join/'} During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/core/handlers/exception.py", line 99, in get_exception_response response = callback(request, **dict(param_dict, exception=exception)) File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/utils/decorators.py", line 142, in _wrapped_view response = view_func(request, *args, **kwargs) File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/views/defaults.py", line 46, in page_not_found body = template.render(context, request) File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/template/backends/django.py", line 61, in render return self.template.render(context) File "/Users/kevin/projects/.envs/cdsso/lib/python3.7/site-packages/django/template/base.py", line … -
Permit user to view login page after logged in
I'm using django 3 and I want to close the and register pages after user has logged in (and redirect to user's profile page). If you can give me the general idea of doing this kind of tasks I can figure the rest of it. -
Djoser change email language
Is there a way to change the email that is sent in djoser based on the language of the user instance? I have found this question How do I explicitly specify language of email I want to send?, but it does not seem to be an option in the last version of djoser, since there are no longer views for each action (activation, reset password etc.) or I have not figured out how it works. Also, I have tried inhereting the UserViewSet class and apply the translation, but I do not know if this is the way to do it and how to specify all the urls of djoser. class UserViewSet(djoser_view.UserViewSet): def perform_create(self, serializer): user = serializer.save() signals.user_registered.send( sender=self.__class__, user=user, request=self.request ) context = {"user": user} to = [get_user_email(user)] language = user.language or 'en-us' with translation.override(language): if settings.SEND_ACTIVATION_EMAIL: settings.EMAIL.activation(self.request, context).send(to) elif settings.SEND_CONFIRMATION_EMAIL: settings.EMAIL.confirmation(self.request, context).send(to) def perform_update(self, serializer): super().perform_update(serializer) user = serializer.instance language = user.language or 'en-us' with translation.override(language): if settings.SEND_ACTIVATION_EMAIL: context = {"user": user} to = [get_user_email(user)] settings.EMAIL.activation(self.request, context).send(to) @action(["post"], detail=False) def activation(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) user = serializer.user user.is_active = True user.save() signals.user_activated.send( sender=self.__class__, user=user, request=self.request ) language = user.language or 'en-us' with translation.override(language): if … -
Which Class is calling the Serializer Class in Django REST
I have two APIView classes and one ModelSerializer class. The APIView classes are using the serializer class. Is there any way to know which APIView class is calling the serializer class? I need seperate representation_view for these 2 APIView. APIView Classes class OwnerAllListAPIView(APIView): def get(self, request, *args, **kwargs): user = self.request.user all_list = ListName.objects.filter(owner=user).all() list_serializer = core_slr.ListNameSerializer(all_list, many=True) return response('Owner list', list_serializer.data, status.HTTP_200_OK) class ListNameDetailAPIView(APIView): def get(self, request, *args, **kwargs): list_name = ListName.objects.filter(id=self.kwargs.get('list_name_id')).first() list_serializer = core_slr.ListNameSerializer(list_name) return response('list name detail view', list_serializer.data, status.HTTP_200_OK) Serializer Class class ListNameSerializer(serializers.ModelSerializer): class Meta: model = ListName fields = [ 'id', 'owner', 'name' ] def to_representation(self, instance): ret = super(ListNameSerializer, self).to_representation(instance) ret['owner'] = f"{instance.owner.first_name} {instance.owner.last_name}" ret['total_question'] = QuestionBank.objects.filter(list_name=instance).count() return ret In the to_representation View, I just wanna to know which API is currently calling the serializer. -
Why I cannot retrieve the session_data while I can get the session_key in Django session
So I was trying to get a anonymous user to login, and then get the session key/data pair that include his name and pw so that it can be send back to an outside app. Later, going to other views, the user can keep being logged in. But I cant seem to be able to get the data from the session. I just get the session_key, but not the session_data in below sessiondata=request.session.session_data. It seems to be empty. Got error of: sessiondata=request.session.session_data AttributeError: 'SessionStore' object has no attribute 'session_data' Pls help if u hv any idea why :( from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import authenticate, login, logout from django.contrib.auth.decorators import login_required from django.http import HttpResponse from django.utils.datastructures import MultiValueDict from django.views.decorators.csrf import csrf_exempt from django.contrib.sessions.models import Session from importlib import import_module from django.conf import settings SessionStore = import_module(settings.SESSION_ENGINE).SessionStore @csrf_exempt def auth(request): if request.method=='POST': print('POST info') request.session['name']=request.POST['username'] request.session['password']=request.POST['password'] form=AuthenticationForm(data=request.POST) for key, value in request.session.items(): print('{} => {}'.format(key, value)) if form.is_valid(): # return redirect('index') if not request.session.session_key: request.session.save() session_id = request.session.session_key sessiondata=request.session.session_data sess = sessiondata print(session_id) print("-----------------------------") print(sess.decode()) return HttpResponse(sess) else: print(request.user.username) form=AuthenticationForm() context={'form': form} return render(request, 'registration/login.html', context) The testing client I used: import … -
django.db.utils.IntegrityError: UNIQUE constraint failed: new__bank_profile.fname_id
i was trying to migrate and this error occurred. django.db.utils.IntegrityError: UNIQUE constraint failed: new__bank_profile.fname_id i was trying to extend User model and that happened.following are my views and models. my views: def dashboard(request): if request.method=="POST": fname = request.POST.get('fname') age = request.POST.get('age') gender = request.POST.get('gender') address = request.POST.get('address') occupation = request.POST.get('occupation') bio = request.POST.get('bio') img = request.POST.get('img') filename = request.POST.get('filename') user=profile(fname=fname,age=age,gender=gender,address=address,occupation=occupation,bio=bio,img=img,filename=filename) user.save() return render(request, 'bank/index2.html') else: return render(request, 'bank/signin.html') my models: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver class profile(models.Model): fname = models.OneToOneField(User,max_length=50,default="",blank=True,null=True,on_delete=models.CASCADE,related_name='fname',unique=True) #fname = models.CharField(max_length=500,default="",blank=True,null=True) age = models.CharField(max_length=3,default="",blank=True,null=True) address = models.CharField(max_length=500,default="",blank=True,null=True) occupation = models.CharField(max_length=150, default="",blank=True,null=True) bio = models.TextField(max_length=500, blank=True,null=True,default="") img = models.ImageField(upload_to='bank/images', default="",blank=True,null=True) filename = models.ImageField(upload_to='bank/images', default="",blank=True,null=True) GENDER_CHOICES = ( ('M', 'Male'), ('F', 'Female'), ) gender = models.CharField(max_length=1, choices=GENDER_CHOICES, default="",blank=True,null=True) def __str__(self): return str(self.fname) -
How to add extra field in model serializer?
I am very new to django rest framework. I have two models ModelA and ModelB. I have a ModelB searilzer to display all the fields in get request. Because of some reasons ModelA and ModelB are not related by FK but ModelA.objects.get(modelB.field1=modelA.pk) this will return single data. class ModelASerailzer(serializers.ModelSerializer): class Meta: model = ModelA fields = ['f1','f2'] class ModelBSerailzer(serializers.ModelSerializer): # I want to do something like this here new_field = ModelA.objects.get(modelB.field1=modelA.pk).f1 # this will return the data in shell #and normal django view but I don't know how to implement this in django rest ? class Meta: model = ModelB fields = ['field1','field2', 'new_field'] -
Django - use redirect view with multiple parameters
Im trying to redirect to a view with multiple parameters: in my urls.py (app exhibition) I have: path('map/<float:lat>/<float:lng>/<int:zoom>', views.MapView.as_view(), name='map') where float is defined in a path converter like this: '[-+]?\d*\.?\d*' For the redirection I have: return redirect('exhibition:map', lat=48.128365,long=11.5662713,zoom=3) After hours of trying and researching similar questions I still get: Reverse for 'map' with keyword arguments '{'lat': 48.128365, 'long': 11.5662713, 'zoom': 3}' not found. 1 pattern(s) tried: ['de/map\\/(?P<lat>[-+]?\\d*\\.?\\d*)\\/(?P<lng>[-+]?\\d*\\.?\\d*)\\/(?P<zoom>[0-9]+)$'] If I adjust the url pattern and the redirect call to a single pattern (be it float or int) the redirection works. Thus the problem should be related to my usage of multiple parameters - but I just can see what is wrong. Any hints welcome!