Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How does a Django ModelForm base class replace widgets for all DateFields?
I have a very simple HTML date picker widget: class NativeDateInput(forms.widgets.DateInput): input_type = 'date' I can use this widget in a repeat-yourself manner in a single ModelForm: class DirectFormExample(ModelForm): my_date = forms.DateField(widget=NativeDateInput) ... I would like a DRY version of this that replaces widgets for all date fields for forms inheriting from an abstract ModelForm base class, but I cannot work out what this should be from either of these strongly related questions: Django Problem inheriting formfield_callback in ModelForms https://stackoverflow.com/a/661171/4107809 class BaseModelForm(ModelForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name, field in self.fields.items(): if isinstance(field, django.forms.fields.DateField): field.widget = NativeDateInput class Meta: abstract = True class SimpleExample(models.Model): my_date = models.DateField() class SimpleForm(BaseModelForm): class Meta: model = SimpleExample fields = ['my_date'] Unlike for the repeat-yourself version, this fails: Widget.use_required_attribute() missing 1 required positional argument: 'initial' How can I perform the widget replacement for all DateFields in all forms inheriting from BaseModelForm? -
Django Multiple Vendor for brick and molar store
I need to find a way to use Django models or forms to upload products to a specific vendor. For example, I have 3 vendors at my store A01, A02, and A03. A01 sells 4 products, A02 sells 1 product, and A03 sells 20 products. In the form I type: A01 - product 1 - cost A01 - product 2 - cost A01 - product 3 - cost A01 - product 4 - cost A02 - product 1 - cost......... and so on and when I send the form it reads and updates and adds products of the vendor that sold it. if that makes sense. -
Unable to customize user registration with djoser
I have being using djoser with django to handle register and login. I have no issue configuring the default register field (username, email, password and re_password). But now I want to customize the register field and add gender and hobby. However, I keep getting the following error when I try to register another user with these additional fields that djoser does not provide by default. user = User.objects.create_user(**validated_data) TypeError: UserManager.create_user() missing 2 required positional arguments: 'gender', 'hobby' The error is coming from the function in models.py file for creating new user shown below: class UserManager(BaseUserManager): def create_user(self, username, email, gender, hobby, password=None, **extra_fields): if username is None: raise ValueError(_('Username is required')) if email is None: raise ValueError(_('Enter a functional email address')) if gender is None: raise ValueError(_('Provide your gender')) if hobby is None: raise ValueError(_('Enter hobby')) user = self.model(email=self.normalize_email(email) **extra_fields) user.username=username user.gender=gender, user.hobby=hobby user.set_password(password) user.save() return user def create_superuser(self,username, email, gender, hobby, password=None): if password is None: raise ValueError(_('Please enter your password')) user = self.create_user(email=self.normalize_email(email)) user.username=username user.gender=gender, user.hobby=hobby user.is_superuser = True user.is_staff = True user.save() return user class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=25, unique=True, default='') email = models.EmailField(max_length=255, unique=True) gender = models.CharField(max_length=50, null=True, blank=True) hooby = models.CharField(max_length=50, null=True, blank=True) is_active … -
How to create a model by specifying the field names of the Foreign key that are unique together rather than it's pk?
I'm trying to configure REST framework serializer to POST a Target object by specifying the 3 field names of it's Foreign relation Market that are unique together (symbol, exchange, type), rather than specifying the primary keys of the Market object. models.py class Exchange(models.Model): exid = models.CharField(max_length=12, unique=True) class Market(models.Model): symbol = models.CharField(max_length=5) type = models.CharField(max_length=5) exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE, related_name='market') class Meta: unique_together = ['symbol', 'type', 'exchange'] class Target(models.Model): weight = models.FloatField() exchange = models.ForeignKey(Exchange, on_delete=models.CASCADE, related_name='target') market = models.ForeignKey(Market, on_delete=models.CASCADE, related_name='target') dt = models.DateTimeField(null=True) Instead of this : { "weight": 19.23, "market": 11, "dt": "2022-06-09" } I would like to post in this form : { "weight": 0.1923, "market_symbol": "ABC/USD", "market_type": "xyz", "market_exchange_exid": "my_exchange", "dt": "2022-06-09" } To achieve this I created a class ModelSerializer and added the 3 custom fields that uniquely specify a market, as suggested in Specifying fields explicitly. class TargetSerializer(serializers.ModelSerializer): market_symbol = serializers.StringRelatedField() market_type = serializers.StringRelatedField() market_exchange = serializers.StringRelatedField() class Meta: model = Target fields = ('id', 'weight', 'dt', 'market_symbol', 'market_type', 'market_exchange') However when I push the data it throws a Bad Request 400. How can I tell him to use this fields as a Foreign key selector ? -
how create form for multiple data and related tabels in django
I want to save several photos for product at the same time when creating a product with one form for product and images this is my models.py class Producte (models.Model): title = models.CharField(max_length=30) price = models.PositiveBigIntegerField() inventory = models.IntegerField(default=0) __discount__ = models.IntegerField(default=0) description = models.TextField() @property def totulpoint(self): like = Comments.objects.filter(commentType=0).count() persentlike = Comments.objects.all().count() / like return 100 / persentlike @property.setter def discount (self , number): if not number in range(0,100): raise ValueError("dicsount must be in range 1,99") else: self.__discount__ = number @property def discount(self): return self.price - (self.price * (self.__discount__ / 100)) class Images(models.Model): image = models.ImageField() producteid = models.ForeignKey(to=Producte ,on_delete=models.CASCADE) this is my forms.py class ProducteForm(forms.Form): title = forms.CharField(max_length=30) price = forms.IntegerField() inventory = forms.IntegerField(default=0) __discount__ = forms.IntegerField(default=0) description = forms.Textarea() @property.setter def discount (self , number): if not number in range(0,100): raise ValueError("dicsount must be in range 1,99") else: self.__discount__ = number class Meta : fields = [ "title", "price", "inventory", "discount", "description", ] Sorry for asking such a question, I'm new to Django Django -v => 4.0.5 -
Django Dynamic/Clone Models
I am looking for a way to achieve the following with Django, would appreciate it if someone can point me in the right direction to do this. There are 3 registered models in an app (Model1,Model2 and Model3). The user will submit a form (single field, e.g. Project Name and Submit button), let's say the project he creates by submitting this form is 'PROJECT001'. Then what is expected to be done is to copy/clone the 3 models (Model1,Model2 and Model3) with a suffix of the project, i.e. 3 new models should be created 'PROJECT001_Model1', 'PROJECT001_Model2', 'PROJECT001_Model3'. I have tried to search for this, however can't find any resources. The closest I have found is https://code.djangoproject.com/wiki/DynamicModels but this documentation seems confusing. Any help is appreciated. Thanks. -
Some problem in customizing a serializer of Djoser
I created two customized serializer for the user_create and current_user endpoints in Djoser. I also wanted to have re_password field in user registeration. But when I add "USER_CREATE_PASSWORD_RETYPE": True in the setting of Djoser, my serializer for create user doesn't work. Could you tell me where is the problem? here is my serializer: from djoser.serializers import UserSerializer as BaseUserSerializer, UserCreateSerializer as BaseUserCreateSerializer class UserCreateSerializer(BaseUserCreateSerializer): class Meta(BaseUserCreateSerializer.Meta): fields = ['id', 'username', 'password', 'email', 'first_name', 'last_name'] class UserSerializer(BaseUserSerializer): class Meta(BaseUserSerializer.Meta): fields = ['id', 'username', 'email', 'first_name', 'last_name', 'password'] and here is settings of Djoser: DJOSER = { "USER_CREATE_PASSWORD_RETYPE": True, "SERIALIZERS": { 'user_create': 'core.serializers.UserCreateSerializer', 'current_user': 'core.serializers.UserSerializer', } } -
Use QueryManager in Filter After SelectRelated
I'm trying to do select_related join in Django followed by a bunch of filtering. queryset = Foo.foo_manager.all().select_related("bar").filter( bar__field_1__gt=0, bar__field_2=1, bar__field_3__lt=100, bar__field_4="X", ) But the Bar class already has its own query manager called bar_manager that fetches all instances that match this condition. Is there a way to use this after the select_related? E.g. queryset = Foo.foo_manager.all().select_related("bar").filter(bar__bar_manager__all=True) -
How can I implement post_save signals in Django?
I am currently building a geolocation app, and I'm somewhat stuck somewhere. I'm trying to implement a post_save Django signals in this code, but I can't figure out what exactly I need to do. any help here would be appreciate. Here's my code: from ipaddress import ip_address from django.contrib.auth import get_user_model from celery import shared_task from apps.users.abstractapi import AbstractAPI User = get_user_model() @shared_task def enrich_user(user_pk): user = User.objects.get(pk=user_pk) api = AbstractAPI() location_details = api.get_geolocation_details(ip_address=user.ip_address) if location_details is not None: user.country = location_details.get("country") user.country_code = location_details.get("country_code") user.country_geoname_id = location_details.details.get("country_geoname_id") user.longitude = location_details.get("longitude") user.latitude = location_details.get("latitude") user.save(update_fields=("country", "country_code", "country_geoname_id", "longitude", "latitude")) holiday_details = api.get_holiday_details( country_code=user.country_code, day=user.date_joined.day, month=user.date_joined.month, year=user.date_joined.year, ) if holiday_details is not None and any(holiday_details): user.joined_on_holiday = True user.save(update_fields=("joined_on_holiday",)) -
How to know the receiver email in django email
I create a webform where user can enter name, subject, message and email. This is how i recieve in views.py files name=request.POST['name'] email=request.POST['email'] subject=request.POST['subject'] message=request.POST['message'] print(name,email,subject,message) send_mail( subject=subject, message=name +'\n'+ message, from_email=email, recipient_list=['myemail@gmail.com'], fail_silently=False, ) The email received to me is via the email which I have defined in settings.py as EMAIL_HOST_USER. I have no clue who the sender is? One way is to add the email in message parameter. Then to reply user, i have to copy the email id from the mail body and then paste it To of gmail and then I can send it back. Is there a way, instead of receiving email from my mail ID, i get it from sender email ID, so i can reply. Thanks -
Problem when deleting ImageField from database
models.py: Picture = models.ImageField('Picture', null=True, blank=True) When I give the command person.Picture.delete() the picture is deleted from the directory, but in the database still has the record of the file path in Picture as shown in image below. How can I delete it? -
django - No such file or directory: '/static/album.html' in production
i created a django app which is working absolutely fine in my local server but when i'm deploying it to azure web app it's homepage is working fine but some tasks in views.py file of my project even after running collectstatic command is not working and giving this error csss & js files are loading but the file i want to load in getData fn is not loading. here is views.py file of my app. from django.shortcuts import render, HttpResponse from django.templatetags.static import static import requests from bs4 import BeautifulSoup import pandas as pd import os def index(request): return render(request, 'main.html') def getData(request): num = 0 album = [] song = [] streams = [] b = [] temp = open(static("album.html"), "w") temp.close() and this is how my my settings.py file looks STATIC_URL = '/static/' STATICFILES_STORAGE = "whitenoise.storage.CompressedManifestStaticFilesStorage" STATIC_ROOT = BASE_DIR / "staticfiles" STATICFILES_DIRS = [ BASE_DIR / "static" ] this is how my project's folder directory looks like hello is my project name (lol) and jdbsdata is my app and the 'staticfiles' folder is created automatically after running collectstatic command but main static folder is the 'static' one Help me please why it can't locate static folder in views.py … -
Django include app from another project url problem
First of all, hello everyone, thank you in advance to anyone who can help. I'm coding a video site with Django. I wanted to add a custom admin panel to my project to add videos to the website and do other things. I downloaded the admin panel here and am trying to include it as an app in my project. But I could not fully grasp the connection between the app's (I've been using django for 2 weeks) My project has a manage.py and sqlite database file, the same is in the admin panel I downloaded. When I run it from the manage.py file of the admin panel, I can access the admin panel without any problems, but this time I am having trouble accessing the urls of my video site. My project file structure, dashboard is the admin panel i downloaded. File structure of the admin panel You can review the admin panel codes click here. myblog/myblog/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('',include('base.urls')), path('dashboard/',include('dashboard.apps.home.urls')), path('dashboard/',include('dashboard.apps.authentication.urls')) myblog/base/urls.py urlpatterns = [ path('',views.index,name="index"), path('main/',views.main,name="main"), path('video/<slug:slug>/',views.video,name="video"), path('test/',views.addVideo,name="addVideo"), path('apivideo/',views.apivideo,name="apivideo"), ] -
django.db.utils.OperationalError when running MySQL/MariaDB in Docker: Lost connection to MySQL server at 'reading initial communication packet'
Running Django version 4 locally with: manage.py runserver 127.0.0.1:8000 And running MySQL/MariaDB in a Docker container: docker run -p 3306:3306 --name $(DATABASE_NAME) -v /tmp/mysql:/var/lib/mysql -e MYSQL_DATABASE=$(DATABASE_NAME) -e MYSQL_USER=$(DATABASE_USER) -e MYSQL_ROOT_PASSWORD=$(DATABASE_PASSWORD) -d mariadb:latest > /dev/null Error django.db.utils.OperationalError: (2013, "Lost connection to MySQL server at 'reading initial communication packet', system error: 2") I can successfully connect to the database with MySQL Workbench as well as the command: mysql -h 127.0.0.1 -P 3306 -u root -p <database> I am launching Django and the MySQL/MariaDB Docker container from a Makefile. Makefile SHELL := /bin/bash .PHONY: dj-start-local dj-start-local: start-mysql PYTHONPATH=. django_project/src/manage.py runserver 127.0.0.1:8000 .PHONY: start-mysql start-mysql: docker run -p 3306:3306 --name $(DATABASE_NAME) -v /tmp/mysql:/var/lib/mysql -e MYSQL_DATABASE=$(DATABASE_NAME) -e MYSQL_USER=$(DATABASE_USER) -e MYSQL_ROOT_PASSWORD=$(DATABASE_PASSWORD) -d mariadb:latest > /dev/null -
Django get related object's QuerySet inside annotate
My Models class Post(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) #Unnecessary class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name="user_comments") post = models.ForeignKey(Post, on_delete=models.CASCADE,related_name="post_comments") liked_users = models.ManyToManyField(User, blank=True, related_name="liked_comments") disliked_users = models.ManyToManyField(User, blank=True related_name="disliked_comments") #Unnecessary What I Have Normally, i use this code to make my comment objects have the attribute "voting" and order them by that attribute. comments = models.Comment.objects.annotate(voting=Count("liked_users")-Count("disliked_users")).order_by("-voting") But when I want to query posts, I can't reach their comments: What I Want I want my QuerySet "posts" to have an attribute for every single post, called "best_3_comments". Which is a QuerySet of comments of them ordered by their voting's. Can I achieve this without querying all of the comments everytime I query posts? posts = models.Post.objects.annotate( best_3_comments = get_query_of_the_posts_comments("post_comments").annotate( voting=Count("liked_users")-Count("disliked_users") ).order_by("-voting")[:3] ) What function(s) can i use to get query of the post's comments, and how should i approach this ? I'm completely open to new ideas of ways to do what I want to achieve, I couldn't find which function and how to use for it. Thank you in advance. -
Django Queryset to include and filter related data
I'm trying to render a template with a list of participants (adult and minor) and their latest checkin and checkout times. There are two types of participants and they are represented in two tables/models: AdultParticipant and MinorParticipant. MinorParticipants have a foreign key relationship to the ParentParticipant. Checkin information (checkin and checkout) is stored in a single table irregardless of whether the checkin data refers to AdultParticipant or the MinorParticipant. One record in this table captures the participant reference and the checkin and checkout times. Any participant can have many checkins. A checkin record can only have one participant. The code as it exists now does everything I want except it displays every checkin record for the participant. I only want to display the last (most recent) record for the participant. How can I construct the queryset to include the participant information and include only the last checkin record for the participant? Thank you in advance. You are appreciated. Models class AdultParticipant(models.Model): first_name = models.CharField(max_length=50) middle_initial = models.CharField(max_length=50, blank=True) class MinorParticipant(models.Model): first_name = models.CharField(max_length=50) middle_initial = models.CharField(max_length=50, blank=True) parent = models.ForeignKey( WaiverAdult, on_delete=models.CASCADE, related_name='minor_of_adult') class CheckIn(models.Model): adult = models.ForeignKey( AdultParticipant, on_delete=models.CASCADE, blank=True, null=True, related_name='adult_checkin') minor = models.ForeignKey( MinorParticipant, on_delete=models.CASCADE, blank=True, null=True, … -
twilio + django calling from browsers
hello working on django app, I set up twilio voice calls in my app, I realised that users can't call in all browsers, but only brave browser, what might be the problem, and how can I solve it? -
How do I separate the attributes of a class in a Django admin form in sections?
Django admin site shows the attributes of a class in a form so you can add a new object, I want to know if there is an easy way to separate the attributes in sections to make the form more organized, like having a "Physical features" section title over fields about physical features, similar to how inline attibutes work having the name of the inline class as a section name. -
Django viewset annotate in subquery based on filterset field
It seems like this should be a common use case but i cant find an existing answer online. I am trying to annotate a count based on a query that is filtered using a filterset field in DRF. class SurveyViewset(viewsets.ModelViewSet): entries = models.SurveyEntry.objects.filter( survey=OuterRef("id") ).order_by().annotate( count=Func(F('id'), function='Count') ).values('count') queryset = models.Survey.objects.annotate( total_entries=Subquery(entries) ).all().order_by("id") serializer_class = serializers.SurveySerializer filter_backends = ( SurveyQueryParamsValidator, CaseInsensitiveOrderingFilter, django_filters.DjangoFilterBackend, SearchFilter, ) filterset_fields = { "surveyaddressgroup": ("exact",), } I have surveys and I want to count the number of SurveyEntry based on a a particular address group. I.e. I ask a survey in a several shopping centres, and I want to see the results when i only choose 1 particular centre to show. At the moment, I get total count regardless of filter the main query. How can i make the subquery take the filterset choice into account? -
In Django's models.Manager create method, how do I store a random object in a foreignkey field?
I am able to create Game objects that have the product_selection field being populated correctly, but for some reason, the correct_product field is not getting populated. Why is that? Here is my code from models.py: import random class GameManager(models.Manager): def create_game(self, player): game = self.create(player = player) product_selection = random.sample(list(Product.objects.exclude(users_who_viewed=player)),3) game.product_selection.set(product_selection) game.correct_product = random.choice(product_selection) return game class Game(models.Model): player = models.ForeignKey(User, on_delete= models.CASCADE,related_name='costcorrect_player') score = models.IntegerField(default=0) product_selection = models.ManyToManyField(Product, blank=True, null=True) correct_product = models.ForeignKey(Product, on_delete= models.CASCADE, related_name='costcorrect_correct_product', null=True) objects = GameManager() -
Heroku with waitress and django
I am trying to use waitress because I am on windows. I cant seem to quite get the Procfile right. This is everything in that file right now. import waitress from waitress import serve web: waitress-serve --port=$PORT QRCodes.wsgi:application There is a yellow warning under 'port' and a red error under '$PORT'. I have looked everywhere and cannot find a solution to this. Please help! -
Can't select related category in Django
I have 2 models class InnerCategory(models.Model): name = models.CharField(max_length=100) slug = models.SlugField(unique=True) class Product(models.Model): name = models.CharField(max_length=70) category = models.ForeignKey(InnerCategory, null=True, on_delete=models.SET_NULL) slug = models.SlugField(unique=True) so i'm trying to get Product queryset and select related Category like so queryset = Product.products.filter( category__slug=self.kwargs['category_slug'] ).select_related('category') print(queryset.category) and when i try to run this page i get an error AttributeError: 'QuerySet' object has no attribute 'category' so how can i get all my Products and Categories in one query -
How to fix "There is no current event loop in thread" when using Celery to execute an asyncio coroutine?
I need to execute an coroutine that establishes websocket streams from a Celery Task in my Django application, but it throws RuntimeError: There is no current event loop in thread 'ThreadPoolExecutor-1_0'. When I insert set_event_loop between new_event_loop and run_until_complete it's still the same error. What could be the solution ? tasks.py from myapp.celery import app import nest_asyncio nest_asyncio.apply() @app.task(bind=True, name='Websocket starter') def ws_starter(self): ws_loops() methods.py import asyncio import nest_asyncio nest_asyncio.apply() def ws_loops(self): async def method_loop(args): while True: try: do_stuff() except ccxt.NetworkError as e: break await client.close() async def clients_loop(loop, dic): do_stuff() await asyncio.gather(method_loop(args)) await client.close() async def main(loop): do_stuff() loops = [clients_loop(loop, dic) for dic in lst] await asyncio.gather(*loops) loop = asyncio.new_event_loop() # asyncio.set_event_loop(asyncio.new_event_loop()) loop.run_until_complete(main(loop)) setings.py os.environ["DJANGO_ALLOW_ASYNC_UNSAFE"] = "true" -
Django Forms: Select a valid choice. That choice is not one of the available choices
I am using Django as a CRUD app to run on a Postgresql database. Every quarter, data is added, and I need a way to update the underlying data. I have a form set up, but when I try to save the form, I get met with "Select a valid choice. That choice is not one of the available choices." I have other forms (that work) set up on my app that do not have this issue, and the code is similar for those. Can anyone tell me what is happening here? forms.py: class MarketViewForm(ModelForm): class Meta: model = MarketView fields = "__all__" widgets = { 'marketview_entry' : forms.NumberInput(attrs={'class' : 'form-control', 'placeholder': 'Marketview Entry'}), 'costarid' : forms.NumberInput(attrs={'class' : 'form-control', 'placeholder': 'Costar ID'}), 'direct_available' : forms.NumberInput(attrs={'class' : 'form-control', 'placeholder': 'Direct Available Space'}), 'direct_vacant' : forms.NumberInput(attrs={'class' : 'form-control', 'placeholder': 'Direct Vacant Space'}), 'sublet_available' : forms.NumberInput(attrs={'class' : 'form-control', 'placeholder': 'Sublet Available Space'}), 'status' : forms.Select(attrs={'class' : 'form-control', 'placeholder': 'Development Status'}), 'import_date' : forms.SelectDateWidget(attrs={'class' : 'form-control', 'placeholder': 'Import Date'}) } labels = { 'marketview_entry' : "Marketview Entry", 'id' : "ID", 'direct_available' : "Direct Available Space", 'direct_vacant' : "Direct Vacant Space", 'sublet_available' : "Sublet Available Space", 'status' : "Development Status", 'import_date' : "Import Date" } … -
How do you run a function to compare two date by month?
I'm trying to run a function to compare today's month with the month input by a user. The dates will be input by the user as 'YYYY-MM-DD'. This is what I have so far: class Sneaker(models.Model): name = models.CharField(max_length=100) brand = models.CharField(max_length=100) description = models.TextField(max_length=250) date = models.DateField('release date') price = models.IntegerField() def worn_for_the_month(self): return self.worn_set.filter(date=date.today().month).count == date.month But get the following error: fromisoformat: argument must be str So I tried using the following function instead with string: def worn_for_the_month(self): return self.worn_set.filter(date=str(date.month)) == str(date.month) And I get this error: %(value)s” value has an invalid date format. It must be in YYYY-MM-DD format. I'm not sure if I'm using the right type of function at this point. I just want to compare the month we're in with the one the user entered.