Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Images are not getting displayed on my website (HTML)
<!doctype html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-1BmE4kWBq78iYhFldvKuhfTAU6auU8tT94WrHftjDbrCEXSU1oBoqyl2QvZ6jIW3" crossorigin="anonymous"> <title>AYNTK</title> </head> <body> <div id="carouselExampleControls" class="carousel slide" data-bs-ride="carousel"> <div class="carousel-inner"> <div class="carousel-item active"> <img src="templates\Slide 1.jpg" class="d-block w-100"> </div> <div class="carousel-item"> <img src="templates\Slide 2.jpg" class="d-block w-100"> </div> <div class="carousel-item"> <img src="templates\Slide 3.jpg" class="d-block w-100"> </div> </div> <button class="carousel-control-prev" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="prev"> <span class="carousel-control-prev-icon" aria-hidden="true"></span> <span class="visually-hidden">Previous</span> </button> <button class="carousel-control-next" type="button" data-bs-target="#carouselExampleControls" data-bs-slide="next"> <span class="carousel-control-next-icon" aria-hidden="true"></span> <span class="visually-hidden">Next</span> </button> </div> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.1.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-ka7Sk0Gln4gmtz2MlQnikT1wXgYsOg+OMhuP+IlRH9sENBO0LRn5q+8nbTov4+1p" crossorigin="anonymous"></script> </body> </html> I am really new to designing with HTML and CSS... I took this code from Bootstrap website, trying to create a carousel and added the relative path of my images to the img tag as source. The images does not get displayed on the website.. What can possibly be the reason? -
Basic idea to access items in S3 bucket from Browser
I use [django-s3direct][1] to upload file to S3 bucket. Once file is uploaded there comes url appeares here. https://s3.ap-northeast-1.amazonaws.com/cdk-sample-bk/line-assets/images/e236fc508939466a96df6b6066f418ec/1040 However when accessing from browser, the error comes. <Error> <script/> <Code>AccessDenied</Code> <Message>Access Denied</Message> <RequestId>025WQBJQ5K2W5Z5W</RequestId> <HostId>FF3VeIft8zSQ7mRK1a5e4l8jolxHBB40TEh6cPhW0qQtDqT7k3ptgCQt3/nusiehDIXkgvxXkcc=</HostId> </Error> Now I can use s3.ap-northeast-1.amazonaws.com url? or do I need to create access point ? Access permission is public and bloc public access is off Bucket policy is like this { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Principal": { "AWS": "arn:aws:iam::678100228133:role/st-dev-base-stack-CustomS3AutoDeleteObjectsCustomR-MLBJDQF3OWFJ" }, "Action": [ "s3:GetBucket*", "s3:List*", "s3:DeleteObject*" ], "Resource": [ "arn:aws:s3:::cdk-st-dev-sample-bk", "arn:aws:s3:::cdk-st-dev-sample-bk/*" ] } ] } Is there any other things I need to check? -
Dynamic Django urls redirects to the wrong function
So what I am trying to do is create urls such that the user can see complaints either by passing a particular parameter or sort by upvotes by default if no parameter is passed. urls.py path('', views.exploreComplaints, name='explore-complaints'), path('?sort_by=<str:sorting_parameter>/', views.exploreComplaints, name='explore-complaints-by-parameter'), views.py def exploreComplaints(request, sorting_parameter="upvotes"): complaints = Complaint.objects.all() if(sorting_parameter=="name"): complaints = sorted(complaints, key = lambda x : x.complaint_name) else: complaints = sorted(complaints, key = lambda x : x.complaint_upvotes, reverse = True) context = {'complaints':complaints} return render(request, 'complaints/complaints.html', context) The sorting parameter does not work when I go to a URL, the value of sorting_parameter is always upvotes, even when I go to a url with ?/sort_by=name in the end. Where am I wrong? -
Rest django checking the duplicate number
if i adding the number 5 i want to check all the numbers before 5( like 1,2,3 and 4 )is must have inside the db ,then only can i add the number 5 ,otherwise show error. And also check is any duplication in the Db using rest django model serilaizer. -
Download Html file instead of render in Django
So I am pretty much a django newbie, I do not even know if what I am asking is possible ;-; So basically what I'm making is a website where users can pass context Then django populates a template with the context But instead of rendering the template I want to make the template populated with context available for download I want to be able to download index.html I know browsers have a save webpage feature but on mobile the javascript does not work and the icons i got from Google icons also do not load -
Need help accessing session variables in Django Channels consumers.py
I am generating a random userid and storing it as a session variable in my view. I am trying to access that session variable in consumers.py to identify the user (not authenticated ) and update the user about the changes in the database. view.py : def index(request): request.session['uniqueid'] = 'random_number' print(request.session['uniqueid']) # this is working return render( request, 'home.html', ) consumers.py: class WSConsumer(WebsocketConsumer): def connect(self): self.accept() U = self.scope['session']["uniqueid"] Error: Exception has occurred: KeyError (note: full exception trace is shown but execution is paused at: connect) 'uniqueid' I changed localhost to 127.0.0.1 ('ws://127.0.0.1:8000/ws/socket/') as described in https://stackoverflow.com/a/67242832, but receive the same error. I am unable to pin down the error, any help would be appreciated. -
Initialize a container model with child models when a new container is created - e.g. Todo list with default tasks
I'm trying to create a todo list as part of an application that is used to prompt a user what they must complete before the application is assessed. To achieve this I have created a TaskList model and a Task model belonging to a TaskList. When I create a new TaskList instance (on a new application) I want to prepopulate the list with some default Tasks that will always be present on every new application. I'm relatively new to Django and Python, so I'm just looking for a push in the right direction. Is there some kind of Django model initialize function I can override on the TaskList to create these default tasks? -
How can I use a Django model's verbose_name in a field definition?
I have the following model: # models.py #============================================================================== from django.db import models class Foo(models.Model): ... exists = models.BooleanField( verbose_name = 'The Foo still exists.', default = True ) ... What I would like to do is use the model's verbose_name in place of 'Foo', so that my model would look something like this: # models.py #============================================================================== from django.db import models class Foo(models.Model): ... exists = models.BooleanField( verbose_name = f'The {self._meta.verbose_name} still exists.', default = True ) ... Obviously, this doesn't work as written since self doesn't exist in that context. I tried the following, which seemed to work: # models.py #============================================================================== from django.db import models class Foo(models.Model): ... def __init__(self,*args,**kwargs): super().init(*args,**kwargs) self.exists = models.BooleanField( verbose_name = f'The {self._meta.verbose_name} still exists.', default = True ) ... However, when I tried Foo.save() I ended up with django.core.exceptions.FieldError: Invalid field name(s) for model Foo: 'exists'. Ultimately, I intend to make Foo into an abstract model for other models to inherit (which is not the question here, just some added context). The question is, how can I use the model's verbose_name in the field definition? -
Django exclude from queryset if all attributes of the set not match
I have 2 models Course and Class I'm trying to exclude the courses where ALL his classes vacancies are 0, but this query is excluding the course if only one of the class vacancies is 0. courses = Course.objects.all().exclude(class_set__vacancies=0) Classes: -
Django: select values from related table
I have these two simple tables: # Table manufacturers in my db: # | id | name | # |----|-------| # | 1 | Tesla | # | 2 | BMW | # Table cars in my db: # | id | model | make | # |----|---------|-------| # | 1 | Model 3 | Tesla | # | 2 | M5 | BMW | # | 3 | Model S | Tesla | So here are my models.py: from django.db import models class ManufacturerModel(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=255, unique=True) class Meta: managed = False db_table = 'manufacturers' class CarModel(models.Model): id = models.IntegerField(primary_key=True) model = models.CharField(max_length=255) make = models.ForeignKey( ManufacturerModel, on_delete=models.DO_NOTHING, null=False, to_field='name', db_column='make' ) class Meta: managed = False db_table = 'cars' I need to get this object: manufacturers = { 'Tesla': ['Model 3', 'Model S'], 'BMW': ['M5'] } Or at least this one: manufacturers_1 = [ { 'id': 1, 'name': 'Tesla', 'cars': [ { 'id': 1, 'model': 'Model 3', 'make': 'Tesla' }, { 'id': 3, 'model': 'Model S', 'make': 'Tesla' } ] }, { 'id': 2, 'name': 'BMW', 'cars': [ { 'id': 2, 'model': 'M5', 'make': 'BMW' } ] } ] Basically it's just a very … -
How to trigger signals for User model whenever profile is updated in django?
I am using signals to create a profile whenever a user account is created. This works fine. It also updates the profile whenever the user's username is changed. The problem here is that I wanted to edit the user's first_name and last_name only when the profile is edited so I tried using signals in which the receiver is now the CustomUser model. But, I don't think I am doing it right. # accounts/models.py class CustomUser(AbstractUser): age = models.IntegerField(null=True, blank=True) bio = models.TextField(null=True, blank=True) class Meta: unique_together = [['first_name', 'last_name']] # pages/models.py class Profile(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, blank=True, null=True) first_name = models.CharField(max_length=200, blank=True, null=True) last_name = models.CharField(max_length=200, blank=True, null=True) # accounts/signals.py @receiver(post_save, sender=Profile) def update_profile(sender, instance, created, **kwargs): if not created: print("Custom user updated!") # pages/signals.py @receiver(post_save, sender=CustomUser) def create_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) print("Profile created!") @receiver(post_save, sender=CustomUser) def update_profile(sender, instance, created, **kwargs): if not created: instance.profile.save() print("Profile updated!") -
How can I get 'sign in with Google' to work using 'dj_rest_auth'?
I'm trying to implement Google sign in using DRF and dj_rest_auth. I've set up 'django-allauth' with Google as provider and the sign in process works in the web browser. I need to connect an android app with my backend. I've created API endpoints which will require authentication. According to the docs, code is required in order to complete authentication and receive the token. After doing some research, I found that code required by dj_rest_auth can be obtained by visiting: https://accounts.google.com/o/oauth2/v2/auth?redirect_uri=<YOUR CALLBACK URL>&prompt=consent&response_type=code&client_id=<YOUR CLIENT ID>&scope=openid%20email&access_type=offline However, even after passing code returned in the query param (after decoding from URL format), the following error is shown: Error retrieving access token: b'{\n "error": "invalid_grant",\n "error_description": "Bad Request"\n}' To see if I can log in with a recent access token, I signed in with my Google account from the homepage , copied the access token from the admin section and submitted it to the endpoint http://localhost:8000/dj-rest-auth/google/. I was able to receive the auth token generated by dj_rest_auth. I need help in getting the auth token by providing code in the post request. My code: # urls.py ... path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('dj-rest-auth/google/', home.GoogleLogin.as_view(), name='google_login'), ... # views.py from allauth.socialaccount.providers.google.views import GoogleOAuth2Adapter from allauth.socialaccount.providers.oauth2.client import … -
the best way to keep the font-size the same on all devices
I am struggling with setting up the font-size so it looks similar in all desktop devices. For now the problem is that on my new laptop sidebar ends on 75% of total web height and on my old laptop it is exceeding 100% of screen height and I had to implement scrollbar. Is there anything I can do to prevent from it and to keep it the same. I tried these 2 solutions but they don't work]. I am using default Bootstrap 5 typography. I am using h1-h6 and p tags on all websites. No custom font sizes and classes applied. -
Where should I put extra logic in django project?
I want to check time continuously (maybe using multi threading) and if it is 12 midnight I want to update database. Where should I put these kind of logic in django project. Is it okay to put these king of code in manage.py? -
How to make unit tests on LoginView and LogoutView in Django?
I'm trying to write proper tests for my views which are just subclassess of LoginView and LogoutView from django.contrib.auth.views. from django.contrib.auth.views import LoginView, LogoutView class UserLoginView(LoginView): template_name = 'finder/login.html' next_page = reverse_lazy('book-list') class UserLogoutView(LogoutView): template_name = 'finder/logout.html' next_page = reverse_lazy('book-list') urls.py: path('login/', views.UserLoginView.as_view(), name='login'), path('logout/', views.UserLogoutView.as_view(), name='logout'), path('book/list/', views.BookListView.as_view(), name='book-list'), What should I take in mind and how should I write proper testing cases in my test.views.py? For now I've got something like this: class UserLoginViewTest(TestCase): def setUp(self) -> None: self.factory = RequestFactory() self.user = User.objects.create_user(username='dummy', password='123secret') def test_positive_login_view(self): # request = self.factory.post(path='/login/', data={'username': 'dummy', 'password': '123secret'}) # request.user = self.user # response = views.UserLoginView.as_view()(request) response = self.client.post(path='/login/', data={'username': 'dummy', 'password': '123secret'}) self.assertRedirects(response, '/book/list/') def test_negative_login_view(self): response = self.client.post(path='/login/', data={'username': 'any', 'password': 'any'}) self.assertEqual(response.status_code, 200) But to be honest those tests are strictly suited to responses which I've got back, so e.g. I don't know why my status_code in response with improper credentials is 200 and not something else like 4xx. And what should I test in such auth views? That my user is getting an authenticated status? but how? And second question: how to use requestfactory in this case? I've tried with code which is commented, but got status_code=403 … -
Custom e-commerce or stick to an e-commerce platform?
I am sorry if this the wrong place to ask this question, but i have been asked to build a small e-commerce site, and since it's small i was wondering if i can just build it myself using something Django or PHP, or should i really just stick to ready built in platforms like WordPress or Magento and if so which one do you recommend for a small e-commerce. I am only asking because the more i search the more i find articles telling me i should stick to built in platforms i just wanted one more advice. -
ModuleNotFoundError: No module named 'index,django'
my project name = portfolio my app name = index index - url.py from django.contrib import admin from django.urls import path, include from index import views urlpatterns = [ path('', views.home, name='home'), path('home', views.home, name='home'), path('about', views.about, name='about'), path('project', views.project, name='project'), path('contact', views.contact, name='contact'), portfolio url.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('index.urls')) ] and views.py from django.shortcuts import render def home(request): return render(request, 'home.html') def about(request): return render(request, 'about.html') def project(request): return render(request, 'project.html') def contact(request): return render(request, 'contact.html') I'm new to django. sorry. -
Elements going inside div tag when using context
My pages have a normal layout like so When trying to include the calendar on the /calendar url everything seems to just squish under the calendar tab. views.py @login_required def calendar(request): context={} results = get_events(request) #context['results'] = results d = date.today() print(d) cal = Calendar(d.year, d.month) html_cal = cal.formatmonth(results, withyear=True) context['calendar'] = mark_safe(html_cal) context['nmenu'] = 'calendar' editProfileForm = UserProfileForm(instance=request.user) context['editProfileForm'] = editProfileForm if request.method=="POST": if 'editProfileForm' in request.POST: editProfileForm = UserProfileForm(request.POST or None, request.FILES or None,instance=request.user) if editProfileForm.is_valid(): editProfileForm.save() editProfileForm = UserProfileForm(instance=request.user) context['editProfileForm'] = editProfileForm context['is_post'] = False return render(request, "home.html", context) else: context['is_post'] = True context['editProfileForm'] = editProfileForm return render(request, "home.html", context) return render(request, 'home.html', context) calendar.html {% block content %} <style> .calendar { width: 98%; margin: auto; font-size: 13px; } .calendar tr, .calendar td { border: 1px solid black; } .calendar th { padding: 10px; text-align: center; font-size: 18px; } .calendar td { width: 200px; height: 150px; padding: 20px 0px 0px 5px; } .month { font-size: 25px; } .date { font-size: 16px; } ul { height: 100%; padding: 0px 5px 0px 20px; } </style> <h1>Calendar</h1> <button>+</button> {{calendar}} {% endblock %} <!-- <ul> {% for result in results %} <li>{{result.start.date}}{% if result.end.date %}-{% endif%}{{result.end.date}}: {{result.summary}}</li> {% endfor %} </ul> … -
Is it possible to use queryset in the FROM clause
I have a model for user's points collection: class Rating(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='rating') points = models.IntegerField() Each user could have multiple records in this model. I need to calculate a rank of each user by sum of collected points. For the listing it's easy: Rating.objects.values('user__username').annotate( total_points=Sum('points') ).order_by('-total_points') But how to get rank for a single user by his user_id? I added annotation with numbers of rows: Rating.objects.values('user__username').annotate( total_points=Sum('points') ).annotate( rank=Window( expression=RowNumber(), order_by=[F('total_points').desc()] ) ) it really added correct ranking numbers, but when I try to get a single user by user_id it returns a row with rank=1. It's because the filter condition goes to the WHERE clause and there is a single row with the number 1. I mean this: Rating.objects.values('user__username').annotate( total_points=Sum('points') ).annotate( rank=Window( expression=RowNumber(), order_by=[F('total_points').desc()] ) ).filter(user_id=1) I got the SQL query of this queryset (qs.query) like SELECT ... FROM rating_rating WHERE ... and inserted it into another SQL query as "rank_table" and added a condition into the outside WHERE clause: SELECT * FROM (SELECT ... FROM rating_rating WHERE ...) AS rank_table WHERE user_id = 1; and executed within the MySQL console. And this works exactly as I need. The question is: how to implement the same … -
When i try to sign up after i Deployed my django projects in Heroku this error occurs although it doesn't in my localhost
When i try to sign up in my Django prject which is deployed in Heroku this error occurs although when i try the same think on my localhost it doesn't (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs\n5.7.14 wwfTXnpKMhQYEw32JsPKVeURPTx0aN-gih7DbYiw9P7hAoVGlm9uAr6nh6wtPSf5RItfk\n5.7.14 U3yBi83J6hZNnidGpRRi0gVOlElqn-aAnjzu2O9HfpxM4jcIC6ut2sAx7C33cch0>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 f14sm18139082qko.117 - gsmtp') Request Method: POST Request URL: http://myportfoliowebsite0.herokuapp.com/signup Django Version: 4.0.2 Exception Type: SMTPAuthenticationError Exception Value: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs\n5.7.14 wwfTXnpKMhQYEw32JsPKVeURPTx0aN-gih7DbYiw9P7hAoVGlm9uAr6nh6wtPSf5RItfk\n5.7.14 U3yBi83J6hZNnidGpRRi0gVOlElqn-aAnjzu2O9HfpxM4jcIC6ut2sAx7C33cch0>\n5.7.14 Please log in via your web browser and then try again.\n5.7.14 Learn more at\n5.7.14 https://support.google.com/mail/answer/78754 f14sm18139082qko.117 - gsmtp') Exception Location: /app/.heroku/python/lib/python3.9/smtplib.py, line 657, in auth Python Executable: /app/.heroku/python/bin/python Python Version: 3.9.6 Python Path: ['/app', '/app', '/app/.heroku/python/lib/python39.zip', '/app/.heroku/python/lib/python3.9', '/app/.heroku/python/lib/python3.9/lib-dynload', '/app/.heroku/python/lib/python3.9/site-packages'] Server time: Tue, 15 Feb 2022 21:48:46 +0000``` -
For some reason {{ post.message }} is not displaying the modle
I am making a simple site to experiment with manipulating user data. I have a form where the user enters in some info and once they hit submit they get redirected to a new page. On this new page, the info they entered is supposed to be displayed. I am under the impression that you use this {{ Modle_Name.Fild_name}} to inject the info into the HTML. However, it is not working. If any of y'all have a solution I would much appreciate it. sucseus.html {% extends "base.html" %} {% block content %} <h1>success</h1> <h2>{{ post.message }}</h2> {% endblock %} views.py from django.shortcuts import render from django.urls import reverse_lazy from django.views import generic from . import forms from forums_simple.models import Post # Create your views here. class Form(generic.CreateView): model = Post template_name = 'forums_simple/form.html' fields = ['message'] success_url = reverse_lazy('forums:sucsseus') class Sucsessus_view(generic.TemplateView): template_name = 'forums_simple/sucseus.html' model = Post models.py from django.db import models # Create your models here. class Post(models.Model): message = models.TextField(blank=True, null=False) created_at = models.DateTimeField(auto_now=True) -
Connect a model to another model on save in admin panel
Sorry for my bad english, but I don't even know how to properly describe my problem. I have 3 models: class Book(models.Model): source=models.ForeignKey(Original, on_delete=models.CASCADE, related_name='book', null=True, blank=True) ... class Original(models.Model): ... class Title(models.Model): book = models.OneToOneField(Book, on_delete=models.CASCADE, related_name='item', null=True, blank=True) original = models.OneToOneField(Original, on_delete=models.CASCADE, related_name='item', null=True, blank=True) original_name = models.CharField(max_length=300, null=True, blank=True) ... In my admin page, when i creating Book instance i writing it's name to Title model as inline and i want to have an option: 1.Fill in the original_name form manually if no source given 2.If source given, leave this field empty,but when saving connect that Book instance to original field in Title model. In the end i want to have a Title model that have original_name and reference to original and book instances, if source given and from which in the future I may refer to the original_name when needed I tried to implement this using save_model function, but i have no clue how set Book instance as original field in Title model I think it must be pretty easy, but i dont know where to start and its frustrating... -
Module not found: how to install django-parsley in a Django project?
This is such a basic question, I'm sorry. I installed django-parsley with poetry (poetry add django-parsley). It's clearly installed in my pyproject.toml file. However, when I try to run python manage.py runserver, I get the following error: from parsley.decorators import parsleyfy ModuleNotFoundError: No module named 'parsley' I also tried adding 'parsley' to my INSTALLED_APPS in settings.py. That gives me this error (which is maybe due to not adding it globally with pip install?): ...some more errors... File "C:\Program Files\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'parsley' What do I need to do to be able to import it in a python file in my project? -
Django support chat with site administration
How do I create a django support chat on my site? Are there ready-made solutions or some additional Python package for development? -
How to pass on django form results to a text box
I haven't been coding for more than a year now and am being a little rusty on some aspects. I have a django form designed using crispy_forms. Nothing very original : a bunch of radiobuttons, textbox... Goal: My purpose is to have a generate_report button that once being clicked on open below the button a textbox with a text generated using the values picked for the former fields. I created in models a __str__ method with the text I want. But I'm not sure that's the proper place for such a function. I can have a text box hidden that only shows once someone click on the generate_report button using javascript, but I don't know how to pass on the text with the data. Any idea? [forms.py] from .models import Foo from crispy_forms import bootstrap, helper, layout class FooForm(forms.ModelForm): class Meta: model = Foo fields = "__all__" def __init__(self, request, *args, **kwargs): self.request = request super().__init__(*args, **kwargs) actions = bootstrap.FormActions(layout.Submit("save", _("Save")), bootstrap.StrictButton("generate_report", css_class="btn-success")) self.helper = helper.FormHelper() self.helper.form_action = self.request.path self.helper.form_method = "POST" self.helper.form_class = "blueForms" self.helper.layout = layout.Layout( field1, field2, field3, actions ) self.form_tag = False self.render_required_fields = False