Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework for Meetingroom Reservation tasks
I need to realize the following tasks: Create employee Create meeting room Get meeting room reservations and the possibility to filter by employee Create reservation (Reservation has title, from and to dates, employees) So, first I created 2 apps Employees and Reservations, this is the Employees' model (Employees/models.py) : from django.db import models from phonenumber_field.modelfields import PhoneNumberField from django.contrib.auth.models import AbstractBaseUser,PermissionsMixin,BaseUserManager # Creating the CustomUserManager class CustomUserManager(BaseUserManager): def _create_user(self, email, password, first_name, last_name, mobile, **extra_fields): if not email: raise ValueError("An Email must be provided") if not password: raise ValueError("The Password is mendatory") user = self.model( email = self.normalize_email(email), first_name = first_name, last_name = last_name, mobile = mobile, **extra_fields ) user.set_password(password) user.save(using=self._db) return user def create_user(self, email, password, first_name, last_name, mobile, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_active',True) extra_fields.setdefault('is_superuser',False) return self._create_user(email, password, first_name, last_name, mobile, password, **extra_fields) def create_superuser(self, email, password, first_name, last_name, mobile, **extra_fields): extra_fields.setdefault('is_staff',True) extra_fields.setdefault('is_active',True) extra_fields.setdefault('is_superuser',True) return self._create_user(email, password, first_name, last_name, mobile, **extra_fields) # Creating User Model class User(AbstractBaseUser,PermissionsMixin): # Abstractbaseuser has password, last_login, is_active by default email = models.EmailField(db_index=True, unique=True, max_length=50) first_name = models.CharField(max_length=50) last_name = models.CharField(max_length=25) mobile = PhoneNumberField(null=False) address = models.CharField( max_length=250) is_staff = models.BooleanField(default=True) is_active = models.BooleanField(default=True) is_superuser = models.BooleanField(default=False) objects = CustomUserManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['first_name','last_name','mobile'] … -
What's a proper way to SET aurora_replica_read_consistency in django?
I am looking for a proper way to connect to Aurora from a redundant django app. I have a django app that runs in multiple regions. The Aurora cluster in AWS is configured to have a writable master in one region and a read-only replica with write-forwarding in the other region. This, supposedly, allows apps to "transparently" write to the read-only DB. It's not very transparent because it requires for every session to SET aurora_replica_read_consistency=SESSION. I was hoping to achieve this in the DATABASE session of the django settings file like so: DATABASES = { 'default': { 'ENGINE': 'django_prometheus.db.backends.mysql', 'NAME': 'mydb', 'USER': 'admin', 'PASSWORD': 'DB_PASSWORD', 'HOST': 'DB_HOST', 'PORT': '3306', 'OPTIONS': { 'init_command': 'SET aurora_replica_read_consistency=SESSION', }, }, } However, this throws an error on the aurora master, which is writable. The error states something that you can only set this variable on the read-only replica. I.e. my django container won't even boot on the master. I tried screwing with the connection signals; however, I did not find a way to make it run the SET command as the first thing after any new django connection to the DB. Signals seem to require each app to have a signal handler. The way … -
How to run pytest on Django rest framework app?
I want to run a pytest on 201 a successful post with just a single field in my project. I have a middleware.py which does something with the last object in the list whenever the project is ran. I have pytests at the moment to judge length of the entries but I want to run pytest when a post is successfully posted? I wish to do the same with a GitHub workflow test -
[DjangoRest + React]: Can't delete items and problems posting (error 403 and 301)
I'm building a very simple react + django website. Everything was going fine until today I made some changes to both the backend and frontend to add a third app that displays dummy pictures with a description. Up until that point, I was using axios to make get, post and delete requests with no trouble. I just wrote axios.post("api/", item) and it would post the item, or axios.delete(api/{props.id}) and the item would be deleted. Now, none of these work. At first I started getting 403 errors. Doing some troubleshooting, I tried adding the full url to see if it worked. Post worked. axios.post("localhost:8000/api/", item) now posts the item. The thing is that when I try to delete - axios.delete(localhost:8000/api/{props.id}) -, I get a 301 error. Besides kicking myself for not backing up before, what can I do? These are the backend and frontend codes. Frontend: import React, { useEffect, useState } from "react"; import Header from "./UI/Header"; import NewTask from "./tasks/NewTask"; import TaskList from "./tasks/TaskList"; import axios from "axios"; import classes from "./ToDo.module.css"; function ToDo(props) { const [taskList, setTaskList] = useState([]); const refreshList = async () => { await axios.get("todo/").then((res) => { const filteredData = res.data setTaskList(filteredData); }); }; useEffect(() … -
How to properly pass an enum class to the .HTML template in django
I have an Enum class like this one: models.py . . class Status(Enum): New = 1 Modified = 2 Done = 3 and I want to pass this to the html template in order to iterate over it and use it. so in my views.py I am passing it like so views.py from models import Status . . status_options = Status return render(request, 'orders.html', {status_options':status_options}) and the problem is when I try to use it inside the HTML template I don't get any values I tried the following orders.html {% for status in status_options %} {{ status.name }} {% endfor %} But I don't get any output Can anyone provide me with some guides here, please? -
Configure the parameters and response template of swagger ui in django
I am using drf_spectacular from drf_spectacular.views import ( SpectacularAPIView, SpectacularSwaggerView, ) Can someone please inform me how to custom the JSON "template" that the users see in specific api URLS below? (shown below) For example, in the parameters I want it to be { "number": 0 } and in the response { "alphabet": "a" } -
Modifying Ajax Request for Geonames (show only one city)
I have the following code, and I would like to obtain the information of Geonames, with the streets names of the city of Barcelona. As I have it now, it shows me streets from all over Spain, and I would like it to only show me the one from a certain city, for example Barcelona. That's my actual code: $("#id_start_point").autocomplete({ source: function( request, response ) { $.ajax({ url: "https://secure.geonames.org/search", dataType: "jsonp", data: { featureClass: "R", fcode: "ST", country: "ES", type: "json", maxRows: 10, name_startsWith: request.term, username: "----" }, success: function( data ) { response( $.map( data.geonames, function( item ) { return { label: item.name + (item.adminName1 ? ", " + item.adminName1 : "") + ", " + item.countryName, value: item.name, } })); } }); }, minLength: 2, select: function( event, ui ) { if (ui.item) { $("#id_start_point").val(ui.item.name); } } }); Thanks! -
Django: How to update DB with renaming of choice fields
Say I have a field which choices A, B, and C. In the next iteration, I rename A to D. When I run migrate, all records that hads this field set to A will be set to ----. Is there a way to tell Django to change A to D during the migration? -
How to give permission to users of one group to create users of another group?
I want to create an application in which only organizations can register themselves and then they register their students. I can't find a way to do it. Is it possible to do it without making the organization as admin as multiple organizations can register on app. This is my user model. ''' from django.db import models import uuid from django.contrib.auth.models import User class OrganizationModel(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False) email = models.EmailField(max_length=250,unique=True) user = models.OneToOneField(User,on_delete=models.CASCADE) organization_name = models.CharField(max_length=264,unique=True) is_verified = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['organization'] def __str__(self): return self.organization_name class StudentModel(models.Model): id = models.UUIDField(primary_key=True,default=uuid.uuid4,editable=False) email = models.EmailField(max_length=250,unique=True) user = models.OneToOneField(User,on_delete=models.CASCADE) roll_no = models.CharField(max_length=20) organization_name = models.ForeignKey(OrganizationModel,to_field="organization_name",on_delete=models.CASCADE,related_name="student") created_at = models.DateTimeField(auto_now_add = True) updated_at = models.DateTimeField(auto_now = True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['organization','roll_no'] def __str__(self): return self.organization_name class Meta: constraints = [ models.UniqueConstraint(fields=['organization_name', 'roll_no'], name='unique_student') ] ''' -
Django Celery, Celery beat workers
In celery I've 3 types of tasks first task executes in every 3 minutes and take almost 1 minute to complete, second task is periodic which runs on every monday and takes almost 10 minutes to complete, the third and last one is for sending users emails for register/forget password, I'm confused how many workers/ celery beat instances I should use, can anyone help me out please? -
check if someone already answered the post Question in Django
I am building a discussion Forum where user can ask question and can reply on other's questions. I want to show "Answered" if the Question is already answered and show "Not answered yet" if Question is not answered by any user My model.py class Post(models.Model): user1 = models.ForeignKey(User, on_delete=models.CASCADE, default=1) post_id = models.AutoField post_content = models.CharField(max_length=5000) timestamp= models.DateTimeField(default=now) image = models.ImageField(upload_to="images",default="") def __str__(self): return f'{self.user1} Post' class Replie(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) reply_id = models.AutoField reply_content = models.CharField(max_length=5000) post = models.ForeignKey(Post, on_delete=models.CASCADE, default='') timestamp= models.DateTimeField(default=now) image = models.ImageField(upload_to="images",default="") def __str__(self): return f'{self.user1} Post' View.py def forum(request): user = request.user profile = Profile.objects.all() if request.method=="POST": user = request.user image = request.user.profile.image content = request.POST.get('content','') post = Post(user1=user, post_content=content, image=image) post.save() messages.success(request, f'Your Question has been posted successfully!!') return redirect('/forum') posts = Post.objects.filter().order_by('-timestamp') return render(request, "forum.html", {'posts':posts}) def discussion(request, myid): post = Post.objects.filter(id=myid).first() replies = Replie.objects.filter(post=post) if request.method=="POST": user = request.user image = request.user.profile.image desc = request.POST.get('desc','') post_id =request.POST.get('post_id','') reply = Replie(user = user, reply_content = desc, post=post, image=image) reply.save() messages.success(request, f'Your Reply has been posted successfully!!') return redirect('/forum') return render(request, "discussion.html", {'post':post, 'replies':replies}) -
getting ModuleNotFoundError at /admin/login/. How to solve this error
While login in as a superuser getting this error. Below I have mentioned the installed app and middleware in settings.py and I have gotten the error named ModuleNotFoundError. Exception Type: ModuleNotFoundError Exception Value: No module named 'account.backends' Exception Location: , line 973, in _find_and_load_unlocked Environment: Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 3.2.13 Python Version: 3.8.2 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'chatbot_app', 'account'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] error Traceback (most recent call last): File "D:\PROJECTS\src\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "D:\PROJECTS\src\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\PROJECTS\src\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "D:\PROJECTS\src\lib\site-packages\django\contrib\admin\sites.py", line 398, in login **self.each_context(request), File "D:\PROJECTS\src\lib\site-packages\django\contrib\admin\sites.py", line 316, in each_context 'available_apps': self.get_app_list(request), File "D:\PROJECTS\src\lib\site-packages\django\contrib\admin\sites.py", line 505, in get_app_list app_dict = self._build_app_dict(request) File "D:\PROJECTS\src\lib\site-packages\django\contrib\admin\sites.py", line 450, in _build_app_dict has_module_perms = model_admin.has_module_permission(request) File "D:\PROJECTS\src\lib\site-packages\django\contrib\admin\options.py", line 548, in has_module_permission return request.user.has_module_perms(self.opts.app_label) File "D:\PROJECTS\src\lib\site-packages\django\contrib\auth\models.py", line 458, in has_module_perms return user_has_module_perms(self, module) File "D:\PROJECTS\src\lib\site-packages\django\contrib\auth\models.py", line 221, in user_has_module_perms for backend in auth.get_backends(): File "D:\PROJECTS\src\lib\site-packages\django\contrib\auth_init.py", line 38, in get_backends return get_backends(return_tuples=False) File "D:\PROJECTS\src\lib\site-packages\django\contrib\auth_init.py", line 27, in get_backends backend = load_backend(backend_path) File "D:\PROJECTS\src\lib\site-packages\django\contrib\auth_init.py", line 21, in load_backend return import_string(path)() File "D:\PROJECTS\src\lib\site-packages\django\utils\module_loading.py", … -
Create folder and subfolder with django app
Maybe this is to trivial question, but please assist me. How can I create folder and subfolder in it with django python. When I google I just get some information about folder structure, but it is not what I am looking for. Please share some code examples if it is possible Many thanks. -
How can i make different login for buyer and seller ? then they will redirect their own profile
details about the questions .................................................................................................................................................................................................... ##I follow this post same to same. ###https://areebaseher04.medium.com/how-to-implement-multiple-user-type-registration-using-django-rest-auth-39c749b838ea ''' ##core/models.py) from django.db import models from django.contrib.auth.models import AbstractUser from django.conf import settings class User(AbstractUser): #Boolean fields to select the type of account. is_seller = models.BooleanField(default=False) is_buyer = models.BooleanField(default=False) class Seller(models.Model): seller = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) area = models.CharField(max_length=100) address = models.CharField(max_length=100) description = models.TextField() def __str__(self): return self.seller.username class Buyer(models.Model): buyer = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE) country = models.CharField(max_length=100) def __str__(self): return self.buyer.username #serializers.py from rest_framework import serializers from rest_auth.registration.serializers import RegisterSerializer from rest_framework.authtoken.models import Token from core.models import Seller, Buyer class SellerCustomRegistrationSerializer(RegisterSerializer): seller = serializers.PrimaryKeyRelatedField(read_only=True,) #by default allow_null = False area = serializers.CharField(required=True) address = serializers.CharField(required=True) description = serializers.CharField(required=True) def get_cleaned_data(self): data = super(SellerCustomRegistrationSerializer, self).get_cleaned_data() extra_data = { 'area' : self.validated_data.get('area', ''), 'address' : self.validated_data.get('address', ''), 'description': self.validated_data.get('description', ''), } data.update(extra_data) return data def save(self, request): user = super(SellerCustomRegistrationSerializer, self).save(request) user.is_seller = True user.save() seller = Seller(seller=user, area=self.cleaned_data.get('area'), address=self.cleaned_data.get('address'), description=self.cleaned_data.get('description')) seller.save() return user class BuyerCustomRegistrationSerializer(RegisterSerializer): buyer = serializers.PrimaryKeyRelatedField(read_only=True,) #by default allow_null = False country = serializers.CharField(required=True) def get_cleaned_data(self): data = super(BuyerCustomRegistrationSerializer, self).get_cleaned_data() extra_data = { 'country' : self.validated_data.get('country', ''), } data.update(extra_data) return data def save(self, request): user = super(BuyerCustomRegistrationSerializer, self).save(request) user.is_buyer = True … -
Comment POST request working but comments not appearing under post
I'm relatively new to all this. I'm in the process of creating a social media page with django/python. The ability to create a post in a news feed (i.e. list of posts) and the ability to click on one post to see a more detailed view is working properly. When a user clicks on a single post to see it in more detail they also have the ability to add a comment.Here's the problem: the 'create a comment' input box is working fine, as is the 'post comment' button, but when you click the 'post comment' button my terminal does show that the comment is being posted, but the list of comments never appears. What appears in my Powershell/Terminal when I click the 'post comment' button: [DD/MONTH/2022 HH:MM:SS] "POST /social/post/5 HTTP/1.1" 200 3995 screenshot of what appears on my website my settings.py installed apps: INSTALLED_APPS = [ 'social', 'landing', 'crispy_forms', 'allauth', 'allauth.account', 'allauth.socialaccount', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'crispy_bootstrap5', 'allauth.socialaccount.providers.instagram', 'allauth.socialaccount.providers.linkedin', 'allauth.socialaccount.providers.facebook', ] my views.py: from django.shortcuts import render from django.urls import reverse_lazy from django.contrib.auth.mixins import UserPassesTestMixin, LoginRequiredMixin from django.views import View from django.views.generic.edit import UpdateView, DeleteView from .models import Post, Comment from .forms import PostForm, CommentForm class … -
Django corsheaders not affecting staticfiles - CORS errors only on static content
I've been successfully using CORS_ORIGIN_ALLOW_ALL = True with my views and I have been able to serve Django views to other domains, no problem. Now, I replaced a call to view to just getting a static file, and this is failing with a CORS error. This is not a problem in production, because I don't use Django to serve static files in production. Yet, how can I enable CORS_ORIGIN_ALLOW_ALL for staticfiles in development? -
digital ocean deployment error: 502 Bad Gateway
I had my site up and running, but the admin CSS was not loading, I am not sure what I did that the server did not agree, but now the entire site is down with a 502 Bad Gateway message. Here are the content of some key files sudo nano /etc/systemd/system/gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target gunicorn.service file (sudo nano /etc/systemd/system/gunicorn.service) [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=eson Group=www-data WorkingDirectory=/home/eson/example ExecStart=/home/eson/example/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ example.wsgi:application [Install] WantedBy=multi-user.target Here is what Nginx has sudo nano /etc/nginx/sites-available/example: server { server_name www.example.com example.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/eson/example; } location /media/ { root /home/eson/example; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/example.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/example.com/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.example.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = example.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name www.example.com example.com; return 404; # managed by Certbot … -
Django Can't recreate Database table?
Unfortunately I deleted two database table from my phpmyadmin database, I deleted migration file from corresponding app, and run this two command python manage.py makemigrations app_name python manage.py migrate But still cant recreate my database table. how to fix this issue? -
Django throw OSError: [Errno 22] Invalid argument: '/proc/52826/task/52826/net'
After starting project django throw OSError: [Errno 22] Invalid argument: '/proc/52826/task/52826/net' or FileNotFoundError: [Errno 2] No such file or directory: '/proc/5390/task/56199' Full trace of OSError: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 61, in execute super().execute(*args, **options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 96, in handle self.run(**options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 103, in run autoreload.run_with_reloader(self.inner_run, **options) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 638, in run_with_reloader start_django(reloader, main_func, *args, **kwargs) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 623, in start_django reloader.run(django_main_thread) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 329, in run self.run_loop() File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 335, in run_loop next(ticker) File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 375, in tick for filepath, mtime in self.snapshot_files(): File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 391, in snapshot_files for file in self.watched_files(): File "/home/alex/projects/project/backend/venv/lib/python3.8/site-packages/django/utils/autoreload.py", line 294, in watched_files yield from directory.glob(pattern) File "/usr/lib/python3.8/pathlib.py", line 1140, in glob for p in selector.select_from(self): File "/usr/lib/python3.8/pathlib.py", line 587, in _select_from for p in successor_select(starting_point, is_dir, exists, scandir): File "/usr/lib/python3.8/pathlib.py", line 535, in _select_from entries = list(scandir_it) OSError: [Errno 22] Invalid argument: '/proc/52826/task/52826/net' Trace of … -
How to run pytest on Get or Post 200 in Django?
I want pytest to call a function that can run if a REST API post or entry in django is successfull? My project is a django rest framework project and the field is routed as a URL having a single field only My field is called raddress as you can see in the urls.py below from django.contrib import admin from django.urls import path, include from rest_framework import routers from rframe import views ###this gets rid of admin authentication class AccessUser: has_module_perms = has_perm = __getattr__ = lambda s,*a,**kw: True admin.site.has_permission = lambda r: setattr(r, 'user', AccessUser()) or True ###### router = routers.DefaultRouter() router.register(r'raddress', views.RaddressViewSet, basename='raddress') #router.register(r'admin',) #router.register(r'users', views.CheckRaddr) #router.register(r'raddress', views.OrganizationViewSet, basename='raddress') urlpatterns = [ path(r'', include(router.urls)), path('admin/', admin.site.urls), As you can see the view is registered as a URL and I don't know how can I test if the post is successful -
Django middleware runs before drf permissions
I have a middleware class that looks something like this: class DogMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_view(self, request, view_func, view_args, view_kwargs): dog_id = view_kwargs.get("dog_id") if dog_id is not None: dog = Dog.objects.get(id=dog_id) request.dog = dog I have a view that looks something like this: class DogDetail(APIView): def get(self, request, dog_id, *args, **kwargs): return "some nice doggy info" My permissions default to IsAuthenticated: "DEFAULT_PERMISSION_CLASSES": ( "rest_framework.permissions.IsAuthenticated", ), When I call the DogDetail view from a logged-out state, with a dog that doesn't exist, I get a 500 error, and a DoesNotExist exception. I infer from this that the middleware runs before the permissions. My questions: Is this expected behavior? If not, what am I doing wrong? If so, it is very un-ideal, because it would be very easy to leak data through middleware. In my example, it would be very easy for a un-authenticated user to determine which dog_id's existed. What is a good way to mitigate this? I guess I could check for authentication in the middleware, and pass unauthenticated requests through without getting the dog_id? That feels like I'm headed for a deep bug in the future where middleware runs properly, … -
How does Instagram use django for both web and mobile app?
I found that Django rest framework is needed to build both Progressive web app and mobile app.. Instagram uses django for backend, React.js for web, native for mobile Here is the question.. DRF might be too slow to be used by millions of people.. isnt it? How instagram sticks django with both PWA and mobile? What tech they use? -
Is it possible to share the same session for multiple domain names in Django?
I have a Django application (domain name: app.com) that allows users to create a template and host it on a subdomain (example.app.com) using the Django sites framework. Using this option: SESSION_COOKIE_DOMAIN=".app.com" The sites under this domain share the same session but once the user hosts the template on his domain name (custom.com) each site has its own session. Is it possible to make all the sites of this Django application share the same session? Why? So I don't have to log in again each time I visit one of these websites. I tried this middleware but still not working. import time from django.conf import settings from django.utils.cache import patch_vary_headers from django.utils.http import http_date from django.contrib.sessions.middleware import SessionMiddleware class SessionHostDomainMiddleware(SessionMiddleware): def process_response(self, request, response): """ If request.session was modified, or if the configuration is to save the session every time, save the changes and set a session cookie. """ try: accessed = request.session.accessed modified = request.session.modified except AttributeError: pass else: if accessed: patch_vary_headers(response, ('Cookie',)) if modified or settings.SESSION_SAVE_EVERY_REQUEST: if request.session.get_expire_at_browser_close(): max_age = None expires = None else: max_age = request.session.get_expiry_age() expires_time = time.time() + max_age expires = http_date(expires_time) # Save the session data and refresh the client cookie. # Skip session … -
How can I count total likes?
I added a like button to my blog. It's working perfectly but I can't count the total number of likes present. What should I do now? models.py: class FAQ(models.Model): likes = models.ManyToManyField(User,default=None, related_name="faqLIKES") views.py: def index(request): allFAQ = FAQ.objects.all() context = {"allFAQ":allFAQ} return render(request,'0_index.html',context) def likeView(request, pk): post = get_object_or_404(FAQ, id=request.POST.get('faqLIKEid')) post.likes.add(request.user) return redirect("/") -
Django initial migrate of existing Application
I have an application with everything working on local dev machine, and I am trying to set it up on another dev machine with fresh DB (Postgres). I wasnt able to run migrations due to a cannot find field error, so i removed all migrations and tried to make them again, but same error. django.db.utils.ProgrammingError: relation "questionnaire_projectquestionanswerchoice" does not exist LINE 1: ...rojectquestionanswerchoice"."id") AS "count" FROM "questionn... So it seems that makemigrations checks code for issues before it makes them, and obviously it wont find them and always errors. The culprit is below, and commenting out, then doing the migrations works but is a bit of a hack, so if i ever need to do again i would have to follow same process. I have left the culprit commented below. This code works, and then i have to uncomment after. Is there an official way to handle this? class ProjectQuestionMostUsedAnswerChoiceViewset(viewsets.ModelViewSet): # dupes = ( # models.ProjectQuestionAnswerChoice.objects.values("name") # .annotate(count=Count("id")) # .order_by("-count") # .filter(count__gt=0)[:10] # ) # queryset = ( # models.ProjectQuestionAnswerChoice.objects.filter( # name__in=[item["name"] for item in dupes] # ) # .distinct("name") # .order_by("name") # ) queryset = models.ProjectQuestionAnswerChoice.objects.all() serializer_class = serializers.ProjectQuestionAnswerChoiceSerializer filter_backends = ( filters.QueryParameterValidationFilter, django_filters.DjangoFilterBackend, ) filterset_fields = { "id": …