Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
allauth tests return errors
For changing things like translations in forms i included allauth app directly in my project but now when i want to run tests it returns lots of errors i think it runs every test while i am not using social logins it tests it and fails my project on Github : github.com/MrHamedi/VSC/tree/dev Shall i delete allauth test to resolve this problem ? or what should i do so allauth tests only test allauth.account tests -
superuser authenticate in class based view
I am working on blog project in which I added an add post which add post now I want only the superuser can add post and that page is visible only to superuser. 1st Method Views.py class AddPostView(CreateView): model = Post template_name = 'MainSite/add_post.html' fields = '__all__' this is my current view I am able to achieve authenticate for superuser using 2nd method 2nd Method class AddPostView(View): def get(self,request): if request.user.is_superuser == True: return render(...) else: pass How can I achieve the same result using 1st method.I tried using LoginRequiredMixin but nothing is happening . I just import LoginRequiredMixin and use it like this . class Addpost(CreateView,LoginRequiredMixin): ... Thanks in advance and advice will be helpful. -
Django, DRF: two similar models views, separate endpoints or not
There are two similar models as shown below. class ProductVideo(models.Model): ... class UserVideo(models.Model): ... Should it be handled dynamically with query_params in one View? # /videos/:id/comment?product=1 class CommentView(generics.CreateAPIView): def get_serializer_class(self): s = self.request.query_params.get("product") if s: return ProductVideoSerializer else: return UserVideoSerializer Or should I create one View at a time? # /videos/product/:id/comment class ProductVideoCommentView(generics.CreateAPIView): ... # /videos/user/:id/comment class UserVideoCommentView(generics.CreateAPIView): ... -
Celerybeat Multiple schedules of the same task
I got following Celery beat task which cleans 1000 items daily at 1 AM: from celery.schedules import crontab from .celery import app as celery_app celery_app.conf.beat_schedule['maintenance'] = { 'task': 'my_app.tasks.maintenance', 'schedule': crontab(hour=1, minute=0), 'args': (1000,) } I want to clean additional 5000 items every Sunday at 5PM. Is there a way to add second schedule? 'schedule': crontab(hour=17, minute=0, day_of_week='sunday'), 'args': (5000,) And how to ensure they won't overlap? -
Local chat on machine used for Outline VPN
I have a remote Ubuntu server on Linode. I use it to provide Outline VPN for me and my friends. Can I somehow create a web chat on this machine so that only users connected by Outline can use it? I tried to run django local server on it, but I couldn't connect. -
Inconsistance between `request.user` and `request.session` in Django
I do understand that login() will attach User to request.session and request.user after authenticate() successfully validate credentials. I am wondering will there be any occasions where request.user becomes anonymous user and request.session still has User attached ? I encountered this myself. If answer to above is yes, then when request.user.is_authenticated == False, should we flush the existing session, and prompt for login again to avoid someone use previously stored session. or we can directly attach user in request.session to request.user to make it logged_in user. thanks for your insights. -
AttributeError: 'JSONParser' object has no attribute 'parser'
when i post data from postman application then this error is accour code elif request.method == 'POST': data = JSONParser().parser(request) serializer = ArticleSerializer(data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) **error ** data = JSONParser().parser(request) AttributeError: 'JSONParser' object has no attribute 'parser' -
Django. ImportError: attempted relative import beyond top-level package
I'm a newbie. And I just started writing a django project. It is called the iRayProject and consists of two applications iRay_user_authentication and iRay_working_with_notes: project structure here iRay_user_authentication - this is a standard django app for registration Here is his urls.py from django.urls import path from .views import login_user, registration urlpatterns = [ path('', login_user, name='login_user'), path('registration', registration, name='registration'), ] In views.py registered user using redirect I want to send to the second application of the project from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth.models import User from django.db import IntegrityError from django.contrib.auth import login, logout, authenticate from ..iRay_working_with_notes.views import list_notes def login_user(request): if request.method == 'GET': return render(request, 'iRay_user_authentication/login.html', {'form': AuthenticationForm}) def registration(request): if request.method == 'GET': return render(request, 'iRay_user_authentication/registration.html', {'form': UserCreationForm}) else: if '_guest' in request.POST: pass else: if request.POST['password1'] == request.POST['password2']: try: user = User.objects.create_user(request.POST['username'], password=request.POST['password1']) user.save() login(request, user) return redirect(list_notes) except IntegrityError: return render(request, 'iRay_user_authentication/registration.html', {'form': UserCreationForm, 'error': 'name is busy ' }) else: return render(request, 'todo_app/registration.html', {'form': UserCreationForm, 'error': 'passwords not math'}) But when trying to import a function from the second views.py from django.shortcuts import render def list_notes(request): return render(request, 'iRay_working_with_notes/list_notes.html') I get an error: ImportError: attempted relative import beyond … -
Run Django with Nginx Web SERVER 502 Bad Gateway
How to fix issue 502 Bad Gateway nginx/1.18.0 (Ubuntu) for running Django? Nginx error log: *29 upstream prematurely closed connection while reading response header from upstream, client: x.x.x.x, s> 2022/03/18 15:33:51 [error] 890#890: *13 upstream prematurely closed connection while reading response header from upstream, client: x.x.x.x,> 2022/03/18 15:42:18 [error] 1976#1976: *2 upstream prematurely closed connection while reading response header from upstream, client: x.x.x.x, > 2022/03/18 15:43:10 [error] 1976#1976: *2 upstream prematurely closed connection while reading response header from upstream, client: x.x.x.x, > 2022/03/18 15:44:35 [error] 1976#1976: *7 upstream prematurely closed connection while reading response header from upstream, client: x.x.x.x> -
Django - implementation of last changes tracker in HTML file
I am looking for a solution that will allow me to create a section in my HTML file with the latest updates in my app. I checked some packages here on djangopackages.org but I am not quite sure which app should I use. The idea is that if there will be any article added or updated then in the latest updates section the information will appear automatically as: '5 new articles have been recently added' or '2 articles have been updated' or'3 users joined our website'. In total, I have 4 models (including the user model) in my Django app that I want to track and display updates in my HTML (homepage, TemplateView) file. What would you recommend? -
'somewhere' gives error : No module named 'where' for my django app
When I import handle_uploaded_file from 'somewhere library on my linux machine.) getting following error when trying to run my django application.)- -
Unable to complete paypal transaction - Python Django - Was not able to redirect back to webapp to perform capture
We have implemented django oscar to include paypal recurring payment. On sandbox, everything works on well. Here is the flow we have implemented but can never get to step 3 and stuck in step 2 after "Agree & Continue" (which basically authorize the card). Call SetExpressCheckout, setting up the billing agreement in the request [L_BILLINGTYPE0=RecurringPayments]. Returns a token, which identifies the transaction, to the merchant. Redirect buyer's browser to: https://www.paypal.com/cgi-bin/webscr?cmd=_express-checkout appended with the token returned by SetExpressCheckout. Displays login page and allows buyer to select payment options and shipping address. <--- stuck here Redirect buyer's browser to returnURL passed to SetExpressCheckout if buyer agrees to payment description. Call CreateRecurringPaymentsProfile in the background (without further actions from the user). Returns ProfileID in CreateRecurringPaymentsProfile response for the successfully created profile (PROFILEID=I-1NNDL8LGNX35). Display successful transaction page (Thank you page). Listen to PayPal IPN notifications to trigger merchant's server logic for future successful/failed/canceled/suspended payments. So in step 2, when I click "Agree & Continue", it has a spinner processing, I can see then on my phone my credit card is charged. But then, nothing happens, it doesnt redirect, so it stays the same. When I click again "Agree & Continue", it then has "Sorry, … -
Can you deploy django apps though shinny server
I want to deploy a django application but the server it's to be deployed in is currently hosting several other r applications. Is there a way to configure shiny-server to serve the django app? My knowledge of r is very limited and nobody knows how the server was set up and configured -
Who to manage changing url while handling old url
I have a url Ex /this-is-url-12334 Now I want to change this url to Ex /this-is-url But I don't want that any old url to show 404 what I want that if anyone who use old url should redirect to new url What approach should I take -
How to implement Category, SubCategory and Product in django
class Category(models.Model): name= models.CharField(max_length=50) @staticmethod def get_all_categories(): return Category.objects.all() def __str__(self): return self.name class Products(models.Model): name = models.CharField(max_length=60) price= models.IntegerField(default=0) category= models.ForeignKey(Category,on_delete=models.CASCADE,default=1 ) How can I now add subcategory to this heirarchy -
How to set html lang attribute in Django template?
I wrote a Django application that serves translated content for German users, and English content for everyone else. Currently I use a base template containing: <!DOCTYPE html> <html lang="en"> Obviously this sets the wrong lang in case the content is served as German. Possibly I could try something like <html lang="{{ 'de' if request.LANGUAGE_CODE == 'de' else 'en' }}"> but this feels clumsy and hard to maintain in case more languages are added. What would be a simple way to set <html lang> to the actual language served? -
Unable to retrieve username and password using POST in Django and Unity as Frontend
Hi there i am building an app in unity and am using Django as backend, i am new to Django and i was trying to retrieve username and password but i get the following error in terminal: However if i use csrf_exempt decorator, it works fine but this opens up my validate view to csrf attacks, is there any secure way? thanks Error: Forbidden (CSRF cookie not set.): /backend/fetchdata/ [18/Mar/2022 12:50:13] "POST /backend/fetchdata/ HTTP/1.1" 403 2870 Here is my view.py: from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt,csrf_protect def testhello(request): return HttpResponse("Hello from Django") # @csrf_exempt def validate(request): username= request.POST["user"] password = request.POST["pass"] # print(password) filelol = open("C://Users//Jay//Desktop//data.txt","w+") filelol.write(username) ``` -
django / joined query
Checked all docs and questions/answers here but not succesfull. Need your help. I've experience in pure PHP and MySQL, but frameworks kills me. My models; class Projects(models.Model): id = models.AutoField(primary_key=True) subject= models.CharField(max_length=50) sender= models.ForeignKey(User, on_delete=models.CASCADE)#inserting django's default user id This is django's default but edited auth_user table CREATE TABLE "auth_user" ( "id" integer NOT NULL PRIMARY KEY AUTOINCREMENT, "password" varchar(128) NOT NULL, "last_login" datetime NULL, "is_superuser" bool NOT NULL, "username" varchar(150) NOT NULL UNIQUE, "first_name" varchar(150) NOT NULL, "last_name" varchar(150) NOT NULL, "email" varchar(254) NOT NULL, "is_staff" bool NOT NULL, "is_active" bool NOT NULL, "date_joined" datetime NOT NULL, "tck_no" varchar(11) NOT NULL ) When I want to fetch my project, I use normally; SELECT u.*, p.* FROM users u, projects p WHERE u.id=p.sender; Above code returns all fields on both table normally. In django viewmodel; @login_required(login_url="/login/") def others_projects(request): projectlist = Projects.objects.all().filter(sender_id=request.user.id) Above code returns Projects table fields, but can not figured how to get first_name field matched record from users foreign key used? -
Django - Add classes to inline only if qs len is more than 5
For TaskInline I'd like to display it collapsed if there are more than 5 elements: from django.contrib import admin from django.contrib.auth.models import User from django.db import models class Task(models.Model): title = models.CharField(max_length=50) description = models.TextField() performer = models.ForeignKey(User, on_delete=models.CASCADE) class TaskInline(admin.TabularInline): model = Task def get_queryset(self, request): qs = super().get_queryset(request) if len(qs) > 5: self.classes = 'collapse', return qs @admin.register(User) class UserAdmin(admin.ModelAdmin): inlines = TaskInline, But trick that is implemented in get_queryset method seems not working (it seems this method selects all the items of Task model). Where should I compare len to add classes? -
Use variable as key name for model
I have the method like this. @classmethod def get_my_msg(cls): return cls.objects.latest("updated_at").my_msg Now , I want to give the variable to function and get the data dynamically such as @classmethod def get_my_msg(cls,key): return cls.objects.latest("updated_at").{key} // use variable here Is it possible? -
Django: How do I make a foreign key dynamic? [duplicate]
How can I dynamically tie two or more models of a video together with a foreign key, as shown below? class ProductVideo(models.Model): ... class UserVideo(models.Model): ... class History(models.Model): video = models.ForeignKey('ProductVideo or UserVideo') ... class Favorite(models.Model): video = models.ForeignKey('ProductVideo or UserVideo') ... -
Django: Using a nested TextChoice class values in a Meta class
I used to declare TextChoices classes inside the model class like this: class Order(models.Model): class OrderStatusChoices(models.TextChoices): NEW = 'NEW' CLOSED = 'CLOSED' CANCELLED = 'CANCELLED' status = models.CharField(choices=OrderStatusChoices.choices, max_length=9) In this case, I was instantiating the class as: from models import Order order = Order(status=Order.OrderStatusChoices.NEW) Now I need to use the TextChoices values in the Meta class to check the database constraint: class Order(models.Model): class OrderStatusChoices(models.TextChoices): NEW = 'NEW' CLOSED = 'CLOSED' CANCELLED = 'CANCELLED' status = models.CharField(choices=OrderStatusChoices.choices, max_length=9) class Meta: constraints = [ models.CheckConstraint( name='%(app_label)s_%(class)s_status_valid', check=models.Q(status__in=OrderStatusChoices.values) ) ] However, if the status class is nested within the order class, the textchoice cannot be referenced (Unresolved reference 'OrderStatusChoices' ). This can be solved by taking the status class out of the order class: class OrderStatusChoices(models.TextChoices): NEW = 'NEW' CLOSED = 'CLOSED' CANCELLED = 'CANCELLED' class Order(models.Model): status = models.CharField(choices=OrderStatusChoices.choices, max_length=9) class Meta: constraints = [ models.CheckConstraint( name='%(app_label)s_%(class)s_status_valid', check=models.Q(status__in=OrderStatusChoices.values) ) ] But this does not make it very convenient to import (for me, maybe I'm wrong and this is normal) the order model without status textchoice and in order to create an instance of the order class, you need to import both the order model and the status textchoice: from models … -
footer is not fixed to bottom
<footer class="footer"> <!-- Copyright --> <div class="navbar fixed-bottom my_footer"> <p class="text-center"> © 2022 Copyright: Anoop Electronics </p> </div> <!-- Copyright --> </footer> this footer is not fixed to the bottom. It follows when its scrolling down/up. https://ecommerce9.pythonanywhere.com/shop/ -
Nginx www redirect to non-www, browser says your connection to this site is not secure, Django
I can't connect to my site with www.example.com, it says 'not secure' only https://example.com works. At first I didn't set the DNS A record for www to redirect to my server ip so www.example.com wasn't working, but once I added the www A record it now shows Not Secure with the red https line through it when I go to www.example.com. Here is my myapp.conf from nginx sites-available: upstream myapp_app_server { server unix:/apps/myapp/myapp_env/run/gunicorn.sock fail_timeout=0; } server { listen 80; listen [::]:80; server_name example.com www.example.com; return 301 https://$server_name$request_uri; } server { listen 443 ssl http2; listen [::]:443 ssl http2; server_name example.com; ssl_certificate /etc/letsencrypt/live/example.com-0001/fullchain.pem; ssl_certificate_key /etc/letsencrypt/live/example.com-0001/privkey.pem; include /etc/letsencrypt/options-ssl-nginx.conf; ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; client_max_body_size 4G; access_log /etc/nginx/logs/nginx-access-prod.log; error_log /etc/nginx/logs/nginx-error-prod.log; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /var/www/html/myapp/static/; } location /media/ { alias /var/www/html/myapp/media/; } location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto https; proxy_set_header Host $http_host; proxy_redirect off; if (!-f $request_filename) { proxy_pass http://myapp_app_server; break; } if ( $host !~* ^(example.com|www.example.com)$ ) { return 444; } } } Here is my nginx.conf from etc/nginx: user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; } http { sendfile on; tcp_nopush on; types_hash_max_size 2048; include /etc/nginx/mime.types; default_type application/octet-stream; … -
" 'User' object has no attribute 'products' 'User' "
When I run my code I keep getting this error " 'User' object has no attribute 'products' 'User' " I don't know where I went wrong please help me. Below is are my user's app codes Because I am trying to build the website to display products onto the user's profile page so the user can see the products they have got and also display these products on the main home page but I got stuck with this error. "'User' object has no attribute 'products'" **View.py** def register(request): if request.method == 'POST': form = UserRegisterForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request, f'{username}! your account created') return redirect('login') else: form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) @login_required def profile(request): users = request.user products = users.products.all() return render(request, 'users/profile.html', {'user': users, 'products': products}) @login_required def add_product(request): if request.method == 'POST': form = ProductForm(request.POST, request.FILES) if form.is_valid(): product = form.save(commit=False) product.users = request.user product.slug = slugify(product.title) product.save() return redirect('profile') else: form = ProductForm() return render(request, 'users/add_product.html', {'form': form}) Models.py from django.contrib.auth.models import User from django.db import models class Users(models.Model): name = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) created_by = models.OneToOneField(User, related_name='users', on_delete=models.CASCADE) class Meta: ordering = ['name'] def __str__(self): return self.name forms.py This …