Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django AppRegistryNotReady Exception after import from django.contrib.auth.models
Here is my folder structure: . ├── app ├── project ├── scripts └── tests ├── fuctional -> test_views.py └── unit Here is my test_script.py from django.test import TestCase from django.urls import reverse from django.contrib.auth.models import User from django.contrib.auth.hashers import make_password from rest_framework.test import APIClient from mrx.views import LoginView, LogoutView When I launch python -m unittest tests/fuctional/test_views.py I get this error: Traceback (most recent call last): File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/runpy.py", line 193, in _run_module_as_main return _run_code(code, main_globals, None, File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/runpy.py", line 86, in _run_code exec(code, run_globals) File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/__main__.py", line 18, in <module> main(module=None) File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/main.py", line 100, in __init__ self.parseArgs(argv) File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/main.py", line 147, in parseArgs self.createTests() File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/main.py", line 158, in createTests self.test = self.testLoader.loadTestsFromNames(self.testNames, File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/loader.py", line 220, in loadTestsFromNames suites = [self.loadTestsFromName(name, module) for name in names] File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/loader.py", line 220, in <listcomp> suites = [self.loadTestsFromName(name, module) for name in names] File "/home/edx/.pyenv/versions/3.8.1/lib/python3.8/unittest/loader.py", line 154, in loadTestsFromName module = __import__(module_name) File "/home/edx/PycharmProjects/mrx_3/tests/fuctional/test_views.py", line 3, in <module> from django.contrib.auth.models import User File "/home/edx/.pyenv/versions/MRX/lib/python3.8/site-packages/django/contrib/auth/models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/home/edx/.pyenv/versions/MRX/lib/python3.8/site-packages/django/contrib/auth/base_user.py", line 48, in <module> class AbstractBaseUser(models.Model): File "/home/edx/.pyenv/versions/MRX/lib/python3.8/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/home/edx/.pyenv/versions/MRX/lib/python3.8/site-packages/django/apps/registry.py", line 253, in get_containing_app_config self.check_apps_ready() File "/home/edx/.pyenv/versions/MRX/lib/python3.8/site-packages/django/apps/registry.py", line 136, in … -
Calling other docker container by name doesn't work when using Nginx (Docker, Django, React/Next.js)
I am working on a project with Docker using Django in the backend and Next.js in the front. I currently have it working without using Nginx by binding the ports of each container to the host machine's port 8000 and 3000 respectively, with the Next.js's serverside calling from environment variable set as 'backend:8000/users/auth_api/google/' for authentication (backend is the container name for the backend). However, upon including Nginx, it doesn't seem to work anymore. I had to include a '/backend/' prefix to my backend container with the proxy_pass setting as I intend for the root '/' to be for the frontend. I've tried setting different environment variables and verified that uri call from the serverside from the logs but it just doesn't reach the backend (logs show that the api call to the environment variable uri was made by the frontend but not received by the backend meaning the api uri is wrong). Environment variables I've tried: SS_BACKEND_GOOGLE_AUTH=http://0.0.0.0:8000/users/auth_api/google/ SS_BACKEND_GOOGLE_AUTH=http://0.0.0.0:8000/backend/users/auth_api/google/ SS_BACKEND_GOOGLE_AUTH=http://backend:8000/users/auth_api/google/ SS_BACKEND_GOOGLE_AUTH=http://backend:8000/backend/users/auth_api/google/ SS_BACKEND_GOOGLE_AUTH=http://backend/users/auth_api/google/ SS_BACKEND_GOOGLE_AUTH=http://backend/backend/users/auth_api/google/ Docker-compose file version: '3.8' services: backend: restart: unless-stopped build: context: ./backend dockerfile: Dockerfile.test command: sh entrypoint.prod.sh container_name: backend expose: - 8000 ports: - 8000:8000 volumes: - ./backend/:/usr/src/backend/ - static_volume:/usr/src/backend/staticfiles - media_volume:/usr/src/backend/mediafiles env_file: - ./.env.test depends_on: - db - … -
How do I solve a python cursor connection error?
Performing system checks... System check identified no issues (0 silenced). Traceback (most recent call last): File "G:\Shares\Website\Development\Intranet\HealthcareProject2\manage.py", line 24, in <module> execute_from_command_line(sys.argv) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\base.py", line 316, in run_from_argv self.execute(*args, **cmd_options) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\base.py", line 353, in execute output = self.handle(*args, **options) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\commands\runserver.py", line 95, in handle self.run(**options) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\commands\runserver.py", line 104, in run self.inner_run(None, **options) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\commands\runserver.py", line 120, in inner_run self.check_migrations() File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\core\management\base.py", line 442, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\db\migrations\loader.py", line 49, in __init__ self.build_graph() File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\db\migrations\loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\db\migrations\recorder.py", line 61, in applied_migrations if self.has_table(): File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\db\migrations\recorder.py", line 44, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "G:\Program Files (x86)\Microsoft Visual Studio\2019\Shared\Python37_64\lib\site-packages\django\db\backends\base\base.py", line 255, … -
I get 'django.db.utils.IntegrityError: FOREIGN KEY constraint failed' when attempting to load json data
I am trying to load some data from a json file into the website,but whenever i type required commands and want to save , i get the following error: Traceback (most recent call last): File "C:\backend\website1\test\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\backend\website1\test\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.IntegrityError: FOREIGN KEY constraint failed The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 3, in <module> File "C:\backend\website1\test\lib\site-packages\django\db\models\base.py", line 753, in save self.save_base(using=using, force_insert=force_insert, File "C:\backend\website1\test\lib\site-packages\django\db\models\base.py", line 790, in save_base updated = self._save_table( File "C:\backend\website1\test\lib\site-packages\django\db\models\base.py", line 895, in _save_table results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw) File "C:\backend\website1\test\lib\site-packages\django\db\models\base.py", line 933, in _do_insert return manager._insert( File "C:\backend\website1\test\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\backend\website1\test\lib\site-packages\django\db\models\query.py", line 1254, in _insert return query.get_compiler(using=using).execute_sql(returning_fields) File "C:\backend\website1\test\lib\site-packages\django\db\models\sql\compiler.py", line 1397, in execute_sql cursor.execute(sql, params) File "C:\backend\website1\test\lib\site-packages\django\db\backends\utils.py", line 98, in execute return super().execute(sql, params) File "C:\backend\website1\test\lib\site-packages\django\db\backends\utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "C:\backend\website1\test\lib\site-packages\django\db\backends\utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "C:\backend\website1\test\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\backend\website1\test\lib\site-packages\django\db\utils.py", line 90, in __exit__ raise dj_exc_value.with_traceback(traceback) from exc_value File "C:\backend\website1\test\lib\site-packages\django\db\backends\utils.py", line 84, in _execute … -
Django+ HTML: how do i filter my own post away such that I am only querying other people's post and not my own posts
does anyone know how I can filter away my own blog posts so that only other people's blog posts are shown? I roughly know you need to use filter() but im unsure of what I must put into the function. Pls Help! Please let me know if you require more information :) def home_feed_view(request, *args, **kwargs): context = {} blog_posts = BlogPost.objects.all() context['blog_posts'] = blog_posts type_of_tinc = TypeoftincFilter(request.GET, queryset=BlogPost.objects.all()) context['type_of_tinc'] = type_of_tinc paginated_type_of_tinc = Paginator(type_of_tinc.qs, 4) page = request.GET.get('page') tinc_page_obj = paginated_type_of_tinc.get_page(page) context['tinc_page_obj'] = tinc_page_obj return render(request, "HomeFeed/snippets/home.html", context) models.py class BlogPost(models.Model): chief_title = models.CharField(max_length=50, null=False, blank=False) author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) body = models.TextField(max_length=5000, null=False, blank=False) slug = models.SlugField(blank=True, unique=True) class Account(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60, unique=True) username = models.CharField(max_length=30, unique=True) date_joined = models.DateTimeField(verbose_name='date joined', auto_now_add=True) last_login = models.DateTimeField(verbose_name='last login', auto_now=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) -
Why Nginx add "?next=" for my URL on Django Webapp
My Django have 5 apps central, mails, insure, redbooks, dshop urls.py urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='central/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(next_page='login'), name='logout'), path('home/', c_view.home, name='home'), path('mails/', include('mails.urls')), path('insure/', include('insure.urls')), path('redbooks/', include('redbooks.urls')), path('dshop/', include('dshop.urls')), path('adminpage/', admin.site.urls), ] My Django deployed on Digital Ocean https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-20-04 Run with $ python manage.py runserver 0.0.0.0:8000, WORKS FINE also $ gunicorn --bind 0.0.0.0:8000 lskweb.wsgi, WORKS FINE but When Nginx started with basic config sudo nano /etc/nginx/sites-available/lskweb server { listen 80; server_name 68.183.111.111; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/pawin/lskweb-ocean; } location / { include proxy_params; proxy_pass http://unix:/home/pawin/lskweb-ocean.sock; } } Nginx add "?next=" in front of my Django url ex. http://68.183.111.111/?next=/home/ instead of http://68.183.111.111/home/ http://68.183.111.111/?next=/mails/ instead of http://68.183.111.111/mails/ but when i click browser go back and click link again sometime nginx give the correct url in one click sometime more clicks .. for Now, my landing page is http://68.183.111.111/login/ (type in browser addr box) is OK /static/ no problem its serv files OK sorry for my English language. Thank you for your helps :) -
Django count using raw query
I'm having a trouble on how can I count query in Django raw using this query below. This is what should looks like.I just want to count number of paid. It would be great if anybody could help me thanks in advance!. rpts_paid_count.append(p.paid).count() #Error AttributeError: 'NoneType' object has no attribute 'count' What I've tried in Django rpts_paid_count = [] blank = "" for p in Person.objects.raw('SELECT * FROM app_person WHERE paid_by != %s GROUP BY paid_by, paid, category, category_status ORDER BY paid_by,paid', [blank]): rpts_paid_count.append(p.paid).count() #Error Part results = {'rpts_paid_count':rpts_paid_count} return JsonResponse(results) -
TypeError: expected string or bytes-like object in Django
I'm learning django and testing how it works with API and currently I'm trying to display records from an localhost API, but it seems like I missed something def fetchapi_patients(request): url = 'http://localhost:8000/core/users/roles/superuser' headers={"Authorization":"Bearer eyJhbGciOiJIUzI1NiIsInR5cCI6IkpXVCJ9.eyJleHAiOjE2MDYzMDg3MzYsImlkIjoiYWRtaW4iLCJvcmlnX2lhdCI6MTYwNjMwNTEzNn0.J2wBp8ecA9TebP6L73qZ1OZmo02DwQy9vTySt0fil4c"} response = requests.get(url, headers=headers) #Read the JSON patients = response.json() #print(patients) #Create a Django model object for each object in the JSON and store the data in django model (in database) for patient in patients: #print(patient['ID']) Patient.objects.create(first_name=patient['first_name'], last_name=patient['last_name'], email=patient['email'], coreapi_id=patient['ID'], created_date=patient['CreatedAt']) return JsonResponse({'patients': patients}) #return HttpResponse('ok') I tried different thing to make it work and I end up to test if it prints something with print(patients) and this gives the list in the terminal from my localhost API, and I found that the API works, but can't find why they don't printed in my frontend part of the websystem. This is my model for Patient: class Patient(models.Model): coreapi_id = models.CharField(max_length=100) first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) email = models.EmailField(max_length=100) language = models.CharField(max_length=20) created_date = models.DateTimeField(default=True) lastmodified_date = models.DateTimeField(default=True) def str(self): return self.email and my jquery script for visualization: // load the database with fetchapi from database $(document).ready(function() { var data; fetch("http://192.168.2.85:7575/fetchapipatients/") .then(response => response.json()) .then(json => data = json) .then(() => {console.log(data); $('#datatable').DataTable( { data: … -
production issue: sqlite3 to postgresql migration issue in django
I am trying to migrate my django project from sqlite3 to postgresql. I have done this succesfully in development but getting errors in production. i have used this command to create dumps: manage.py dumpdata --exclude auth.permission --exclude contenttypes > db.json then i changed database in my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'dbname', 'USER': 'username', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '5432', } then i exclude contenttypes as follow: python3 manage.py shell from django.contrib.contenttypes.models import ContentType ContentType.objects.all().delete() quit() but i am getting this error: django.db.utils.IntegrityError: Problem installing fixtures: insert or update on table "django_admin_log" violates foreign key constraint "django_admin_log_content_type_id_c4bce8eb_fk_django_co" DETAIL: Key (content_type_id)=(7) is not present in table "django_content_type". please help -
Styling django filter form in html
Here's how my django filter form currently looks: And here's my html code: <form action="" method="get" class="form-inline"> {{myfilter.form|bootstrap}} <button class="btn btn-primary" type="submit"> Search</button> </form> I am having trouble with the following: How do I bring the filters in center of the page? How do I change the "Name contains" to "Name"? How do I change the color of text to white in order to make them more visible? I have tried to search it online but no luckk. Little help will be appreciated. THANKS! -
Get initial value on nested serializer with many=True
class SomeSerializer(ModelSerializer): class Meta: fields = ("currency", "amount") model = SomeModel def get_amount(self, value): if getattr(self, "initial_data", None): currency = self.initial_data.get("currency") # for a case when serializer used directly else: currency = self.root.initial_data[self.source]["currency"] # for a case when serializer is nested # do some stuff return amount My serializers works fine, bith when is's used directly or as nested serializer. Here is serializer that uses previous one as nested: class OperationSerializer(Serializer): ... operation = SomeSerializer() Everything works fine until I try to use OperationSerializer with many=True. In this case I cannot get initial value of currency, because I need to specify an index for the root element which is not known for me. -
How to hide Python & Django technologies from Wappalyzer
I have a Django site and I want to hide Python and Django technologies from the eyes of Wappalyzer hackers. I've been searching this topic in the net and found nothing useful. How can I do that in Django version 3 and python version 3.7? How to do that in different versions of Django and python? Any help would be appreciated. -
whats the most sensible way of keeping the current user when using mobile auth on login?
I want mobile auth on login, but am wondering what the best way would be to store the current user, before giving them a session id (which would be granted on successful mobile auth). does it make sense to store a jwt in cookies for the user after they enter their password, while they're on the 2fa auth page? I've looked at a few sites with 2fa, and cant see any that do this, so figure there must be a better way? -
Django RecursionError on A2 Hosting server with basic project
I recently set up Python hosting for my Django application. I used A2Hosting with cPanel, and followed these instructions that they gave. So now I have a Django project and application, with a few modifications they asked for; I can confirm that the app is running, but… Now I'm doing the standard procedure, creating a simple HttpResponse view, creating an app-local urls.py, linking that urls.py to the project-wide urls.py, and removing this url block that they had me use, which WORKS, but I really don't want to render the templates raw like this: url(r'^$', TemplateView.as_view(template_name='static_pages/index.html'), name='home'), Well now I'm getting this error: (DOMAIN, APP, and USERNAME removed for privacy) RecursionError at / maximum recursion depth exceeded while calling a Python object Request Method: GET Request URL: http://APP.DOMAIN.TLD/ Django Version: 3.1.4 Exception Type: RecursionError Exception Value: maximum recursion depth exceeded while calling a Python object Exception Location: /home/USERNAME/virtualenv/APP/3.7/lib/python3.7/site-packages/django/urls/resolvers.py, line 258, in match Python Executable: /home/USERNAME/virtualenv/APP/3.7/bin/python Python Version: 3.7.8 Is my version too high? I assumed the documentation just used lower numbers because it hasn't been updated in a while. -
Channels_redis causing the error AttributeError: 'Redis' object has no attribute 'bzpopmin'
I am facing the following error message on my Django application: Exception inside application: 'Redis' object has no attribute 'bzpopmin' Traceback (most recent call last): File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/staticfiles.py", line 44, in __call__ return await self.application(scope, receive, send) File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/routing.py", line 71, in __call__ return await application(scope, receive, send) File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/sessions.py", line 47, in __call__ return await self.inner(dict(scope, cookies=cookies), receive, send) File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/sessions.py", line 254, in __call__ return await self.inner(wrapper.scope, receive, wrapper.send) File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/auth.py", line 181, in __call__ return await super().__call__(scope, receive, send) File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/middleware.py", line 26, in __call__ return await self.inner(scope, receive, send) File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/routing.py", line 160, in __call__ send, File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/consumer.py", line 94, in app return await consumer(scope, receive, send) File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/consumer.py", line 59, in __call__ [receive, self.channel_receive], self.dispatch File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/utils.py", line 58, in await_many_dispatch await task File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels/utils.py", line 50, in await_many_dispatch result = task.result() File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels_redis/core.py", line 469, in receive real_channel File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels_redis/core.py", line 524, in receive_single index, channel_key, timeout=self.brpop_timeout File "/home/jack/.conda/envs/GuessWhich/lib/python3.7/site-packages/channels_redis/core.py", line 361, in _brpop_with_clean result = await connection.bzpopmin(channel, timeout=timeout) AttributeError: 'Redis' object has no attribute 'bzpopmin' This seems to be after a WebSocket connection is created with the WebSocket disconnecting after the error is thrown. At first I tried other, similar, issues that were caused by … -
MultiValueDictKeyError Django : Uploading Image from HTML Form
I've included MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') URL in urls.py enctype="multipart/form-data" request.FILES["find"] ::find is the name of input. user = Register.objects.get(id=pk) user.profile_pic = request.FILES["find"] But it is not giving the error MultiValueDictKeyError at /updateUserData/7/ -
How can I change text displayed when user put wrong data?
I'm working in Python (django) now. I'm building a simple login page. I'm working with forms, and I want to add an infromation (ex. "Your data is wrong") when user put invalid username or password. How can I do it? Where can I change it? -
Show data after dropdown selection
I am struggling with my code. I want to show data from a specific user on screen. When the second dropdown is selected with the user from a specific group, I want his records to be shown on screen. But what ever I try, the data stays the same from one user. In a later stadium I want to make an Else and say if there is no data, that there is no data of the person. Should I do something with a jquery, or is there an easier way to solve this? The first dropdown is the group, the second dropdown the user. models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class DisplayGroups(models.Model): group_name = models.CharField(max_length=200) def __str__(self): return self.group_name class DisplayUsername(models.Model): username = models.CharField(max_length=100) def __str__(self): return self.username class CijferLijst(models.Model): name = models.CharField(max_length=200, default='') vak1 = models.CharField(max_length=200, default='') cijfer1 = models.DecimalField(max_digits=3, decimal_places=1, default='1.0') vak2 = models.CharField(max_length=200, default='') cijfer2 = models.DecimalField(max_digits=3, decimal_places=1, default='1.0') username = models.ForeignKey(User, on_delete=models.CASCADE, default='') def __str__(self): return '%s %s %s %s %s %s'%(self.name, self.vak1, self.cijfer1, self.vak2, self.cijfer2, self.username) bekijk.html {% extends 'home/base.html' %} {% block title %}Cijfers studenten{% endblock %} {% block javascript %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <script> $(document).ready(function() { … -
Is there a way in Django Rest Framework to deliver only specific attributes?
When building a large web backend we are faced with the problem that we have models with a lot of attributes. As we want to reduce the size of the responses for efficiency we use different serializers for our models. Take this simple model for instance: class Address(models.Model): country_id = models.ForeignKey(Country, on_delete=models.PROTECT) postal_code = models.CharField(max_length=10) street = models.CharField(max_length=176) number = models.CharField(max_length=20) additional = models.CharField(max_length=256, blank=True, default='') city = models.CharField(max_length=176) state = models.CharField(max_length=50) user = models.ForeignKey('user.User', on_delete=models.CASCADE) For this alone we have an ID Serializer, a StringSerializer (for delivering a usable string), a MinimalSerializer (for a list of multiple addresses), a DetailSerializer (with depth=1 for getting country and user details ... Now with this complexity we face several issues and thought about restructuring the api to include the required fields in the request. Is this possible with django + drf? We believed to find something under Content Negotiation but this is a different topic. -
Django display uploading files in different fields
I am creating a system with Django. A user has several customers. And every customer has a different file upload field. I have upload functions but it is common for everyone. What I want is for every customer should have different pdf upload and display field. How can I do that? models.py class Pdf(models.Model): comp_name = models.CharField(max_length=200, default='', blank=True, null=True) title = models.CharField(max_length=200) pdf = models.FileField(upload_to='pdfs/') type = models.CharField(max_length=200, default='Select') year = models.CharField(max_length=200, default='Select') def __str__(self): return self.title views.py def pdf_list(request): pdfs = Pdf.objects.all() return render(request, 'pdf_list.html', {'pdfs': pdfs}) def upload_pdf(request): if request.method == 'POST': form = PdfForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('pdf_list') else: form = PdfForm() return render(request, 'upload_pdf.html', {'form': form}) forms.py class PdfForm(forms.ModelForm): CHOICES = [ ('img', 'Image'), ('txt', 'Text'), ] type = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) year = forms.fields.DateField(widget=forms.widgets.DateInput(attrs={'type': 'date'})) comp_name = forms.ModelChoiceField(queryset=CompanyProfile.objects.all(), required=False, widget=forms.HiddenInput()) customer/model.py class Customer(models.Model): name = models.CharField(max_length=20) surname = models.CharField(max_length=20) companyName = models.CharField(max_length=200, default="Choose") -
Django DRF authentication methods
I am new to Django and am trying to create an application using Vue js web app, Flutter for mobile and django in the back end. I am actually confused which authentication method I should be using. I am making food delivery app clone. -
Ajax - 500 Internal Server Error on LocalHost
I am trying to create an EditForm for my data in Django and am receiving a 500 Internal Server error whenever I hit Save Changes. Screenshots below are of the process within Console and when I click on the xhr error. Any idea what would be causing this, considering I am just on my local http://127.0.0.1:7000 server at this point? views class UpdateCrudUser(View): def get(self, request): id1 = request.GET.get('id', None) employee1 = request.GET.get('employee', None) description1 = request.GET.get('description', None) stakeholder_group1 = request.GET.get('stakeholder_group', None) stakeholder_quadrant1 = request.GET.get('stakeholder_quadrant', None) obj = Stakeholder.objects.get(id=id1) obj.employee = employee1 obj.description = description1 obj.stakeholder_group = stakeholder_group1 obj.stakeholder_quadrant = stakeholder_quadrant1 obj.save() user = {'id':obj.id,'employee':obj.employee,'description':obj.description,'stakeholder_group':obj.stakeholder_group,'stakeholder_quadrant':obj.stakeholder_quadrant} data = { 'user': user } return JsonResponse(data) urls path('ajax/crud/update/', views.UpdateCrudUser.as_view(), name='crud_ajax_update'), html // Update $("form#updateUser").submit(function() { console.log("open"); var idInput = $('input[name="formId"]').val().trim(); var employeeInput = $('input[name="formemployee"]').val().trim(); var descriptionInput = $('input[name="formdescription"]').val().trim(); var stakeholder_groupInput = $('input[name="formstakeholder_group"]').val().trim(); var stakeholder_quadrantInput = $('input[name="formstakeholder_quadrant"]').val().trim(); console.log("create"); if (employeeInput && descriptionInput && stakeholder_groupInput && stakeholder_quadrantInput) { // Create Ajax Call $.ajax({ url: '{% url "polls:crud_ajax_update" %}', data: { 'id': idInput, 'employee': employeeInput, 'description': descriptionInput, 'stakeholder_group': stakeholder_groupInput, 'stakeholder_quandrant': stakeholder_quadrantInput }, dataType: 'json', success: function (data) { if (data.user) { updateToUserTabel(data.user); } } }); console.log("submitted"); } else { alert("All fields must have a valid value."); … -
Customising the template for a form widget.: Can other object properties be passed as attributes?
I have a model form that represents the choices for a ManyToMany field as checkboxes. The two related models are as follows: Passenger Model: class Passenger(models.Model): ... attributes etc ..... trip_addons = models.ManyToManyField(AddOn, blank=True) 'Add on' Model: class Addon(models.Model): name = models.CharField(max_length=254) description = models.TextField() price = models.DecimalField(max_digits=8, decimal_places=2) image = models.ImageField(null=True, blank=True) image_thumb = models.ImageField(null=True, blank=True) image_url = models.URLField(max_length=1024, null=True, blank=True) def __str__(self): return self.name But rather than rendering the default html checkboxes, I would like present the 'addon' options a little more like the 3rd example 'Choose your main dish' in this link, with the picture and short description in addition to the name. I have created my own template to be used by the widget and that works. I just would like to know if can pass the description, image and price data to these templates? forms.py class CustomCheckbox(forms.CheckboxSelectMultiple): """ Creates a custom checkbox select widget that subclasses Django's CheckboxSelectMultiple and customises it with a different template """ template_name = 'bookings/forms/checkbox_select.html' option_template_name = 'bookings/forms/checkbox_option.html'. and in the Meta for my Modelform: widgets = { "trip_addons": CustomCheckbox(), } -
Which is the best way to protect a Django API?
I've deployed a Django API powered with Django Rest Framework with some open endpoints and some Authenticated endpoints using Token authentication. Which is the best way to protect the entry API allowing only to send request from the app frontend team? I was thinking to use an Nginx basic auth, but then the Authorization header is duplicated, so Token auth is not working. -
How Do I Allow Users To Post Links In Django?
I dont need to have the full rich text editor but i want users to be able to post hyperlinks that work so is there a good way to do this in django forms or models?