Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: TypeError, when i try to create new user gives auth group error
I'm still learning Django. When I try to create a new user I get this error: I use Django rest framework and Djoser. I have a simple serializer that I only define the fields, and I put it in Djoser settings. I put my model "accounts" as AUTH_USER_MODEL and is a model changed from AbstractUser. If you need me to put more things here, say it. -
Mocking a class method in Python
Say I have the following: # maincode.py from othermodule import do_something class Myclass(): @staticmethod def return_array(): array_result = do_something() return array_result @classmethod def main(): array_result = cls.return_array() # Test.py # import necessary libraries for mocking class Test: @mock.patch('maincode.Myclass.return_array', autospec=True) def test(self, mock_return_array): mock_return_array.return_value = ["value1"] Myclass.main() However, I am getting TypeError: 'NonCallableMagicMock' object is not callable My mock.patch argument points to the correct place, however when I do print(cls.return_array) in main() I'm getting: <NonCallableMagicMock name='get_exposed_commands' spec='classmethod' id='________'> Any suggestions on how to fix this? Thanks -
Another user is not adding in the Banned Members
I am building a Blog Group App, In which users can make group about blogs and only one admin. Admin ban the members. BUT when i try to ban a user then it is saving some other user. Like there are 2 users and when i try to ban user_1 then user_2 is saving. AND sometimes it says Page Not Found(404). AND then i reset my database. Sometimes it says Group object query doesn't exist. I have no idea what is wrong in the code, I have tried many times but failed. models.py class Group(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30,default='') banned_members = models.ManyToManyField(User, related_name='banned_members', blank=True) class GroupPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) group = models.ForeignKey(Group,on_delete=models.CASCADE) post_title = models.CharField(max_length=30,default='') views.py def bans(request,pk): group = get_object_or_404(Group,pk=pk) post = get_object_or_404(GroupPost,pk=pk) group.banned_members.add(post.user) return redirect('home') def GroupDetailView(request,pk): data = get_object_or_404(Group,pk=pk) posts = data.grouppost_set.order_by('-date_added') context = {'data':data,'posts':posts} return render(request, 'detail_group.html',context) urls.py path('bans/<int:pk>/', views.bans, name='bans'), detail_group.html {% for pos in posts %} <a href="{{ pos.get_absolute_url }}">{{ pos.post_title }}</a> <b>User :</b>{{ pos.user }}<a href="{% url 'bans' user.id %}">BAN</a> {% endfor %} I am trying to ban user I have no idea what i am doing wrong. Any help would really be Appreciated. Thank You in Advance. -
Module "whitenoise.storage" does not define a "CompressedMainfestStaticFilesStorage" attribute/class
I'm using whitenoise to serve static files in my Django project. Here is the settings.py STATIC_URL = 'data/static/' SITE_ROOT = os.path.dirname(os.path.realpath(__file__)) STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'data/static/'), ] STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') I have my static files in data/static folder. When I try to run python manage.py collectstatic after commenting this line: STATICFILES_STORAGE = 'whitenoise.storage.CompressedMainfestStaticFilesStorage' It runs fine. But when I try to run collectstatic after uncommenting this, it gives the above error. Anyone has any idea as to why is this an error? Here are the apps and middleware: INSTALLED_APPS = [ 'admin_interface', 'colorfield', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles', 'app', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] And I have tried setting Debug to True and False but it doesn't work in either cases with compression on. -
how to make a query based on another existing query which made with group by in django
i trying to make a query based on selected category , for example i have a hotel website , i made a query to display category of rooms family = 'family' single = 'single' room_types = ( (family , 'family'), (single , 'single'), ) class Room(models.Model): room_no = models.IntegerField(unique=True) beds = models.IntegerField(default=2) balcon = models.BooleanField(default=False) room_type = models.CharField(max_length=15,choices=room_types,default=single) i made this query for displaying room categories , and i want to make each unique value a link and clickable , to go to that category room lists def categories(request): lists = Room.objects.values('room_type', 'beds', 'balcon').annotate( total=Count('pk') ).order_by('room_type', 'beds', 'balcon') return render(request,'rooms/categories.html',{'lists':lists}) <div class="grid grid-cols-1 gap-6 pt-3 pt-8 sm:grid-cols-2 md:grid-cols-3 lg:grid-cols-4 "> {% for i in lists %} <a href="{% url to go to list of rooms based on that category %}" class="transition transform cursor-pointer duration-400 hover:scale-105 hover:shadow-xl"> <div class="h-32 overflow-hidden rounded-tl-2xl rounded-tr-2xl room"></div> <div class="items-center p-2 rounded-bl-xl rounded-br-xl bglightpurple"> <div class="text-center rounded-lg" style="background: #534e70;"> <p class="inline textorange "><i class="bi bi-columns-gap"></i></p> <p class="inline text-white">{{i.room_type}}</p> </div> <div class="flex flex-wrap items-center justify-between mt-4 text-white"> <div class="text-sm"> <p class="inline ">{{i.beds}} beds</p> <p class="inline px-1 text-sm bg-yellow-500 rounded-lg">{{i.total}}</p> </div> <div class="text-sm"> <p class="inline px-1 text-sm bg-green-500 rounded-lg">{{i.balcon}}</p> </div> </div> </div> </a> {% endfor %} </div> i'm … -
django url pattern "The empty path didn't match any of these."
I am trying to configure static files for django v2.2.1 following this https://docs.djangoproject.com/en/2.2/howto/static-files/ In settings.py: STATIC_URL = '/static/' STATICFILES_DIR = [ os.path.join(BASE_DIR, 'static'), ] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') In urls.py: from django.contrib import admin from django.urls import include, path from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Project directory: But I'm getting this error when running localhost:8000 I've been scratching my head for too long. What am I missing here? -
Issue in display media preview in sharing the link in Javascript code for Django project
I am using below code snippet in my media gallery project : {% block head %} <meta property="og:title" content="{{image.title}}"> <meta property="og:image" content="{{ image.file.url }}"> <meta property="og:description" content="{{ image.description }}"> {% endblock %} But, when i am sharing the link on social media, i am only seeing the description of image and not the image preview . Attached is the screenshot. Screenshot of image link share to facebook Please help. -
Djnago QuerySet: distinct() work for one field, but don't work for enother
I have QuerySet with two fields: ```Python print(products_mtm) <QuerySet [ {'fk_products': 2653, 'fk_classes': 20}, {'fk_products': 2653, 'fk_classes': 23}, {'fk_products': 2653, 'fk_classes': 29}, {'fk_products': 2654, 'fk_classes': 20}, {'fk_products': 2654, 'fk_classes': 21}, {'fk_products': 2654, 'fk_classes': 24}, {'fk_products': 2655, 'fk_classes': 20}, {'fk_products': 2655, 'fk_classes': 25}, ....] print(products_mtm.values_list('fk_products').distinct()) <QuerySet [(2653,), (2654,), (2655,),...] # It's OK! print(products_mtm.values_list('fk_classes').distinct()) <QuerySet [(20,), (23,), (29,), (20,), (21,), (24,), (20,) (25,)...] #It does't DISTINCT it is full values_list of the 'fk_classes' ``` -
Django forms with classbased view
I am using class-based views for my forms but I'm not using Crispy forms instead I'm using these to submit my form- views.py: class PostCreateView(LoginRequiredMixin, CreateView): model = post fields = ['content'] def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form) and post-form.html: {% extends "blog/base.html" %} {% block content %} <main> <div class="container"> <div class="row"> <div class="col-md-8 my-5"> <div class="content-section" style="padding:10px 20px"> <form method="POST" enctype='multipart/form-data'> <fieldset class="form-group"> {% csrf_token %} <fieldset> <label for="content">Name:</label> <input type="text" id="content" name="content"> </fieldset> <button type="submit">Sign Up</button> </form> </div> </div> </div> </main> Now my question is is it safe to use in this way. Can it handle multiple requests for a production environment? -
Django oscar - customizing StockRecordForm form
I am trying to customize StockRecordForm in django-oscar administration. What I have: Forked dashboard app, also catalogue_dashboard Included new StockRecord attribute in models.py Updated forms.py like this: class StockRecordForm(base_forms.StockRecordForm): class Meta(base_forms.StockRecordForm.Meta): fields = [ 'partner', 'partner_sku', 'price_currency', 'price', 'num_in_stock', 'low_stock_threshold', 'new_attribute', ] from oscar.apps.dashboard.catalogue.forms import * Part of my INSTALLED_APPS looks like this: #'oscar.apps.dashboard.apps.DashboardConfig', #'oscar.apps.dashboard.catalogue.apps.CatalogueDashboardConfig', 'mikeapps.dashboard.apps.DashboardConfig', 'mikeapps.dashboard.catalogue.apps.CatalogueDashboardConfig', But modification is not showing up. Is there anything else I should modify? -
getting 'cannot unpack non-iterable int object' when creating a model in Django
My models.py from django.db import models from django.contrib.auth.models import User import datetime from django.utils import timezone # Create your models here. class LiveClass(models.Model): standard = models.IntegerField() no_of_students_registered = models.IntegerField(default=0) class Meta: verbose_name_plural = 'Class' def __str__(self): return str(self.standard) + ' class' class User_details(models.Model): name = models.OneToOneField(User, on_delete = models.CASCADE, max_length=30) standard = models.IntegerField(default=0) email = models.EmailField() mobile_number = models.IntegerField() class Meta: verbose_name_plural = 'User_details' def __str__(self): return str(self.name) class Mentor(models.Model): name = models.CharField(max_length=30) details = models.TextField() ratings = models.FloatField(default=0) class Meta: verbose_name_plural = 'Mentors' def __str__(self): return self.name class LiveClass_details(models.Model): standard = models.ForeignKey(LiveClass, on_delete=models.CASCADE) chapter_name = models.CharField(max_length=30) chapter_details = models.TextField() mentor_name = models.ForeignKey(Mentor, max_length=30, on_delete=models.CASCADE) class_time = models.DateTimeField() end_time = models.DateTimeField(default=timezone.now()) isDoubtClass = models.BooleanField(default=False) doubtsAddressed = models.IntegerField(default=0) no_of_students_registered = models.IntegerField(default=0) no_of_students_attended = models.IntegerField(default=0) class Meta: verbose_name_plural = 'LiveClass_details' def __str__(self): return self.chapter_name class SavedClass(models.Model): class_details = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'SavedClasses' def __str__(self): return 'SavedClass : ' + str(self.class_details) class RegisteredClass(models.Model): class_details = models.ForeignKey(LiveClass_details, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: verbose_name_plural = 'RegisteredClass' unique_together = ['class_details', 'user'] def __str__(self): return 'Registered Class' + str(self.class_details) serializers.py from rest_framework import serializers from . import models class LiveClass_serializer(serializers.ModelSerializer): class Meta: model = models.LiveClass fields = '__all__' … -
fliter onto a prefetch django
Hello I want to know why my queryset don't work. models.py: class Category(models.Model): category = models.CharField(max_length=60) slug = models.SlugField(unique=True) class Product(models.Model): categories = models.ManyToManyField(Category, related_name="products") ... my queryset: Category.objects.prefetch_related( Prefetch( "products", queryset=Product.objects.annotate( effective_stock=... ), ) ).filter(products__effective_stock__gt=0) I get: Related Field got invalid lookup: effective_stock Thank you -
We have detected that you have triggered a build from source code, remote: ! at least twice
I found this error I tried log but couldn't find the solution, please let me know if anyone having the solution to this problem, actually two repositories is crated how to remove one so my code push on Heroku server ........ (tmenv) C:\Users\ok\Desktop\Django\Django_project\taskmate>git push heroku master Enumerating objects: 346, done. Counting objects: 100% (346/346), done. Delta compression using up to 4 threads Compressing objects: 100% (336/336), done. Writing objects: 100% (346/346), 1.50 MiB | 329.00 KiB/s, done. Total 346 (delta 58), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: Heroku/python remote: -----> App not compatible with buildpack: https://buildpack-registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote:! Push failed remote:! remote: ! ## Warning - The same version of this code has already been built: f6098f48382cfe82018384a09a28f785eb546aae remote: ! remote: ! We have detected that you have triggered a build from source code with version f6098f48382cfe82018384a09a28f785eb546aae remote: ! at least twice. One common cause of this behavior is attempting to deploy code from a different branch. remote: ! remote: ! If you are developing on a branch and deploying via git you must run: remote: ! … -
Not Found: / Error while deploying project on pythonanywhere
I'm deploying python django website on pythonanywhere. I added favicon.ico in static files and settings in my project and after running the web app I'm seeing Not Found The requested resource was not found on this server. and in error log getting : 2021-06-19 04:39:55,391: Not Found: /favicon.ico 2021-06-19 04:42:25,484: Not Found: / 2021-06-19 06:03:44,307: Not Found: / 2021-06-19 06:04:05,420: Not Found: / I have added code in urls.py : path( "favicon.ico",RedirectView.as_view(url=staticfiles_storage.url("favicon.ico"))) header.html : <link rel="icon" type="image/x-icon" href="{% static 'favicon.ico' %}"> and also install django-favicon package. how do I get rid of it? -
nested categories in Django and usage in template
I followed some instructions given by stackoverflow's answer for nested categories( by making the category model reference itself in the field called "parent"), but while implementing it, I came across the template tag problems where I can't really iterate the object since the error message says I can't. I tried to avoid this problem by trying using {% for i in c.c_set.all %}(where c stands for the for iterator in my template for loop) but just in vain. How can I loop through the nested categories in my html template using Django? thank you so much for your answer in advance! ###It's my models.py's Category model. class Category(models.Model): parent = models.ForeignKey('self', default=None, null=True, blank=True, related_name='nested_category', on_delete=models.CASCADE) nesting_level = models.IntegerField() name = models.CharField(max_length=50, unique=True) slug = models.SlugField(max_length=60) def __str__(self): return self.name ##This is my context_processors.py's function that returns "Category" querysets. def categories(request): Category = Category.objects.all() return { 'Category':Category, } ###This is my base.html's nav bar tags. <nav> <ul>{% for c in Category %} <li><a href="{{c.get_absolute_url}}">{{c.nesting_level}}{{c}}</a> <ul> {% for i in c %} <li><a href = "#">{{ i.name}}</a></li> {% endfor %} </ul> </li> {% endfor %} </ul> </nav> -
how can i insert html code from database into django template?
i tried to insert it via dtl variables but there were html tags on the page models.py html code in desciption field class Vacancy(models.Model): title = models.CharField(max_length=100) specialty = models.ForeignKey(Specialty, on_delete=models.CASCADE, related_name="vacancies") company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name="vacancies") skills = models.TextField() description = models.TextField() salary_min = models.FloatField() salary_max = models.FloatField() published_at = models.DateTimeField() html <a href="#"><img src="/media/company_images/{{ vacancy.company.logo }}" width="130" height="80" alt=""></a> <div class="d-flex align-items-baseline align-content-baseline"> <h1 class="h2 mt-4 font-weight-bold" >{{ vacancy.title }}</h1> <p class="m-0 pl-3">{{ vacancy.salary_min }}р – {{ vacancy.salary_max }}р</p> </div> <p class="mt-2">{{ vacancy.skills }}</p> <p class="text-muted mb-4">Primal Assault (15-30 человек), Рязань или удаленно</p> <div style="line-height: 1.8;"> {{ vacancy.description }} </div> -
Unable to recover Postgres server after power outage
I lost power to my Debian sandbox server running Django/Postgres. Now Django can't connect to Postgres: > python manage.py runserver 0:8000 [...] django.db.utils.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (::1) and accepting TCP/IP connections on port 5432? could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? Searching for the exact error I understand this is a postgres error. I verified the postgresql server is running: > sudo systemctl status postgresql ● postgresql.service - PostgreSQL RDBMS Loaded: loaded (/lib/systemd/system/postgresql.service; **enabled**; vendor preset: enabled) Active: **active** (exited) since Wed 2021-06-16 21:15:49 EDT; 2 days ago I found this post from 6 years ago, django.db.utils.OperationalError Could not connect to server(2015) with a solution; however, the accepted answer wants a file and directory my installation of Postgres on Debian does not have /usr/local/var... or postmaster.pid: > find . -iname '*postmaster*' /postgresql/11 ./lib/bitcode/postgres/postmaster ./lib/bitcode/postgres/postmaster/postmaster.bc ./bin/postmaster The error message is somewhat misleading to my objective. Database settings are configured as default (localhost:5432)--the firewall is not configured for remote connections (sudo ss -tulpn | grep 5432 shows nothing; sudo lsof -nP -iTCP -sTCP:LISTEN has no setting … -
How can I change/update field value in my User model by button?
I'm using django-cookiecutter User model (added VideoTape ManyToMany connection). I've created my own model VideoTape. I want to create the option of adding a VideoTape for the user (by updating? videotapes field in User) by clicking the "RENT" button on page VideoTape details: models.py: class User(AbstractUser): name = CharField(_("Name of User"), blank=True, max_length=255) first_name = None # type: ignore last_name = None # type: ignore videotapes = models.ManyToManyField(VideoTape, blank=True, null=True) def get_absolute_url(self): return reverse("users:detail", kwargs={"username": self.username}) class VideoTape(models.Model): title = models.CharField(max_length=256, verbose_name=_("VideoTape Title")) slug = models.SlugField(max_length=256, unique=True, editable=False) description = models.TextField(verbose_name=_("VideoTape Description")) genres = models.TextField(verbose_name=_("VideoTape Genres"), null=True) thumbnail = models.URLField(null=True) def save(self, *args, **kwargs): if not self.slug: base = self.title.strip() for candidate in generate_slug(base): if not VideoTape.objects.filter(slug=candidate).exists(): self.slug = candidate break else: raise Exception("Can't create new VideoTape object") super().save(*args, **kwargs) def get_absolute_url(self): return reverse("videotapes:detail", kwargs={"slug": self.slug}) def __str__(self): return self.title videotape_detail.html {% extends "base.html" %} {% block content %} {% if request.user.is_superuser %} <div> <a href="{% url 'videotapes:update' slug=videotape.slug %}" class="btn btn-outline-primary"> <i class="fa fa-edit"></i>Edit </a> <a href="{% url 'videotapes:delete' slug=videotape.slug %}" class="btn btn-outline-danger"> <i class="fa fa-times"></i>Delete </a> </div> {% endif %} <div class="card"> <div class="card-horizontal"> <div class="img-square-wrapper"> {% if videotape.thumbnail %} <img class="" src="{{ videotape.thumbnail }}" alt="Card image cap" … -
How to prevent Django Post_Save signal fire twice? (dispatch_uid="my_unique_identifier" DOES NOT WORK for me)
How to prevent Django Post_Save signal fire twice? (dispatch_uid="my_unique_identifier" DOES NOT WORK for me) @receiver(post_save, sender=Session, dispatch_uid="my_unique_identifier") def post_save_session_email_to_manager(sender, instance, created, **kwargs): print('hihi') Why print('hihi') is fired twice when model (sender) Session is updated ? Any workaround ? -
In Django Todo App how can each user have a distinct set of the task?
I am making a todo app using Django. Currently, the problem I am facing is that no matter which user logs in, the same set of tasks appears, i.e. if a user adds some task for himself, they appear in every other user's todo list. How can I modify my code so that each user can have a distinct set of tasks? Here's some of my code: Here is my Code: Models from django.db import models # Create your models here. class TodooModel(models.Model): fd = models.TextField() cr_dt = models.DateTimeField(auto_now_add=True) Views.py from django.shortcuts import render,redirect from .models import TodooModel # Create your views here. def home(request): if request.user.is_authenticated: return render(request,"home.html") else: return redirect("user_login") def create(request): if request.user.is_authenticated: if request.method == "POST": fdk= request.POST.get("task") data = TodooModel(fd=fdk) data.save() return render(request,"create.html",{"msg":"Added Succesfully"}) else: return render(request,"create.html") else: return redirect("user_login") def views(request): if request.user.is_authenticated: data = TodooModel.objects.get() return render(request,"views.html",{"data":data}) else: return redirect("user_login") def delete(request,id): if request.user.is_authenticated: de = TodooModel.objects.get(id=id) de.delete() return redirect("views") else: return redirect("user_login")''' > `Blockquote` -
*name* is not defined
I am making a webpage using React frontend and Django backend. I have trouble running my backend because things supposedly aren't defined. E.g. I get this message when trying to run "python manage.py makemigrations": "name 'api_view' is not defined". All the yellow underlines says that name is not defined, except the one on line 1. I did not have this problem the last time a run my code (a month ago). Everything was working fine then. What can I do to fix it? -
I want to create a relational Database in Django with user_auth table which is created automatically in postgreSQL
I want to create a Relational database with auth_user table which is automatically created in django after migrations(database is postgresql). I have created a table with class named order. My models.py looks like this Models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class order(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) product = models.CharField(max_length=50) price = models.IntegerField() now I want to link the user id with table order with user_id. And my views.py looks like this. views.py def order_Data(request): product = request.POST['product'] price = request.POST['price'] orders = order(product=product,price=price) orders.save() messages.info(request,'Data saved') return render(request,'home.html') I think I have linked tables properly but in user_id of order table is setting as null and giving me error. I dont know what to do now. Please Help me out (Iam also a learner in Django). Thank you in advance. -
Delete view for combined models
What I am trying to do is to delete the instance from a combined list from more than one models, I am getting the error 'list' object has no attribute 'filter' here is my class based delete view class NotificationDeleteView(LoginRequiredMixin, DeleteView): template_name = 'gym_admin/confirm_delete.html' success_url = reverse_lazy('notification_dash') success_message = 'Notification deleted successfully!' def get_queryset(self): subscription = Subscription.objects.filter(user=self.request.user).last() if subscription.status == 'active': promo_notification = PaidPromoNotification.objects.all() program_notification = PaidProgramNotification.objects.all() blog_notification = BlogPaidNotification.objects.all() video_notification = VideoPaidNotification.objects.all() qs = list( chain(promo_notification, program_notification, blog_notification, video_notification) ) return qs elif subscription.status == 'trialing': promo_notification = PromoNotification.objects.all() program_notification = ProgramNotification.objects.all() blog_notification = BlogNotification.objects.all() video_notification = VideoNotification.objects.all() qs = list( chain(promo_notification, program_notification, blog_notification, video_notification) ) return qs -
Django DetailView and FormView on same URL, how to handle form validation errors?
I'm creating a page where a question (DetailView) is asked and the user can answer (FormView) using the same URL. I've basically followed the advice from the docs here - https://docs.djangoproject.com/en/3.2/topics/class-based-views/mixins/#an-alternative-better-solution class QuestionView(View): def get(self, request, *args, **kwargs): view = QuestionDetailView.as_view(template_name='question_detail.html') return view(request, *args, **kwargs) def post(self, request, *args, **kwargs): view = AnswerFormView.as_view() return view(request, *args, **kwargs) My DetailView is something like this where you can see I am adding the form to the context. In addition I do some extra validation in my AnswerForm.clean() method. class QuestionDetailView(DetailView): model = QuestionModel def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['form'] = AnswerForm return context It can be displayed properly and when the user submits the Answer (via a POST) it can work when my form validation passes. The problem is how to handle this when the form validation fails because the get_context_data() belongs to the GET, not the POST. I tried just adding the same get_context_data() to the POST related code but then the form errors do not show up on the form, so the user doesn't know what is wrong. Any advice welcome, thanks. -
How can I pass multiple parameters into the API url in Django Rest Framework?
kindly guide me in this matter I'm a beginner looking forward to you