Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django leaflet marker icon doesn't appear on Heroku
I have deployed my Django app to Heroku but when I want to fill the location field, the marker icon doesn't appear even though I have used whitenoise to serve the static files. It is working locally though. This is the . Here's how I set my whitenoise INSTALLED_APPS = [ ..., 'whitenoise.runserver_nostatic' ] MIDDLEWARE = [ ..., 'whitenoise.middleware.WhiteNoiseMiddleware' ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR,'static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' -
Filter a field with timestamp (datetime) using today's date in Django
I have a Django model with a timestamp field. I want to filter and get the number of rows containing today's date. The timestamp field contains date, time and time zone. I tried this: today_date = date.today().strftime("%Y-%m-%d" ) Pending = tablename.objects.filter(timestamp=today_date,).count() But I got zero (0). Thank you. -
Django Rest framework url static files missing?
I got an api with rest framework but the field img missing the host url .ex:localhost:... The img field should have localhost: ... / images / ... But it only has /images/.. How can I change it to urlhost/images/.. Models.py class Product(models.Model): id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. productcode = models.CharField(db_column='ProductCode', max_length=200, blank=True, null=True) # Field name made lowercase. name = models.CharField(db_column='Name', max_length=200) # Field name made lowercase. price = models.FloatField(db_column='Price') # Field name made lowercase. img = models.FileField(db_column='IMG', max_length=200) # Field name made lowercase. description = models.CharField(db_column='Description', max_length=2000, blank=True, null=True) # Field name made lowercase. stock = models.IntegerField(db_column='Stock') # Field name made lowercase. createdate = models.DateField(db_column='CreateDate',default=dateupdate()) # Field name made lowercase. brandname = models.ForeignKey(Brand, models.DO_NOTHING, db_column='BrandName') # Field name made lowercase. Views.py @api_view(['GET']) def CartdetailsView(request): username = request.user.username queryset = Cartdetails.objects.filter(username=username) serializer = CartdetailsSerializer(queryset,many=True) return Response(serializer.data) -
Django template variable in html
i want to adjust the width of processbar with variable cresource.cpu_avail_percent, how can i add style tag my code {% for cresource in c_resources %} <div class="progress-bar progress-bar-striped progress-bar-animated bg-success" role="progressbar" aria-valuenow="100" aria-valuemin="0" aria-valuemax="100" style="width:{{cresource.cpu_avail_percent}};"> </div> {% endfor %} i'm using django 3.2.6 -
extract children with a given condition - Django MPTT and Django rest framework
In this tree I want to do a query so that only the first generation of the red circle is extracted. But the condition is that the value of each circle must be greater than zero, ie the green circles: Serializers: class CircleBaseSerializer(serializers.ModelSerializer): class Meta: model = Circle fields = ('id', 'value') class CircleChildrenSerializer(CircleBaseSerializer): class Meta(CircleBaseSerializer.Meta): pass class CircleParentSerializer(CircleBaseSerializer): children = CircleChildrenSerializer(many=True) class Meta(CircleBaseSerializer.Meta): pass View: class CircleViewSet(ReadOnlyModelViewSet): serializer_class = CircleParentSerializer queryset = Circle.objects.all() def get_queryset(self): id = self.kwargs["id"] u=Circle.objects.get(pk=id) Certainly result is [5(1,0,3)] that is not desirable. How can I do this query? -
Leveraging django auth.views LogoutView
I have two usertypes a and b how should i leverage the auth views i.e LogoutView that django provides how can my view look with what methods and attributes i should use and how should i set my login_url and etc this is how my function based view looks now.. views.py @login_required def logout(request): if request.user.usertype_a: logout(request) return redirect(reverse('user_a')) else: logout(request) return redirect(reverse('user_b')) -
'Settings' object has no attribute Django Restframework
I know this question has been asked before. But i am unable to understand the answer. I have defined an environment variable in settings.py s3path=env('S3PATH') Then i call it in views.py from django.conf import settings as conf_settings conf_settings.s3path but i am getting this error 'Settings' object has no attribute 's3path' -
When to use API vs SMTP in Django
Can API be used to replace SMTP for mail sending in Django especially for things like reset password and mail confirmation. I will really love if I can get clarification on a topic in django. I am a newbie to django and when it comes to sending mail I register for Mailgun and used the API since I have used requests before but picking up django to work with I am trying to do user registration using DJ-Rest-auth and django_allauth and there is thing about configuring email backend using SMTP. my question is Can i do without using SMTP for django_allauth if Yes a workflow how to connect my password reset to use the api for mail. I can easily pass in the mail function to serve as an alert in the views when user registers -
selection query based on combo box input django
I have two models; City and location that I want to connect together. The models for them are as follows: class City(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) ordering = models.IntegerField(default=0) city_id = models.IntegerField(default=0) class Meta: ordering = ['ordering'] def __str__(self): return self.title class Location(models.Model): title = models.CharField(max_length=255) slug = models.SlugField(max_length=255) ordering = models.IntegerField(default=0) location_id = models.IntegerField(default=0) city_id_fk = models.ManyToManyField(City) class Meta: ordering = ['ordering'] def __str__(self): return self.title First you select which city and then based on the combo box selection you are displayed locations. Im connecting the two tables using city_id_fk. Now i want to write a query for selection based on the city selected. How can I do that? -
Django - Get a single queryset values list from two related models
I have an user model class User(AbstractBaseUser): name = models.CharField(max_length=100, default='Default') email = models.EmailField( verbose_name='email address', max_length=255, unique=True, ) active = models.BooleanField(default=True) and a related SecondaryEmails model class SecondaryEmails(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='secondary_emails') email = models.EmailField() is_validated = models.BooleanField(default=False) Now I want to create a method to get a values_list containing both the User model's email and all the emails stored in the related SecondaryEmails model. I am able to get a values_list containing only the email of the User model >>> User.objects.filter(email='test@gmail.com').prefetch_related('secondary_emails').values_list('email') >>> <QuerySet [('test@gmail.com',)]> The related SecondaryEmails model contains another two emails 'a1@gmail.com', 'a2@gmail.com'. I wanted these two emails also to be appended in the values_list() like the following: <QuerySet [('test@gmail.com',), ('a1@gmail.com',), ('a2@gmail.com',)]> Thanking you in advance. -
makemigrations can't detect change in django
I know there are a lot of similar questions: but I will describe my problem as simply as I can. This is the app I want to migrate. This is my setting.py This is what happens when I type in makemigrations(after I add a field in my model) This is what happens when I type in showmigrations(after I add a field in my model) I have reinstall django using pip, I have created new app , I have created new project,new venv, I even have reinstall python itself, all same story. I suspect my django source code has been corrupted, but when I install django using pip, it use file that is downloaded before instead download new file. Trust me, I have tried all the way you a newbie could possibly tried, could someone tell me how to redownload django itself or someone who is way smarter than me know what's going on right now. Thx! -
unable to filter() users with their date_joined field
I want to count all the users whose date_joined matches with 'today's' date. I have two users who have today's date in the date_joined field but the count always returns zero. I am perhaps not filtering the data correctly. These are the waays that I have tried to filter the data models class CustomUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField( unique= True) full_name = models.CharField(max_length=255) phone_no = models.CharField(max_length=10, blank= True) address = models.CharField(max_length=500, blank= True) plan = models.CharField(max_length=255, blank= True) age = models.CharField(max_length=2, blank= True) date_joined = models.DateTimeField(default=timezone.now) views from datetime import datetime, date def dashboard(request): all_users = CustomUser.objects.all().exclude(is_staff = True).count() all_users_bydate = CustomUser.objects.all().filter(date_joined= datetime.today()).count() print(all_users_bydate) all_users_bydate = CustomUser.objects.all().filter(date_joined= datetime.today().date()).count() all_users_bydate = CustomUser.objects.all().filter(date_joined= datetime.today().date()).count() even tried to explicitly filter all_users_bydate = CustomUser.objects.all().filter(date_joined= date(2021, 12, 11)).count() all of these ways did not work at all and always retuned zero. Please rectify me what I am doing wrong. -
Python - Django: select mulitple fields from different models to serialize into one json result
I'm currently working in my first Django project and am using the authentication mechanism that is included with Django. I currently have a game model with a foreign key relationship to a user in the auth_user table. Here are the following fields: class Game(models.Model): game_id = models.UUIDField(default=uuid.uuid4, editable=False, max_length=10) host = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete = models.CASCADE) join_code = models.CharField(max_length=100, null=True) active = models.BooleanField(default=True) I currently have a view method that just grabs all of the active game objects, and then passes those results into a serializer that serializes the data to be returned to the client. def get(self, request, format=None): games = Game.objects.filter(active__exact=True) serializer = GameSerializer(games, many=True) return Response(serializer.data) I want to add the username and email fields that are in AUTH_USER_MODEL to the results to be serialized, but I haven't been able to find examples of adding specific fields from a related model to the results that are serialized. Basically, I'm trying to figure out the django model equivalent of the following SQL statement select u.username, u.email, g.* from game g inner join AUTH_USER_MODEL u on u.user_id = g.host_id Finally, once I have the results from that sort of query, how would I serialize the combined objects? Do I need … -
Add and delete in one instance django Formset
I have a formset which generally works (Add, Delete, Edit) items except when I decide to Add and Delete(or vice versa) in one instance, the formset throws the 'id': ['This field is required.'] error. Below are prints of request.POST: When it works: <QueryDict: {'csrfmiddlewaretoken': ['lnEG6qbrWRg4NdkKwg1UU86KTBuIgJIc4ZqJAWvZpASgxECnicmlUmVhJIInvqEJ'], 'form-TOTAL_FORMS': ['3'], 'form-INITIAL_FORMS': ['3'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-id': ['6'], 'form-0-year': ['2023'], 'form-1-id': ['7'], 'form-1-year': ['2024'], 'form-2-id': ['8'], 'form-2-year': ['2025']}> When it does not work (I deleted 2024 and added 2026): <QueryDict: {'csrfmiddlewaretoken': ['fh0mPGYzVt0AOjpE5Q9JuTp1zuqwNCuMYTMpjci7ocCMyKHhRMuau7eypBEb2jqj'], 'form-TOTAL_FORMS': ['3'], 'form-INITIAL_FORMS': ['3'], 'form-MIN_NUM_FORMS': ['0'], 'form-MAX_NUM_FORMS': ['1000'], 'form-0-id': ['6'], 'form-0-year': ['2023'], 'form-1-id': ['8'], 'form-1-year': ['2025'], 'form-2-id': [''], 'form-2-year': ['2026']}> [{}, {}, {'id': ['This field is required.']}] Model: class Year(models.Model): year = models.CharField(max_length=100, null=True) user = models.CharField(max_length=300, null=True, blank=True) Forms: YearFormset = forms.modelformset_factory( Year, fields=('year',), extra=1, widgets={ 'year': forms.TextInput( attrs={ 'require': 'required', 'class': 'form-control', 'placeholder': 'Enter Year here' }) } ) View: def year(request): year_items = Year.objects.filter(user=1) year_set = YearFormset(queryset=year_items) year_set.extra = 0 if year_items else 1 context = {'years':year_set} if request.method == 'POST': print(request.POST) submit_year = YearFormset(request.POST) if submit_year.is_valid(): Template: <form method="POST"> {% csrf_token %} <br> {{ years.management_form }} {% for year in years %} <div class="form-row"> <div class="col-4"> <div class="input-group"> {{year.id}} {{year.year}} <button class="btn btn-success add-form-row">+</button> </div> <br> </div> … -
Serialize and create one-to-one relation with parent_link true in django and django rest framework
How to save the object with one-to-one relation and having parent_link=True using serializer. Below are my models and serializer having some fields from the actual model that I wanted to implement. I am not able to save the 'user' relation in the database. It is throwing the integrity error. class Audit(models.Model): is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) class Meta: abstract = True class User(Audit): class Meta: db_table = 'user' email = models.EmailField(unique=True) password = models.TextField() is_active = models.BooleanField(default=False) class UserProfile(User): class Meta: db_table = 'user_profile' user = models.OneToOneField(User, on_delete=models.CASCADE, parent_link=True, primary_key=True) address = models.TextField(null=True) dob = models.DateField() language = models.CharField(max_length=50, null=True) class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ['user', 'address', 'dob', 'language'] And the requested data looks like this. { "email": "abc@pqr.com", "password": "1234", "dob": "2021-12-11", "language" : "English" } -
How to define a relationship in Django Models such that a space in a model can be allocated to an object without overlapping?
I need to define models in Django such that it should check the server objects can fit into the rack object in question without overlapping each other and that you only use as many space(in Us) as you actually have in the rack. I tried defining the Django model as follows: ` from django.db import models class Location(models.Model): name = models.CharField(max_length =200) def __str__(self): return str(self.name) class Rack(models.Model): id = models.IntegerField(primary_key = True, auto_created = True) size = models.IntegerField() location = models.ManyToManyField(Location) def __str__(self): return str(self.id) class Server(models.Model): id = models.IntegerField(primary_key= True, auto_created=True) size = models.IntegerField() rack_id = models.ForeignKey(Rack, on_delete=models.CASCADE) owner = models.CharField(max_length = 200) locations = models.OneToOneField(Location, on_delete=models.CASCADE) def __str__(self): return str(self.id) ` I am unsure how to define the locations such that if I choose a location for a server, it is assigned to a location within the Rack, without overlapping the same location by any other server. At the same time, I need to make sure I only use as many space(in Us) as I actually have in the rack. -
Error 'AnonymousUser' object has no attribute '_meta'
I am writing an authorization system on my site and when I try to log in, I get the error 'AnonymousUser' object has no attribute '_meta'. Why is this happening? Here is structure of my project: ├───ithogwarts │ │ db.sqlite3 │ │ manage.py │ │ │ ├───ithogwarts │ │ │ asgi.py │ │ │ settings.py │ │ │ urls.py │ │ │ wsgi.py │ │ │ __init__.py │ │ │ │ │ └───__pycache__ │ │ settings.cpython-310.pyc │ │ settings.cpython-39.pyc │ │ urls.cpython-310.pyc │ │ urls.cpython-39.pyc │ │ wsgi.cpython-310.pyc │ │ wsgi.cpython-39.pyc │ │ __init__.cpython-310.pyc │ │ __init__.cpython-39.pyc │ │ │ ├───main │ │ │ admin.py │ │ │ apps.py │ │ │ models.py │ │ │ tests.py │ │ │ urls.py │ │ │ views.py │ │ │ __init__.py │ │ │ │ │ ├───migrations │ │ │ │ __init__.py │ │ │ │ │ │ │ └───__pycache__ │ │ │ __init__.cpython-310.pyc │ │ │ __init__.cpython-39.pyc │ │ │ │ │ ├───static │ │ │ └───main │ │ │ ├───css │ │ │ │ footer.css │ │ │ │ header.css │ │ │ │ index.css │ │ │ │ │ │ │ ├───img │ │ │ │ 1.jpg │ │ … -
django restrict choice options according to the usertype
I have two user types usertype a and usertype b i have a form to update the task with fields name,info and status i have STATUS_CHOICES = ( ('A','A'), ('B','B'), ('C','C') ) the user type a should c only ('A','A'),('B','B'), in dropdown and usertype b should have (C,C) as dropdown how do i acheive this in django the user type a should c only ('A','A'),('B','B'), in dropdown and usertype b should have (C,C) as dropdown how do i acheive this in django forms.py class Form(forms.ModelForm): class Meta: model = Model fields = (name', 'info',status') -
Django - Turn settings.DEBUG to True for one test
I have this test for checking if I can ping the swagger endpoint from django.test import SimpleTestCase from django.test.utils import override_settings from django.urls import reverse from rest_framework import status class SwaggerTest(SimpleTestCase): @override_settings(DEBUG=True) def test_successful_swagger_ping(self): """ Test to ensure that Swagger can be reached successfully. If this test throws 5XX that means there's an error in swagger annotation on some view function. """ response = self.client.get(reverse('swagger')) self.assertEqual(response.status_code, status.HTTP_200_OK) So this test fails, because I only have swagger added to url when settings.DEBUG=True. I thought @override_settings(DEBUG=TRUE) would fix that, but it doesn't. My test passes when I manually set settings.DEBUG=True under my settings.py file, otherwise it throws an error because it can't find the endpoint. I've tried decorating both the class and the function with @override_settings -
Can't send email through Django and Gmail
I keep getting this error while trying to send mail through gmail on my sign up form: raise SMTPAuthenticationError(code, resp) smtplib.SMTPAuthenticationError: (534, b'5.7.14 <https://accounts.google.com/signin/continue?sarp=1&scc=1&plt=AKgnsbs\n5.7.14 7Iv4Nop2BfVsxIWEI1h5NxEG5QKSiQP2IRGqFYj-mB1tr4my5OBVeMzEbuG1hSttzGi2z\n5.7.14 O6-2CSgs_9v57jLx6MkoOy8yKLcw5zgCYzPQ40opvla_U9TqolpkdWMi5c4jyT1_>\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 v8sm557096wrc.114 - gsmtp') Here is my smtp settings # smtp settings EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'xbxx@gmail.com' EMAIL_HOST_PASSWORD = 'dgesfgg' -
How does a method of a class class run if you haven't instantiated an object for that class? Referring to Python's TestCase class
I am fairly new to Python (and programming in general) so this may be a noob question, but I was of the understanding that in python, when you create a class, and you create X methods within it, that if you want to leverage those methods, you need to instantiate the class or create an instance of the class. I am reviewing the TestCase module (testing goat for TDD) and I notice that we can run the program (performs all the logic within the methods of the classes) without actually creating any instance objects to "call" those methods directly. So my question is...how is it running. Ex. class AddStuff(TestCase): def test_equal_two(self): two = 1 + 1 self.assertEqual(two, 2) When I run python manage.py test, this will run, even though I haven't created an instance of AddStuff...I don't get it... -
Multiple model inheritance with one concrete and one abstract model in django
I wanted to inherit the Grandparent abstract model, parent concert model in the child model. How I'll be able to achieve this in django? There are conflicts in field name as the abstract model is having audit fields. which is common going to be common in both parent and child class. How do I override or remove the common field coming from the parent model? Below is the models which showcase what I wanted to achieve. class Audit(models.Model): is_active = models.BooleanField(default=True) created_at = models.DateTimeField(auto_now_add=True, null=True) updated_at = models.DateTimeField(auto_now=True, null=True) class Meta: abstract = True class User(Audit): class Meta: db_table = 'user' email = models.EmailField(unique=True) phone = models.CharField(validators=[phone_regex], max_length=50, unique=True) is_active = models.BooleanField(default=False) class UserProfile(User, Audit): class Meta: db_table = 'user_profile' address = models.TextField(null=True) profile_image = models.TextField(null=True) dob = models.DateField() ..... -
Serving Media files in cPanel Shared Hosting for Django Web App
I am not able to display media files on Cpanel shared hosting Django web app. I receive a Error 404 URL Not Found whenever I try to access the media file. I have specified + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) in my urls.py file. This error only occurs whenever DEBUG = False. I am using whitenoise to serve the static files without any issue it is only the media directory that causes the 404 web error. settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') I am using Python v3.8.6, Django=2.1 and CPanel Shared Hosting via NameCheap. I know it's recommended to have a webserver to store and serve media files in Production Environment but I am unable to edit the Apache httpd.conf file as mentioned in the Django documentation. -
Django Limiting Session Login Time to N seconds
I am trying to limit the amount of time a user can stay logged in for using the settings.py and using Sessions. settings.py LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' SESSION_EXPIRE_AT_BROWSER_CLOSE = False SESSION_COOKIE_AGE = 60 SESSION_SAVE_EVERY_REQUEST = True home.html {% extends 'base.html' %} {% block title %}Home{% endblock %} {% block content %} {% if user.is_authenticated %} Hi {{ user.username }}! <p><a href="{% url 'logout' %}">Log Out</a></p> {% else %} <p>You are not logged in</p> <a href="{% url 'login' %}">Log In</a> {% endif %} {% endblock %} urls.py from django.urls import path from django.views.generic.base import TemplateView # new urlpatterns = [ path('', TemplateView.as_view(template_name='home.html'), name='home') ] views.py from django.shortcuts import render def index(request): # now the index function renders the home page return render(request,'home.html') Currently it stays logged in and displays the Hi user.username no matter how long the time passes. -
How to send non-empty Origin header in POST request if running an app on localhost?
I just upgraded to Django 4 and it includes the ticket 16010 with csrf origin verification changes. To my knowledge, if you are running an app on localhost, browsers won't send origin (they will send null). So, whenever we run a Django app on localhost, we should expect a header Origin: null in POST requests. But with the recent change CSRF on localhost can't be validated because of another change - CSRF_TRUSTED_ORIGINS now need to have a scheme. release notes Is it possible to add a non-empty Origin header when POSTing from localhost?