Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'PeopleViewSet' should either include a `queryset` attribute, or override the `get_queryset()` method
** Models.py ** ''' from django.db import models class Person(models.Model): color = models.ForeignKey(Color, null=True, blank=True, on_delete=models.CASCADE) name = models.CharField(max_length=100) age = models.IntegerField() def __str__(self): return self.name ''' ** views.py ** ''' from rest_framework import viewsets from .models import * from .serializers import * class PeopleViewSet(viewsets.ModelViewSet): serializer_class = PersonSerializer quaryset = Person.objects.all() ** serializers.py ** ''' from rest_framework import serializers from .models import * class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' ''' ** urls.py ** ''' from django.urls import path, include from app import views from rest_framework.routers import DefaultRouter router = DefaultRouter() router.register('person', views.PeopleViewSet, basename='person') urlpatterns = router.urls urlpatterns = [ path('', include(router.urls)), ] ''' I'm getting this error 'PeopleViewSet' should either include a queryset attribute, or override the get_queryset() method. What is my mistake? -
Is it possible to redirect users to OTP function before accessing password reset form in Django views.py?
Suppose I have 2 Functions in my views.py I just want user's first attempt first the function (OTP function) and then go to the second form ( password change form ) even after they type URL for PassChangeForm in browser url , they directly redirect to OTP function Suppose I have 2 Functions in my views.py the first function is to enter OTP and the second function is to get the password reset form I want user to first attempt OTP enter the form and then after go for the password reset form path('PassChangeForm/',views.PassChangeForm, name="PassChangeForm" ), Even they PassChangeForm type in Browser url they get automatically redirected on OTP form -
why can't i run my django project using python manage.py runserver?
I'm trying to run a django file that is given to me to work on, but the moment i run python manage.py runserver it show an error as stated below: C:\Python39\python.exe: can't open file 'C:\Users\tayry\Todo-List-With-Django-master\manage.py': [Errno 2] No such file or directory anyone know how to fix this issue? -
Template does not exist error been trying to solve for two hours
TemplateDoesNotExist at /login/ users/login.html Request Method: GET Request URL: http://127.0.0.1:8000/login/ Django Version: 4.2.1 Exception Type: TemplateDoesNotExist Exception Value: users/login.html Exception Location: C:\Users\a\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\template\loader.py, line 47, in select_template Raised during: django.contrib.auth.views.LoginView Python Executable: C:\Users\a\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.3 Python Path: ['C:\Users\a\Desktop\ecommerce', 'C:\Users\a\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\a\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\a\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\a\AppData\Local\Programs\Python\Python311', 'C:\Users\a\AppData\Local\Programs\Python\Python311\Lib\site-packages'] views.py from django.shortcuts import render , redirect from django.contrib import messages from django.contrib.auth.decorators import login_required from django.http import HttpResponse from . forms import UserRegistrationForm # Create your views here. def register(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) if form.is_valid(): form.save() username = form.cleaned_data.get('username') messages.success(request,f'Your account has been created!') return redirect('login') else: form = UserRegistrationForm() return render(request,'users/register.html',{'form':form}) @login_required def profile(request): return render(request,'users/profile.html') urls.py from django.contrib import admin from django.urls import path,include from django.contrib.auth import views as auth_views from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/', user_views.profile, name='profile'), path('login/', auth_views.LoginView.as_view(template_name='users/login.html'),name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'),name='logout'), path('', include('eshop.urls')), ] -
Django rest_framework serializer dynamic depth
I am using a ModelSerializer to serialize a model. How do I have depth = 1 when retrieving a single instance, and depth = 0 when retrieving a list. from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ['id', 'first_name', 'last_name', 'organizaton'] depth = 1 # <--- How to change this to 0 for the list? -
Active Django user after successful PayPal payment
I am attempting to implement a PayPal gateway after user sign-up for a webapp. Once the user registration form is submitted, a signal sets the user to inactive (on purpose). I want to set the user to active after a successful PayPal payment; however, Im having trouble identifying how to get the user id to the receiver to activate the user account since the PayPal button has a separate landing page (and the user isn't authenticated at this point). Is it possible to pass the newly created user instance from the registration page as context to the payment-process page? Any help would be greatly appreciated. Code below: VIEWS def register(request): if request.method == "POST": form = RegisterForm(request.POST) if form.is_valid(): form.save() return redirect("process-payment") else: # create empty form for user to fill in form = RegisterForm() return render(request, "register/register.html", {"form": form}) def payment_done(request): return redirect('login') def process_payment(request): host = request.get_host() paypal_dict = { "cmd": "_xclick-subscriptions", 'business': settings.PAYPAL_RECEIVER_EMAIL, "a3": "1.75", # monthly price "p3": "1", # duration of each unit (depends on unit) "t3": "M", # duration unit ("M for Month") "src": "1", # make payments recur "sra": "1", # reattempt payment on payment error "no_note": "1", # remove extra notes (optional) … -
I made simple student work automation with pycharm python with buttons. I need to open this project with django, but I can't install django
I have a simple button student work automation project that I made with pycharm python. This is my school homework. I need to make a django connection and open it in django, I couldn't manage it, I did it all over again, I can't manage the url definitions, can anyone help me please I installed django with my research, made some progress and got this error '' The install worked successfully! Congratulations! You are seeing this page because DEBUG=True is in your settings file and you have not configured any URLs '' but now i deleted django, i went back to the beginning, can anyone install django from the beginning please -
How can I specify OneToMany relationship in Django models?
I am using Django for fetching data from the join of three tables. Table1, Table2, and Table3 all have a column name cols. I want to join all three tables and have to define the models for that. I can use models.ForeignKey but as per the documentation: The field on the related object that the relation is to. By default, Django uses the primary key of the related object. If you reference a different field, that field must have unique=True. But the field cols in Table3 is not unique, there can be duplicate values for the field. Then how can I do the OneToMany relationship for these tables? I could use ManyToMany but then it violates the relationship between Table1 and Table2 as they have unique values for the column. -
Amazon S3 Bucket static files not accessible from my Heroku-hosted Django app
Django app hosted on Heroku. All static files are in an AWS S3 bucket with "Block all public access: Off", ACL set to "allow list/read" across the board, and the "access: public" tag is displayed under permissions. Launching Django app from Heroku dashboard is met with Bad request 400 error. Launching with debug=True shows more: "SuspiciousOperation at / Attempted access to '/img/faviconB-32x32.png' denied." Removing the link tag for that exact resource in my index.html is no improvement, same error occurs for any remaining static files. I can access any item in the bucket with its object url without issue, for example: https://heroku-brainteasers-app-tmurphy.s3.us-east-2.amazonaws.com/static/img/brainteaserslogo.jpg my django settings.py: AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = 'heroku-brainteasers-app-tmurphy' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_SIGNATURE_VERSION = 's3v4' AWS_DEFAULT_ACL = None # Use S3 bucket's setting AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' STATICFILES_STORAGE = 'mydjangosite.storage_backends.StaticStorage' DEFAULT_FILE_STORAGE = 'mydjangosite.storage_backends.PublicMediaStorage' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/static/' MEDIA_URL = f"https://{AWS_S3_CUSTOM_DOMAIN}/media/" STATICFILES_DIRS = [ BASE_DIR / 'static', ] If I remove all the static file 's from my html, taking the bucket out of the loop entirely, the app loads and I see the home page. It seems like the django settings are failing to request the resources properly from my bucket, … -
Check if an id is in another model's field, and get the connected values
Given these two models: class Event(models.Model): title = models.CharField(max_length=200) class dateEvent(models.Model): venue = models.ForeignKey(Venue, on_delete=models.CASCADE,null=True, blank=True) event = models.ForeignKey('Event', on_delete=models.CASCADE) class Venue(models.Model): venue_name = models.CharField(max_length=50) How can I filter only the venues that appear in a dateEvent? And how can I get the Event details linked to a specific venue? Right now I attempted this, which returns noniterable and non exists error: venues = list(Venue.objects.filter(dateevent__venue.icontains=id).values('venue_name', 'dateevent__event.id') -
AttributeError at /news/nasafning-rni-bilindi/ 'list' object has no attribute 'comment'
AttributeError at /news/nasafning-rni-bilindi/ 'list' object has no attribute 'comment' Request Method: GET Request URL: http://127.0.0.1:8000/news/nasafning-rni-bilindi/ Django Version: 4.2.1 Exception Type: AttributeError Exception Value: 'list' object has no attribute 'comment' Exception Location: C:\Users\Victus\faculty_news\news\views.py, line 91, in detail Raised during: news.views.detail Python Executable: C:\Users\Victus.virtualenvs\faculty_news-HS6Ih4-T\Scripts\python.exe Python Version: 3.10.0 Python Path: ['C:\Users\Victus\faculty_news', 'C:\Users\Victus\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\Victus\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\Victus\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\Victus\AppData\Local\Programs\Python\Python310', 'C:\Users\Victus\.virtualenvs\faculty_news-HS6Ih4-T', 'C:\Users\Victus\.virtualenvs\faculty_news-HS6Ih4-T\lib\site-packages'] Server time: Sat, 27 May 2023 21:35:47 +0500 Traceback Switch to copy-and-paste view C:\Users\Victus.virtualenvs\faculty_news-HS6Ih4-T\lib\site-packages\django\core\handlers\exception.py, line 55, in inner response = get_response(request) … Local vars C:\Users\Victus.virtualenvs\faculty_news-HS6Ih4-T\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars C:\Users\Victus\faculty_news\news\views.py, line 91, in detail comments = news.comment.filter(active=True) nothing nothing nothing -
Django - "" appearing under <body> tag and adding space to page
I noticed this when i was getting spacing above the navbar, after Inspecting the page i found a random "" under tag which is causing to add a space on the page. This doesnt show up if i stick all the html in one file (home.html) and runserver. However, when i start using extends or includes with my base.html, "" pops up. Any ideas on possible fixes? I am using Visual Studio Community 2022 - Version 17.5.2 Inspect Page <!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Test</title> </head> Byte Order Mark - it might have something to do with utf-8 with BOM? ive tried copy/pasting in notepad and saving as.. utf-8 without BOM and then pasting back into the html file but it didnt work I used: $(document).ready(function () { let html = document.querySelector("html"); let cleanHTML = html.innerHTML.replace(/[\u200B-\u200D\uFEFF]/gim, ''); html.innerHTML = cleanHTML; }) seems to be removing the problem but i would like to find the root cause of why this is happening instead of pasting code in every project -
Add google domain to Django app hosted in AWS EC2 Ubuntu
Add custom domain name to a Django application that is hosted in AWS EC2 - Ubuntu I deployed the Django application from GitHub to AWS EC2 server which is based on Ubuntu. After deployment, the app is able to run on my local. I also added the custom google domain name into the allowed hosts from Django settings.py and redeployed the changes to the virtual environment but the custom google domain still did not work. Is there anything else that I need to do to successfully launch the custom google domain? Your suggestions and insights are greatly appreciated. Thank you! -
Error on railway with Django projectNixpacks build failed
error nixpacks Error on railway with Django project Nixpacks build failed i made all steps following this video https://www.youtube.com/watch?v=NUqtNglEcCU my files files i tried on Railway and Vercel, yesterday i was having the error ModuleNotFoundError: No module named 'widget_tweaks', so i tried on Vercel and failed, so when i go back to Railway the error changed to Nixpacks build failed requirements.txt -
How safe is setting consumer_timeout to long values like 10years
Im guessing it's there for a reason, but I can't seem to find any answer to this question. In short I have a django app where users get set badges that months or even years down the line need to be auto removed for which I use celery. My question is will setting consumer_timeout to large values pose a risk for those actions to not be performed or performed early/late (mind you a delay of even a few hours shouldn't be a big deal for long duration tasks) -
Django Python Arabic Search
I have fields name and author which are in Arabic and I want to search on them with a keyword keyword = request.POST.get('search', '') books = Book.objects.filter(Q(name__icontains=keyword)).order_by('category', 'code') The problem is that django treats the two letters 'أ' and 'ا' as two different letters while users would expect that they are interchangeable in search and both should give the same output. Is there a way I can treat them as one letter without replacing them in variations of the code? like this keyword_var1 = keyword.replace('أ', 'ا') Also the same problem with the letters 'ى' and 'ي' -
Why is {% load static %} not working in PyCharm for Django?
[HTML file]setting.py file I am trying to add CSS and JavaScript to html file in Django but getting unexpected token error when I entered {% load static %}.so getting web page without applying CSS. I also run the >python manage.py collectstatic -
Django : Forbidden CSRF cookie not set.)
I''m using Django with pyJWT to generate JWT for a simple login. Although it previously worked well now I'm getting Forbidden (CSRF cookie not set.) error there is no CSRF_COOKIE_SECURE in the setting.py url.py in app urlpatterns = [ path('login' , LoginView.as_view()), path('user' , UserView.as_view()) ] main url.py urlpatterns = [ path('', admin.site.urls), path('api/' , include('users.urls')) ] view.py class LoginView(APIView): def post(self,request): username = request.data['username'] password = request.data['password'] user = User.objects.filter(username = username).first() if user is None: raise AuthenticationFailed("User not found") if not user.check_password(password): raise AuthenticationFailed('Incorrect Password') payload = { 'id': user.id, 'exp': datetime.datetime.utcnow() + datetime.timedelta(minutes=60), 'iat': datetime.datetime.utcnow() } token = jwt.encode(payload , 'secret' , algorithm='HS256' ) response = Response() response.set_cookie(key='jwt' , value=token , httponly=True) response.data = { 'jwt': token } return response settings.py MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", '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', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True for clarification this is the API url I used: http://localhost:8000/api/login when i use postman to call API I'm getting this error : Forbidden (CSRF cookie not set.): /api/login [27/May/2023 18:53:53] "POST /api/login HTTP/1.1" 403 2870 when i use axios post I'm getting this error : Forbidden (Origin checking failed - http://localhost:5173 does not match any trusted origins.): … -
Difference between self.user and self.user_id
I am a beginner of learning Django. When I read the code below, I have a few of questions. from django.db import models from django.contrib.auth.models import User class Friendship(models.Model): from_user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name='following_friendship_set', ) to_user = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, related_name='follower_friendship_set', ) created_at = models.DateTimeField(auto_now_add=True) class Meta: index_together = ( ('from_user_id', 'created_at'), ('to_user_id', 'created_at'), ) unique_together = (('from_user_id', 'to_user_id'), ) def __str__(self): return '{} followed {}'.format(self.from_user_id, self.to_user_id) Why should use self.from_user_id and self.to_user_id not self.from_user and self.to_user in the str function? What is the difference? 2. from django.db import models from django.contrib.auth.models import User from tweets.models import Tweet class NewsFeed(models.Model): user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) tweet = models.ForeignKey(Tweet, on_delete=models.SET_NULL, null=True) created_at = models.DateTimeField(auto_now_add=True) class Meta: index_together = (('user', 'created_at'), ) unique_together = (('user', 'tweet'), ) ordering = ('user', '-created_at') def __str__(self): return f'{self.created_at} inbox of {self.user}: {self.tweet}' Why should use self.user and self.tweet not self.user_id and self.tweet_id in the str function above? Why does the author use id but not use id in this part? I am so confused. What is the difference between self.user and self.user_id? -
keyError:'etag' while uploading staticfiles to cloudinary from django
I have uploaded statifiles on cloudinary from django ,but when i am uploading again the samefiles with some changes it just through this error KeyError:'etag' -
Getting Connection reset by peer while debugging django app
I am debugging django app running inside docker container on my laptop. I attached vscode to the docker container and started the django app in debug mode. I have built a rest endpoint and put breakpoint on the first line in the REST endpoint. Now, I accessed that rest end point from postman REST client. It hit the breakpoint. Then, I stepped through the whole rest end point. It returned a desired JSON response, which I obtained in postman window. So the rest endpoint point seem to work fine, following the desired steps and returning the desired response. However after I receive the response in the postman window, a few seconds, vscode prints following in the same terminal window in which debugging is running: Exception happened during processing of request from ('10.0.5.4', 52994) Traceback (most recent call last): File "/usr/local/lib/python3.6/socketserver.py", line 654, in process_request_thread self.finish_request(request, client_address) File "/usr/local/lib/python3.6/socketserver.py", line 364, in finish_request self.RequestHandlerClass(request, client_address, self) File "/usr/local/lib/python3.6/socketserver.py", line 724, in __init__ self.handle() File "/usr/local/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/usr/local/lib/python3.6/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/usr/local/lib/python3.6/socket.py", line 586, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 104] Connection reset by peer Above stack trace does not list any … -
Wagtail - Switching from InlinePanel to FieldPanel results in errors
My wagtail blog was based on a now very out of date tutorial, however it wasn't until Wagtail 5.0 that the features I was using/way of doing things have finally been deprecated. For the most part, following the 'Upgrade Considerations' listed in the documentation, I've been able to make changes and everything has gone smoothly. The problem I have encountered is in switching an InlinePanel to a FieldPanel. This is the code from my models.py to define a blog category: class PostPageBlogCategory(models.Model): page = ParentalKey( "myblog.PostPage", on_delete=models.CASCADE, related_name="categories" ) blog_category = models.ForeignKey( "myblog.BlogCategory", on_delete=models.CASCADE, related_name="post_pages" ) panels = [ FieldPanel("blog_category"), ] class Meta: unique_together = ("page", "blog_category") @register_snippet class BlogCategory(models.Model): name = models.CharField(max_length=255) slug = models.SlugField(unique=True, max_length=80) panels = [ FieldPanel("name"), FieldPanel("slug"), ] def __str__(self): return self.name class Meta: verbose_name = "Category" verbose_name_plural = "Categories" And this is the section of my 'Post Page' model which allowed for a user to choose a category when creating a new page: content_panels = Page.content_panels + [ FieldPanel("header_image"), InlinePanel("categories", label="category"), FieldPanel('body'), ] If I leave this as is, it technically works, with the exception that the + icon in the following screenshot no longer works. That + icon, in Wagtail 4.1, would open … -
Account activation with token sent to email failed - Django
I'm making a blog website and I'm at the authentication part. I have programmed the code to send a mail, to the email submitted by the user, (for verification) when an account has been registered. This mail contains the activation token. I was able to do this just a few days ago before I had to tweak parts of my views.py for other reasons. My guess is that the code changed by mistake, and now I'm not sure about what to do. I tested this a few minutes ago and everything worked fine, except for the activation. It sent the activation link to me but when I clicked it, it told me that the activation failed. I'm sure there's a really silly mistake in my code but I'm just not able to find it. views.py def activate(request, uidb64, token): try: uid = force_str(urlsafe_base64_decode(uidb64)) myuser = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): myuser = None if myuser is not None and generate_token.check_token(myuser, token): myuser.is_active = True myuser.save() login(request, myuser) return redirect('home') else: return render(request, 'authstuff/activation_failed.html') tokens.py from django.contrib.auth.tokens import PasswordResetTokenGenerator from six import text_type class TokenGenerator(PasswordResetTokenGenerator): def _make_hash_value(self,user,timestamp): return ( text_type(user.pk) + text_type(timestamp) # text_type(user.profile.signup_confirmation) ) generate_token = TokenGenerator() I've made … -
How can I encrypt or hash the true origin source of media files?
I want to do something to encrypt the source of my media files. Now how can I achieve that, for example, could that work if I serve my file locally? or the files should be on a server like AWS S3 in order to have that secure link where you can't use that link to download a video for example. Here is a screenshot of video courses type of website that have something that I'd like to do. I've seen other types of links protected/encrypted... I just want to know if I can do that locally too or if the only way is to upload my videos on a hosting server like AWS and feed the files from there, and also if I serve the video files from a service like AWS do I need to do something else too in order to encrypt that source link, or it will be already done by AWS server? Thank you in advance! -
Can not connect Django to sql server
I follow the steps from ( Microsoft help to connect SQL server to Django) and then I receive this error "django.core.exceptions.ImproperlyConfigured: 'mssql' isn't an available database backend or couldn't be imported. Check the above exception. To use one of the built-in backends, use 'django.db.backends.XXX', where XXX is one of: 'mysql', 'oracle', 'postgresql', 'sqlite3'" Python version is 3.10.11 Django version is 3.2.19 **steps: ** Create a Django project $ django-admin startproject mysite E dit setting.py file Go to mysite/mysite/settings.py In DATABASE section, edit accrodingly. Make sure the DATABASE_NAME is exist in your SQL Server instance. settings.py DATABASES = { "default": { "ENGINE": "mssql", "NAME": "DATABASE_NAME", "USER": "USER_NAME", "PASSWORD": "PASSWORD", "HOST": "HOST_ADDRESS", "PORT": "1433", "OPTIONS": {"driver": "ODBC Driver 17 for SQL Server", }, }, } Run Django project Windows py manage.py runserver