Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
'RegisterAPI' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method
I am trying to display a register_view here and I'm getting the error. I have made some changes to the views fil,e but i am still getting the errors and i don't know how to fix it. Here is my views.py file: from django.shortcuts import render from rest_framework.response import Response from rest_framework import generics, permissions from knox.models import AuthToken from .serializer import RegistrationSerializer class RegisterAPI(generics.GenericAPIView): user_serializer_class = RegistrationSerializer def post(self, request, *args, **kwargs): user_serializer = self.get_serializer(data=request.data) data = {} if user_serializer.is_valid(): user = user_serializer.save() return Response({ "user": RegistrationSerializer(user, context=self.get_serializer_context()).data, "token": AuthToken.objects.create(user)[1] }) else: data = user_serializer.error return Response(data) And here is what is in my serializer.py file: from rest_framework.serializers import ModelSerializer, CharField from rest_framework.serializers import ValidationError as Error from django.contrib.auth.models import User class RegistrationSerializer(ModelSerializer): password2 = CharField( style={'input_type': 'password'}, write_only=True) class Meta: model = User fields = [ "username", "email", "password", "password2" ] extra_kwargs = { 'password': {'write_only': True} } def save(self): user = User( email=self.validated_data['email'], username=self.validated_data['username'] ) password1 = self.validated_data['password1'] password2 = self.validated_data['password2'] if password1 != password2: raise Error({'password': 'Passwords must match'}) user.set_password(password) user.save() return user -
Is there a more DRY way to create these repetitive django class based views, and URL patterns?
Is there a better, more DRY way to create repetitive sets of views and urls in django? Below are my views and urls. As you can probably see, There are currently two sets of views and urls that are would be identical if not for the different model name. Is there a way to create 3 classes at once as a mixin or something similar to that so that all I have to do to add a new set of classes is pass the model name to one function or child class? Is there something similar I could do for the urls? relevant section in views: class AlertMessageUpdate(LoginRequiredMixin, UpdateView): template_name = "LibreBadge/applicationadmin/AlertMessage/alertMessageForm.html" model = AlertMessage fields = "__all__" class AlertMessageCreate(LoginRequiredMixin, CreateView): template_name = "LibreBadge/applicationadmin/AlertMessage/alertMessageForm.html" model = AlertMessage fields = "__all__" class AlertMessageList(LoginRequiredMixin, ListView): template_name = "LibreBadge/applicationadmin/AlertMessage/alertMessageList.html" model = AlertMessage class BadgeTemplateUpdate(LoginRequiredMixin, UpdateView): template_name = "LibreBadge/applicationadmin/BadgeTemplate/badgeTemplateForm.html" model = BadgeTemplate fields = "__all__" class BadgeTemplateCreate(LoginRequiredMixin, CreateView): template_name = "LibreBadge/applicationadmin/BadgeTemplate/badgeTemplateList.html" model = BadgeTemplate class BadgeTemplateList(LoginRequiredMixin, ListView): template_name = "LibreBadge/applicationadmin/BadgeTemplate/badgeTemplateList.html" model = BadgeTemplate relevant section in urls.py: url(r'^applicationadmin/alertmessages/update/(?P<pk>[-\w]+)/$', views.AlertMessageUpdate.as_view(), name='AlertMessageUpdate'), url(r'^applicationadmin/alertmessages/create/$', views.AlertMessageCreate.as_view(), name='AlertMessageCreate'), url('applicationadmin/alertmessages/$', views.AlertMessageList.as_view(), name='AlertMessageList'), url(r'^applicationadmin/badgetemplates/update/(?P<pk>[-\w]+)/$', views.BadgeTemplateUpdate.as_view(), name='BadgeTemplateUpdate'), url(r'^applicationadmin/badgetemplates/create/$', views.BadgeTemplateCreate.as_view(), name='BadgeTemplateCreate'), url('applicationadmin/badgetemplates/$', views.BadgeTemplateList.as_view(), name='BadgeTemplateList'), The answer to this question will be used in … -
Django. How to "join" two models that have foreignkeys to a third model?
I'm learning Django and getting data from join tables is proving to be difficult. My models are: class User(AbstractUser): pass class Post(models.Model): username_p = models.ForeignKey("User", on_delete=models.CASCADE, related_name="user_p") post = models.CharField(max_length=365) like = models.PositiveIntegerField(default=0) timestamp = models.DateTimeField(auto_now_add=True) def __str__(self): return f"{self.username_p} posted {self.post} the {self.timestamp}, and the post has {self.like} likes" def serialize(self): return { "id": self.id, "username": self.username_p.username, "post": self.post, "like": self.like, "timestamp": self.timestamp.strftime("%b %d %Y, %I:%M %p"), } class Follower(models.Model): followername = models.ForeignKey("User", on_delete=models.CASCADE, related_name="follower") followedname = models.ForeignKey("User", on_delete=models.CASCADE, related_name="followed") def __str__(self): return f"{self.followername} follows {self.followedname}" I'm trying to join all tables to get all the posts (including username_p, post, like and timestamp) from all the followedname users that one followername user may have. Any ideas on what query could work on my views.py? -
How to organise relationships between Django model?
I have basic Django User model, from django.contrib.auth.models import User Person model class Person(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) and Comment model class Comment(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) comment = models.CharField(max_length=255) I wanna make something like: I created User, I has own unique id ( for example 1). I created Person, I has own unique id and link to User. And then I created Comment - it has link to Person model. I want that one User can have many Persons. One Person can have Comments -
Collect Static Error when trying to deploy Django application to heroku
I have put a decent amount of work into my first Django project and I wanted to host it on heroku. I have seen solutions to this problem elsewhere but everything I've tried doesn't seem to fix the error I'm getting and I've been trying to fix this for 6 hours so I figuered I'd just ask. I'm trying to use whitenoise for the static files the static files work fine in my local server, and I can run collect static in my console without any error. Here is the error -----> $ python manage.py collectstatic --noinput Traceback (most recent call last): File "/tmp/build_2341adf2_/manage.py", line 22, in <module> main() File "/tmp/build_2341adf2_/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/app/.heroku/python/lib/python3.9/site-packages/django/core/management/__init__.py", line 345, in execute settings.INSTALLED_APPS File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 83, in __getattr__ self._setup(name) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 70, in _setup self._wrapped = Settings(settings_module) File "/app/.heroku/python/lib/python3.9/site-packages/django/conf/__init__.py", line 177, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "/app/.heroku/python/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module … -
How can have two filed of Generic Relations in same model django
class Customer(models.Model): name = models.CharField(max_length=100) class Staff(models.Model): name = models.CharField(max_length=100) class MoneyTransfer(models.Model): received_by = generic relation payed_by = generic relation How Implement two generic field in django model ? -
fatal error: libmemcached/memcached.h: no such file or directory
I try to setup a development environment for developing on django itself. Docs: Contributing / Running the test suite for the first time python -m pip install -r requirements/py3.txt It fails: ... x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -DUSE_ZLIB -I/home/guettli/.virtualenvs/djangodev/include -I/usr/include/python3.8 -c src/_pylibmcmodule.c -o build/temp.linux-x86_64-3.8/src/_pylibmcmodule.o -fno-strict-aliasing -std=c99 In file included from src/_pylibmcmodule.c:34: src/_pylibmcmodule.h:42:10: fatal error: libmemcached/memcached.h: no such file or directory 42 | #include <libmemcached/memcached.h> | ^~~~~~~~~~~~~~~~~~~~~~~~~~ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 What can I do to fix this? -
Django: How to display posts from specific categories on a page
i am building a blog in Django and where register user can write blog articles . I want to display posts that are associated with certain categories on one page. i tried to do that but it does not show the post associated to the article. here is my files models.py from django.db import models from django.contrib.auth.models import User from django.urls import reverse from datetime import datetime, date class Category(models.Model): name = models.CharField(max_length=255) def __str__(self): return self.name def get_absolute_url(self): # return reverse('article', args=(str(self.id))) return reverse('home') # go to home page after article submission class Post(models.Model): title = models.CharField(max_length=255) tags = models.CharField(max_length=255, default="Ryan's World") author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() post_date = models.DateField(auto_now_add=True) category = models.CharField(max_length=255, default="uncategorized") def __str__(self): return self.title+' | '+str(self.author) def get_absolute_url(self): # return reverse('article', args=(str(self.id))) return reverse('home') # go to home page after article submission views.py created function based view from django.shortcuts import render from django.views.generic import ListView, DetailView, CreateView, UpdateView, DeleteView from .models import Post, Category from .forms import PostForm, EditForm from django.urls import reverse_lazy class HomeView(ListView): model = Post template_name = 'home.html' ordering = ['-id'] def CategoryView(request, cats): category_posts = Post.objects.filter(category=cats) return render(request, 'categories.html', {'cats':cats ,'category_posts': category_posts }) . . . urls.py from django.urls … -
Changing the "extra" value of modelformset
Inside my views.py I have got a line of code, that has an extra value, that tells me a number of image fields, that I am able to use. ImageFormSet = modelformset_factory(Image, form=ImageForm, extra=3) Is there a way to change that extra fixed value from the form view? So when I click button add more it would change the value to +1 (extra=4) and add another button to add next image? Is it even possible, or do I have to find another way to be able to upload adjustable number of images. -
How to integrate amar pay gateway in django
This is a payment integration Api. import requests url = " https://sandbox.aamarpay.com/index.php" myobj ={ 'store_id':'aamarpaytest', 'tran_id':'a8r4yjrhkflndcjs4', 'success_url':'www.succes.com', 'fail_url':'www.fail.com', 'cancel_url':'www.fail.com', 'amount':'10', 'currency':'BDT', 'signature_key':'dbb74894e82415a2f7ff0ec3a97e4183', 'desc':'yes,pls', 'cus_name':'sakin', 'cus_email':'test@gmail.com', 'cus_add2':'Dhaka', 'cus_city':'dhaka', 'cus_postcode':'dhaka', 'cus_country':'Bangladesh', 'cus_phone':'01905555555' } x = requests.post(url, data = myobj) After passing those information they give a redirect link with a unique track id . <html xmlns="http://www.w3.org/1999/xhtml"> <head> <script type="text/javascript"> function closethisasap() { document.forms["redirectpost"].submit(); } </script> </head> <body onload="closethisasap();"> <form name="redirectpost" method="post" action="/paynow.php?track=AAM1607838673103267"> </form> </body> </html> And this link work totally fine. Is there any way ? I can use this in django .i want to grab this redirect link and pass my user through this link.And this html has auto submit script.So i think their's another way to resolve this problem.But i can't figure it out. Help me out how can i configure this in views. And And unfortunately they don't have any python module to make work easier .. Because of some native mobile banking system, i have to use it .I have no choice .. any documentation,or any link which i can follow Thank you in advance 😊 -
How to extend session model in django to create new fields?
I want to extend the base session model in Django to create two new fields which are 'Date Created' and 'User Id'. I searched the Stack Overflow for answers and I found one which is related to my question here and also in the django docs here but it is not clear how it works and why it is done that way. Maybe because, I am new to Django I am having trouble understanding them. So can you please provide a simpler explanation. -
Dependencies of Django Project
I created a setup.py and setup.cfg like explained in the Django docs. Now I am unsure how to add dependencies to my project. If someone installs my code, other tools like Pillow should automatically get installed. I read that install_requires is the right way (not requirements.txt), but how to specify this? The file setup.py looks pretty generic, and all content is in setup.cfg. But examples I see all have their list of dependencies in setup.py via install_requires. How to specify the dependencies of a Django project? -
error in django templates at {{form.as_table}} when trying to use Create form
I'm workin on a project of a webApp for fleet managment, using Django 3.1 and Python 3.7. I'm using models: class Driver(Employee): supervisor_id = models.ForeignKey('Supervisor', on_delete=models.CASCADE, blank=True, null=True) projects = models.ManyToManyField('Client', through='ProjectFleet', blank=True, null=True) is_driver=True def __str__(self): return (self.last_name) class Client(models.Model): client_name = models.CharField(max_length=128, blank=True, null=True) client_adress = models.CharField(max_length=128, blank=True, null=True) client_logo = models.ImageField(upload_to='ClientsLogos/', max_length=100, blank=True, null=True) phone_number1 = PhoneNumberField(blank=True, null=True) phone1_label = models.CharField(max_length=128, blank=True, null=True) phone_number2 = PhoneNumberField(blank=True, null=True) phoneé_label = models.CharField(max_length=128, blank=True, null=True) phone_number3 = PhoneNumberField( blank=True, null=True) phone3_label = models.CharField(max_length=128, blank=True, null=True) client_email1 = models.EmailField(blank=True, null=True) email1_label = models.CharField(max_length=128, blank=True, null=True) client_email2 = models.EmailField(blank=True, null=True) email2_label = models.CharField(max_length=128, blank=True, null=True) client_email3 = models.EmailField(blank=True, null=True) email3_label = models.CharField(max_length=128, blank=True, null=True) drivers = models.ManyToManyField('Driver', through='ProjectFleet') def __str__(self): return (self.client_name) class ProjectFleet(models.Model): client_id = models.ForeignKey('Client', blank=True, null=True, on_delete=models.SET_NULL) drivers = models.ForeignKey('Driver', blank=True, null=True, on_delete=models.SET_NULL) def __str__(self): return (self.client_id) class Contract(models.Model): client_id = models.ForeignKey('Client', blank=True, null=True, on_delete=models.SET_NULL) contract_title = models.CharField(max_length=128, blank=True, null=True) contract_details = models.CharField(max_length=512, blank=True, null=True) effective_date = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True) expiration_date = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True) def __str__(self): return (self.contract_title) the views I'm trying to use : class DriverCreationView(LoginRequiredMixin, CreateView): model = Driver fields = ['registration_number','first_name', 'last_name', 'password', 'cni', 'birth_date', 'birth_city', 'picture', 'matricule_cnss', 'driving_licence', 'recruitment_date', 'phone', 'salary', 'Contract_type', … -
Django Exceptions Unregistered Namespace
I am receiving the following error: "File "C:\Users\odesm\anaconda3\envs\adb3\lib\site-packages\django\urls\base.py", line 83, in reverse raise NoReverseMatch("%s is not a registered namespace" % key) django.urls.exceptions.NoReverseMatch: 'accounts' is not a registered namespace" I have reviewed similar errors on stack overflow and attempted their solutions but none of them seem applicable. I do not understand in what manner I have failed to register the namespace when it has been specified in the path(include(namespace="")) and I have included the app_name="app_name" in the corresponding url.py file. base.html (the snippet throwing the error) <li class="nav-item"> <a class="nav-link" href="{% url 'accounts:login' %}">Login</a> </li> urls.py (under a sitemanger app) app_name = 'sitemanager' urlpatterns = [ path('', views.HomeView.as_view(), name='site-home'), path('accounts/', include('accounts.urls', namespace='accounts')), path('accounts/', include('django.contrib.auth.urls')), ] urls.py (for the accounts app) app_name = 'accounts' urlpatterns = [ path('login/', auth_views.LoginView.as_view(template_name='accounts/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(template_name='accounts/logout.html'), name='logout'), path('signup/', views.SignUpView.as_view(template_name='accounts/signup.html'), name='signup'), path('edit/', views.UpdateProfileView.as_view(template_name='accounts/update_profile.html'), name='edit'), path('<slug:username>/', views.ProfileView.as_view(template_name='accounts/profile.html'), name='profile') ] To me, it appears I have registered the proper namespace but it seems my logic is at fault somewhere. -
Authentication for users not working in django
I have a model created in the database that stores all the user information and I am creating a login page against which I want to authenticate all my users. However , authenticate() returns NONE and I am not able to understand the reason. I thing that I am confused at is , I am not sure if the user is getting authenticated against the model shown below :- Models.py :- from django.db import models class Client(models.Model): SEX_CHOICES = [('M', 'Male'), ('F', 'Female')] fname = models.CharField(max_length=100) lname = models.CharField(max_length=100) password = models.CharField(max_length=50, default=True) mailid = models.EmailField(max_length=100) sex = models.CharField(max_length=1, choices=SEX_CHOICES, blank=True) age = models.IntegerField() forms.py :- class AuthForm(forms.ModelForm): class Meta: model = Client fields = ['mailid', 'password'] labels = { 'mailid': 'Email', 'password': 'Password' } widgets = {'password': forms.PasswordInput(), } views.py :- def auth(request): if request.method == 'POST': filled_form = AuthForm(request.POST) if filled_form.is_valid(): mailid = filled_form.cleaned_data['mailid'] password = filled_form.cleaned_data['password'] user = authenticate(request, mailid=mailid, password=password) if user is not None: login(request, user) return redirect('home') else: note = 'Sorry, could not verify!' new_form = AuthForm() return render(request, 'auth.html', {'authform': new_form, 'note': note}) -
ArrayField not recognized in Django 3.1.4 for MongoDB database
I am trying to use the ArrayField in Django ORM, but it is not recognized. This is my code: from django.db import models from django.forms import forms # Create your models here. class Produtos(models.Model): authors : models.ArrayField() -
Is is possible to make property as primary key in model Django?
Currently I'm an inexperienced newcomer in Django and developing API endpoint using this framework A class contains a property with custom id as below. When POST a new A, custom_id is generated automatically from default id in Django e.g. 'A00001', 'A00002', 'A00003', ... class A(models.Model): name = models.CharField(max_length=64) @property def custom_id(self): return '{}{:05d}'.format('A', self.pk) def __str__(self): return self.name I would like to use custom_id as primary key to this model instead of default id. If so, I wanna use custom_id for POST/PATCH/UPDATE/DELETE request as well Is it possible to achieve that and how to modify the class? Thanks. *Note: custom_id is a string type, not integer. I know it's a bad idea to use string type for primary key but please feel free to skip it for a moment. -
Calling a view as a value for action's attribute in HTML forms that leads to a NoReverseMatch error
I am creating a web application using django, and I want now to add a view that modifies entries (my web application is an encyclopedia, so the view let us editing the page). We may be able to access the editing page by cliking on the link of this html page: {% extends "encyclopedia/layout.html" %} {% block title %} {{ title }} {% endblock %} {% block body %} {{ html | safe }} {% if exists %} <br><br><br><br> <a href="{{ address }}">Edit encyclopedia</a> {% endif %} {% endblock %} So django'll go through this url urlpatterns = [ ... ... ... path("<str:title>/edit", views.edit, name="edit"), ] Then, this url should bring us to a this view: def edit(request, title): if request.method == "POST": form = NewForm(request.POST) if form.is_valid(): with open(f"entries/{title}.md", "w") as file: file.write(form.cleaned_data["content"]) return redirect(reverse("encyclopedia:display")) else: return render(request, "encyclopedia/edit.html",{ 'form' : NewForm(), 'message' : """<div class="alert alert-danger" role="alert"> Your entries are empty. </div>""" }) markup = util.get_entry(title)[0] print(request.) return render(request, "encyclopedia/edit.html",{ 'form' : NewForm(), 'title' : title, 'markup': markup, }) And here is my html file: {% extends "encyclopedia/layout.html" %} {% block title %} Edit {% endblock %} {% block body %} <h1>New Encyclopedia</h1> <p>Our websites' encyclopedias are written … -
How to autofill a slug field in django
I am trying to build a Blog app with django. Here is my model: class BlogPost(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=264) slug = models.SlugField(max_length=264,unique=True) content = models.TextField() image = models.ImageField(upload_to='blog_images') publish_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) def __str__(self): return self.title Everything works fine, there are no errors. But, what I want is that, whenever a user creates a new blog post and starts to write a title, the slug should start filling itself. Meaning that if the title of a blog post is Flask Mega Tutorial, the slug of that post should automatically become flask-mega-tutorial, without the user needing to set a slug. How can I do this? -
Redirect from login to a dynamic user by id in Django
Good afternoon folks, I'm stuck on this. I am using class-based views and when I log in correctly I want to enter this url: http://127.0.0.1:8000/8/ where "8" is the id of my custom Proxy model. this is my view class-based login enter image description here This is my model, where when the id takes a specific value such as 8 it will show me the data of that model and when it is 9 it will show me the data of the id = 9 enter image description here the videos and many publications I see that in settings they place LOGIN_REDIRECT_URL = '/ 8 /' but it is not a solution to a dynamic id -
How can I elegantly represent negative dollar amounts in DTL?
I have a model representing billionaires and certain statistics about them. One of the fields is ytd_change, a float representing the amount of net worth the subject gained since the previous year, in millions of US dollars. (This metric was in the original corpus, not calculated.) Negative numbers indicate losses in net worth. For positive dollar amounts, it's simple enough. But net worth losses come out odd: Example: <li>{{ billionaire.name }}: ${{ billionaire.ytd_change }}M</li> For Larry Page and Carlos Slim respectively, this evaluates to: Larry Page: $4720.0M Carlos Slim: $-75.3M Is there an elegant way to get the negative sign in the proper place (i.e. "-$75.3M") with the built-in filters? It doesn't seem right to handle this in the view. Should I add representational methods to the model? Or is a custom filter the best answer? -
ImproperlyConfigured Exception in Django, how can i fix it?
Exception has occurred: ImproperlyConfigured Requested setting AUTH_USER_MODEL, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. File "C:\Users\Brians Surface\vidly\api\models.py", line 2, in from tastypie.resources import ModelResource -
Is there annotate for nested serializer in django?
class CustomUserSerializer(serializers.ModelSerializer): updated_at = serializers.SerializerMethodField() ip_address = serializers.IPAddressField(read_only=True) is_expert = serializers.SerializerMethodField() has_profile = serializers.SerializerMethodField() def get_is_expert(self, obj): return obj.profiles.all().filter(expert_profile__status=ExpertProfile.APPROVED).exists() or obj.request_expert def get_has_profile(self, obj): return obj.profiles.exists() class ProfileBasicInfoSerializer(serializers.ModelSerializer): user = CustomUserIDNameSerializer(read_only=True) expert_profile = ExpertBasicInfoSerializer(read_only=True) class Meta: model = Profile fields = ['user', 'expert_profile', 'mobile_number'] class MandateReadOnlySerializer(serializers.ModelSerializer): author = serializers.StringRelatedField(read_only=True) designator = ProfileSerializer(read_only=True) designee = ProfileSerializer(read_only=True) address = AddressSerializer(read_only=True) updated_at = serializers.SerializerMethodField() class Meta: model = Mandate fields = "__all__" def get_updated_at(self, instance): return (instance.updated_at+datetime.timedelta(hours=9)).strftime("%Y-%m-%d %H:%M:%S") [queryset] Mandate.objects.all().select_related('address', 'designator', 'designator__address','designator__user', 'designee', 'designee__expert_profile', 'designee__user', 'author').prefetch_related('address', 'designator', 'designator__expert_profile', 'designator__user', 'designee', 'designee__address', 'designee__user', 'author').prefetch_related('designator__expert_profile', 'designee__expert_profile')' Those serializers are nested. Like MandateReadOnlySerializer is called in Modelviewset. ProfileSerializer is called in MandateSerializer. CustomUserSerializer is called in ProfileSerializer. At this situation, I don't want to call get_is_expert method called Mandate.length times. Because it makes N+1 problem. And also there is no advantage more caculation. The results are all same. Because the Custom user is same. Just Mandate model is only different. I am trying to make annotate for that value in ModelViewset but it isn't look like possible to make annotation for nested serializer. I also tried cached_property but It doesn't work. Is there any way to prevent N+1 Problem? Please help me. -
Django - directly using the Model class to avoid writing a Form class explicitely
Currently prototyping for a Django app. I have code that defines a model and a form, which I then use to have users enter new instances in the DB. For instance: models.py class Produits(models.Model): no_prod = models.CharField(max_length=70) descfr = models.CharField(max_length=70) cost = models.DecimalField(max_digits=10, decimal_places=2) prix1 = models.DecimalField(max_digits=10, decimal_places=2) prix2 = models.DecimalField(max_digits=10, decimal_places=2, default=None) forms.py class CreateProduct(forms.Form): no_prod = forms.CharField(max_length=70) descfr = forms.CharField(max_length=70) cost = forms.DecimalField(max_digits=10, decimal_places=2) prix1 = forms.DecimalField(max_digits=10, decimal_places=2) prix2 = forms.DecimalField(max_digits=10, decimal_places=2) views.py def create_product(request): if request.method == "POST": form = CreateProduct(request.POST) if form.is_valid(): # create a product p = Produits(**form.cleaned_data) p.save() return HttpResponseRedirect('/soum/produits') # let's say go back to product list or something else: form = CreateProduct() return render(request, 'soum/produitsform.html', {'form': form}) That works all right. However, the form & the model fields are exactly the same. In fact in the application a number of classes in the models may map one to one in this way. Is there a clever way in Django simplify the code above, so that "by default" I could just create a form that directly uses a model, and then only make explicit forms for those classes that don't map 1 to 1? -
Template loader not looking at directories defined in DIRS
I'm trying to add a base template for use in different apps in my Django project. I've created a base.html file at "myapp/templates/base.html" Here is the relevant info in my settings.py: BASE_DIR = Path(__file__).resolve().parent.parent TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(os.path.dirname(os.path.dirname(os.path.abspath(__file__))), 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] When I try to load the view in my browser, I get a this error: TemplateDoesNotExist at /home/ base.html Request Method: GET Request URL: http://127.0.0.1:8000/home/ Django Version: 3.1.1 Exception Type: TemplateDoesNotExist Exception Value: base.html Exception Location: /Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages/django/template/backends/django.py, line 84, in reraise Python Executable: /Library/Frameworks/Python.framework/Versions/3.8/bin/python3 Python Version: 3.8.5 Python Path: ['/Users/jonmi/PycharmProjects/projects/grocery', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python38.zip', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/lib-dynload', '/Library/Frameworks/Python.framework/Versions/3.8/lib/python3.8/site-packages'] Server time: Sun, 13 Dec 2020 01:43:02 +0000 As I understand it, the template loader should look in each of my installed_apps' template directories since APP_DIRS is set to True, and it should also look in any directory in the DIRS list. However, the template loader is only looking in the app directories (e.g. myapp/home/templates/home/base.html) and not in anything I add to the DIRS list. I've tried changing whats in the DIRS list, including just trying to type out the path to base.html as a string myself, but it …