Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Customize/remove select box blank option in Django
Code category_options = ( ('th','Technology'), ('sc','Science'), ('f','Food'), ('t','Travel'), ('h','Health'), ('fa','Fashion'), ) class Blog(models.Model): title = models.CharField(max_length=150) description = models.TextField() category = models.CharField(choices=category_options,max_length=2) View image It creates an option at the top of the list that has no value and displays as a series of dashes: <option value="">---------</option> What is the cleanest way to remove this auto-generated option from the select box? I am expecting like this <option value="">Select category</option> Guys can you help me to update the empty dashes in django -
Create "ListField" that expands dynamic with an "add new element" button, Django
This question should maybe be split into two questions, but since the HTML solution (could) depend on the model (and vice versa) I'm putting it into one question. I have a model for recipes: from django.db import models class Recipe(models.Model): title = models.CharField("Title", max_length = 64, primary_key=True) what_to_do = models.TextField("What to do") n_persons = models.IntegerField(default = 2) what I want to to, is to add a way of storing ingredients for a recipe. My first thought was storing them in a list of dict, usgin the JSONField e.g [{"what":"egg","units":"pcs","N":2},{"what":"flour", "units":"gram", "N":200}]. Then I iterate over each ingredients in the template and list it like <div class = "container"> {% for ing in recipe.ingredients %} <li> {{ing.what}} - {{ing.N}} {{ing.units}} </li> {% endfor %} </div> which works fine. The issue is; how do I make some user-friendly way of adding a new ingredient to a recipe? Optimally in my template I would have 3 columns with fields like "what" "how much?" " units -------+----------------+------- ====== ====== ====== | | | | | ====== ====== ====== where the user can write what they would like. But the user should be able to add a new line if they want to add more … -
Django runserver_plus pyOpenSSL not installed error, although it is
So I try to run runserver_plus using ssl: python manage.py runserver_plus --cert-file cert.crt Then I get following error: CommandError: Python OpenSSL Library is required to use runserver_plus with ssl support. Install via pip (pip install pyOpenSSL). But the deal is that pyOpenSSL is already installed within my environment. Here is pip list output: asgiref (3.5.2) certifi (2022.9.24) cffi (1.15.1) charset-normalizer (2.1.1) cryptography (38.0.3) defusedxml (0.7.1) Django (3.0.14) django-extensions (2.2.5) idna (3.4) oauthlib (3.2.2) Pillow (7.0.0) pip (9.0.1) pkg-resources (0.0.0) pycparser (2.21) PyJWT (2.6.0) pyOpenSSL (19.0.0) python3-openid (3.2.0) pytz (2022.6) requests (2.28.1) requests-oauthlib (1.3.1) setuptools (39.0.1) six (1.16.0) social-auth-app-django (3.1.0) social-auth-core (4.3.0) sqlparse (0.4.3) urllib3 (1.26.12) Werkzeug (0.16.0) wheel (0.38.4) Screenshot: Thanks in forward for any help! I've tried to install different versions of pyOpenSSL, both erlier and later. Unsuccessfully. Runserver_plus starts successfully without additional parameters, but my point is to access virtual server securely. -
How to work with MultipleCheckBox with Django?
good afternoon, I'm new with django and I'm trying to make an application that registers the attendance of entrepreneurs (I'm currently working with this). There are some services that I would like to select, sometimes the same person requires more than one service per appointment. However, part of the application uses the Models and part uses the Forms, I'd like to keep the two ones separate to keep the code organized, but I have no idea how to do it, I even created a separate class just for the tuple that holds the values, but no I managed to implement, can anyone help me? Here are the codes: models.py from django.db import models from django_cpf_cnpj.fields import CPFField, CNPJField class CadastroEmpreendedor(models.Model): ABERTURA = 'ABERTURA MEI' ALTERACAO = 'ALTERAÇÃO CADASTRAL' INFO = 'INFORMAÇÕES' DAS = 'EMISSÃO DAS' PARC = 'PARCELAMENTO' EMISSAO_PARC = 'EMISSÃO DE PARCELA' CODIGO = 'CÓDIGO DE ACESSO' REGULARIZE = 'REGULARIZE' BAIXA = 'BAIXA MEI' CANCELADO = 'REGISTRO BAIXADO' descricao_atendimento = ( (ABERTURA, 'FORMALIZAÇÃO'), (ALTERACAO, 'ALTERAÇÃO CADASTRAL'), (INFO, 'INFORMAÇÕES'), (DAS, 'EMISSÃO DAS'), (PARC, 'PARCELAMENTO'), (EMISSAO_PARC, 'EMISSÃO DE PARCELA'), (CODIGO, 'CÓDIGO DE ACESSO'), (REGULARIZE, 'REGULARIZE'), (BAIXA, 'BAIXA MEI'), (CANCELADO, 'REGISTRO BAIXADO'), ) cnpj = CNPJField('CNPJ') cpf = CPFField('CPF') nome = models.CharField('Nome', … -
How to get country name and state name from pincode in django?
I want to get state name and country name from pincode. I'm doing a cargo application using django,in that while user giving his pincode automatically state name and country name gas to be displayed by default. -
Pydantic nested model field throws value_error.missing
Having following code running fine with Django and Ninja API framework. Schema for data validation: class OfferBase(Schema): """Base offer schema.""" id: int currency_to_sell_id: int currency_to_buy_id: int amount: float exchange_rate: float user_id: int added_time: datetime = None active_state: bool = True class DealBase(Schema): """Base deal schema.""" id: int seller_id: int buyer_id: int offer_id: int deal_time: datetime = None class UserExtraDataOut(UserBase): """Extended user schema with extra data response.""" offers: List[OfferBase] sold: List[DealBase] bought: List[DealBase] Endpoint with user object. Please, note, User model is not modified: @api.get("/users/{user_id}", response=UserExtraDataOut, tags=["User"]) def get_user_info(request, user_id): """Get user profile information with offers and deals.""" user = get_object_or_404(User, pk=user_id) return user Deal model: class Deal(models.Model): """Deal model.""" seller = models.ForeignKey( to=User, related_name="sold", on_delete=models.PROTECT, verbose_name="Seller" ) buyer = models.ForeignKey( to=User, related_name="bought", on_delete=models.PROTECT, verbose_name="Buyer" ) offer = models.ForeignKey( to="Offer", on_delete=models.PROTECT, verbose_name="Offer" ) deal_time = models.DateTimeField(auto_now=True, verbose_name="Time") It gives me this response: { "id": 0, "username": "string", "first_name": "string", "last_name": "string", "email": "string", "offers": [ { "id": 0, "currency_to_sell_id": 0, "currency_to_buy_id": 0, "amount": 0, "exchange_rate": 0, "user_id": 0, "added_time": "2022-11-22T18:37:47.573Z", "active_state": true } ], "sold": [ { "id": 0, "seller_id": 0, "buyer_id": 0, "offer_id": 0, "deal_time": "2022-11-22T18:37:47.573Z" } ], "bought": [ { "id": 0, "seller_id": 0, "buyer_id": 0, "offer_id": 0, "deal_time": … -
how to put my form in line orientation (horizontal). django forms
I want to put my form in horizontal.I tried to do this, but it got unformatted and disorganized MY HTML: <div class="tab-pane fade container-fluid p-2" id="profile" role="tabpanel" aria-labelledby="profile-tab"> <h6 class="m-0 font-weight-bold text-primary">Horas Adicionais</h6> <div class="row mt-4"> <div class="col"> {{ form_funcionarioadicional.management_form }} {% for fa in form_funcionarioadicional %} <div class="faform row"> <div class="col"> {{fa}} </div> </div> {% endfor %} </div> </div> </div> currently it is like this, I wanted to leave it horizontal How can I fix this in html, or in forms.py? -
What is the difference between request.POST.get and request.POST
usually I use POST or GET requests except for GET.get paginations, but I don't understand the concept there are only two possibilities POST or GET . example even if there is the same effect I do not understand the difference between request.GET.get('page') and request.GET["page"] request.POST['rate'] and request.POST.get('rate') -
Reverse for 'admin_update' with arguments '('',)' not found. 1 pattern(s) tried: ['admin_update/(?P<lesson_id>[^/]+)$']
I'm trying to pass arguments to edit table values. Would be grateful if anyone could breakdown the solution. views.py ` #@login_required(login_url='/admin_login/') def AdminManageRequests(request): lessons = Lesson.objects.all() return render(request,'admin/manage_requests.html',{'lessons':lessons}) def AdminUpdateRequests(request, lesson_id): lesson = Lesson.objects.get(pk=lesson_id) form = StudentRequestForm(request.POST or None, instance=lesson) context = { 'lesson':lesson, 'form':form } return render(request, 'admin/update_requests.html',context) ` urls.py ` path('admin_update/<lesson_id>', views.AdminUpdateRequests, name='admin_update'), ` manage_requests.html ` {% extends 'admin/admin_home_base.html' %} {% block admin_content %} <div> <h3 class="display-8" style="text-align:center"> Admin Lesson Request Management </h3> <hr class="my-4"> <p style="text-align:center"> You can view fulfilled and unfulfilled lesson requests. </p> <p class="lead" style="text-align:center"> {% include 'admin/partials/fulfilled_lessons.html' %} <br> {% include 'admin/partials/unfulfilled_lessons.html' %} </p> </div> {% endblock %} ` lessons_table_base.html ` <div class="card"> <div class="card-header"> <h5 class="card-title">{% block card_title %}{% endblock %}</h5> <div class="card-body table-responsive p-0"> <table class="table table-hover text-nowrap"> <thead> <tr> <th>Lesson ID</th> <th>Lesson Name</th> <th>Student</th> <th>Teacher</th> <th>Interval (Days)</th> <th>Duration (Minutes)</th> <th></th> </tr> </thead> <tbody> {% for lesson in lessons %} {% block lessons_content %} {% endblock %} {% endfor %} </tbody> </table> </div> </div> </div> ` fulfilled_lessons.html ` {% extends 'admin/partials/lessons_table_base.html' %} {% load widget_tweaks %} {% block card_title %} Fulfilled Requests&nbsp;&nbsp;<i class="bi-send-check-fill"></i> {% endblock %} {% block lessons_content %} {% if not lesson.is_request %} <tr> <td>{{ lesson.lesson_id }}</td> <td>{{ lesson.lesson_name … -
Cannot import 'Questions'. Check that 'questions.apps.QuestionsConfig.name' is correct
hi everybody i have a message django.core.exceptions.ImproperlyConfigured: Cannot import 'Questions'. Check that 'questions.apps.QuestionsConfig.name' is correct. apps.py in application questions dirctory from django.apps import AppConfig class OrdersConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'Questions' settings.py INSTALLED_APPS = [ 'questions.apps.QuestionsConfig', who can i solve this problem -
Specific model not visible for staff account in Django admin. Other models displaying as expected
I have several models in my project. All models are visible from the staff account if I add permissions for them, but one particular model is not displayed and I can't figure out why. This model is not displayed even if I add direct permissions to the user or add to a certain group with the necessary permissions, however, if I check the "Superuser status" box in the user settings, then this model appears. What could be the matter? -
TypeError at /admin/login/ 'NoneType' object is not iterable
TypeError at /admin/login/ 'NoneType' object is not iterable Request Method: GET Request URL: http://127.0.0.1:8000/admin/login/?next=/admin/ Django Version: 4.1.3 Exception Type: TypeError Exception Value: 'NoneType' object is not iterable Exception Location: E:\mohammad\Dijongo\myprojects\Greany\lib\site-packages\debug_toolbar\panels\templates\panel.py, line 47, in _request_context_bind_template Raised during: django.contrib.admin.sites.login Python Executable: E:\mohammad\Dijongo\myprojects\Greany\Scripts\python.exe Python Version: 3.10.1 Python Path: ['E:\mohammad\Dijongo\myprojects\Greany\src', 'C:\Program Files\Python310\python310.zip', 'C:\Program Files\Python310\DLLs', 'C:\Program Files\Python310\lib', 'C:\Program Files\Python310', 'E:\mohammad\Dijongo\myprojects\Greany', 'E:\mohammad\Dijongo\myprojects\Greany\lib\site-packages'] Server time: Tue, 22 Nov 2022 17:41:41 +0000 project repo: https://github.com/pythone-developer/Ecomerce-greany project repo: https://github.com/pythone-developer/Ecomerce-greany -
pywhatkit how to close youtube after song ends?
is it possible to close the youtube tab after the song ends? I want to implement python code into raspberry so I can manually close the tab each time -
full link for media in django-rest
I wrote this view: api_view(["GET"]) def article_grid_list(request): # fetched data from database data = Articles.objects.all().order_by("-created_date")[:11] pinned_article = Articles.objects.get(pinned=True) # serialized data pinned_data = ArticlesSerializer(pinned_article) horizontal_data = ArticlesSerializer(data[:3], many=True) small_data = ArticlesSerializer(data[3:8], many=True) card_data = ArticlesSerializer(data[8:], many=True) final_data = { "pinned":pinned_data.data, "horizontal": horizontal_data.data, "small": small_data.data, "card": card_data.data } when I print result of this route, I'm getting 'cover' field like this : "cover": "/media/article/artice_cover_NkOUuZ7vH3zEejCgV.jpg", but when I write this function like ModelViewSet I'm getting full url of cover field and I want to get full url in every reqeust modelViewSet Example : class ArticleGridList(viewsets.ModelViewSet): queryset = Articles.objects.all().order_by("-created_date") serializer_class = ArticlesSerializer I except like this : "cover": "http://localhost:8000/media/article/artice_cover_NkOUuZ7vH3zEejCgV.jpg", my app urls.py file : router = routers.SimpleRouter() router.register('articles', ArticlesViewSet) urlpatterns = [ path("article-grid-list/", article_grid_list) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) urlpatterns += router.urls``` -
My localhost:8000 just stopped to work. How can I get it back?
I am using ubuntu 20.04 I do not know if it matters, but I tried to see if the 8000 PORT was being used before I tried to run, and it was not. I was working on my Django project, running my localhost:8000 last night, but it stopped. Everything I have is a infinite loading. So, I returned today and I could not run my project. I do not know what happened. So, I started a new branch from the working code to check if it stopped because of me, but nothing changed. I've tried to restart and turn off my computer, I've erased my cache, I've tried in 4 different browsers (chrome, firefox, opera, brave), I've tried to re-run, and I've tried to use my local IP, but nothing happened. I am expecting to run again my project and I do not know if is related to my computer. -
Default value can be assigned for forms.DecimalField? Is it has to be already assigned in model declaration?
Wherever I try to give a default value to this field, which is supposed to be outside of my model gives error saying "default" or "attr" argument is unexpected. log_duration_minute = forms.DecimalField( help_text=_("log_duration_helper_text_minute"), default="0.00", ) The error message: __init__() got an unexpected keyword argument 'default' -
DRF Api-Key missing Attribute
I am trying to use the DRF Api Key mechanism for authentication, after following the guide here: https://florimondmanca.github.io/djangorestframework-api-key/guide/ I receive nothing but errors, does someone have a working example or see what i am doing wrong here? Global Settings: REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': [ 'rest_framework_api_key.permissions.HasAPIKey' ] } Tested in a class view also class TestingApiKey(APIView): permission_classes = [IsAuthenticated | HasAPIKey] def post(self, request):``` 3 sample curl requests: Example 1 curl --location --request POST 'http://127.0.0.1:8000/api/test' \ --header 'Authorization: Api-Key TiJwEHau.MF4ov6E3iz3C9KNNRAGdryH1tXfkjz8r' \ --header 'Content-Type: application/json' \ --data-raw '{ "username" : "Testing", "Password" : "Testing123" }' Example 2: curl --location --request POST 'http://127.0.0.1:8000/api/test' \ --header 'Api-Key TiJwEHau.MF4ov6E3iz3C9KNNRAGdryH1tXfkjz8r' \ --header 'Content-Type: application/json' \ --data-raw '{ "username" : "Testing", "Password" : "Testing123" }' Example 3 curl --location --request POST 'http://127.0.0.1:8000/api/test' \ --header 'X-Api-Key: Api-Key TiJwEHau.MF4ov6E3iz3C9KNNRAGdryH1tXfkjz8r' \ --header 'Content-Type: application/json' \ --data-raw '{ "username" : "Testing", "Password" : "Testing123" }' Each test I carry out returns a 500 server error with the response: 'HasAPIKey' object has no attribute 'authenticate' Anyone had this issue or understand why I would get this? -
What is the difference between response.COOKIES and request.session to handle cookies in DJango?
Disclaimer: I am a beginner, following the Django for everybody course on Coursera and I've looked around for explanations on Google but I can't wrap my head around this. I'm confused; request.COOKIES.get('foo', 0) and response.set_cookie('foo', 'bar') seems to be a long way round of getting and setting cookies when one can simply do: request.session.get('foo', 0) or request.session['foo'] = 'bar'. It seems like a long way around because with the response.set_cookie method I need to start a HttpResponse but with request.session. It seems that if i stick to just request.session i don't need to switch inbetween request.COOKIES and starting HttpResponses to use response.set_cookie to handle cookies. Can someone please explain what is the difference between these approaches to handling cookies and when you would/should use one or the other? -
Get sql executed by django in json format in django console without any \ and with single internal quates
I'm trying to get all the sql commands executed by django json format in django console. I'm getting some sql commands like this when I try to change them into json: "SELECT \"django_migrations\".\"id\", \"django_migrations\".\"app\", \"django_migrations\".\"name\", \"django_migrations\".\"applied\" FROM \"django_migrations\"" I want only external double quates and all the internal quates should be single without any \ in between. I tried using replace function and what not, but could'nt do it. I am expecting my sql command in like: "SELECT 'django_migrations'.'id', 'django_migrations'.'app', 'django_migrations'.'name', 'django_migrations'.'applied' FROM 'django_migrations'" -
Logging in Python Django: INFO not logging onto file
I have setup a logger in my Django project for 4 different cases: info messages, debug messages, error messages, ad gunicorn logging. Here is the content of my settings.py: LOGGING = { "version": 1, "disable_existing_loggers": False, "formatters": { "main_formatter": { "format": "{asctime}-{levelname}-{module}-{funcName}-{message}", "style": "{", }, }, "handlers": { "console": { "class": "logging.StreamHandler", "formatter": "main_formatter", }, "dfile": { "class": "logging.FileHandler", "filename": "logs/debug.log", "formatter": "main_formatter", }, "file": { "class": "logging.FileHandler", "filename": "logs/info.log", "formatter": "main_formatter", }, "efile": { "class": "logging.FileHandler", "filename": "logs/error.log", "formatter": "main_formatter", }, "gfile": { "class": "logging.FileHandler", "filename": "logs/gunicorn.log", "formatter": "main_formatter", }, }, "loggers": { "main": { "handlers": ["dfile", "console"], "propagate": True, "level": "DEBUG", }, "main": { "handlers": ["file", "console"], "propagate": True, "level": "INFO", }, "main": { "handlers": ["efile", "console"], "propagate": True, "level": "ERROR", }, "gunicorn.access": { "handlers": ["gfile", "console"], "propagate": False, "level": "DEBUG", }, }, } And here is an example: import logging [...] logger = logging.getLogger(__name__) [...] logger.error(f"{request.user}: Erreur interne. Code [LI.001]") # THIS WORKS logger.info(f"Password Generated and Sent to {email}") # THIS DOESNT WORK In my logs/ folder, I have 4 files: info.log, error.log, debug.log and gunicorn.log The only output I see is in error.log and gunicorn.log, the other 2 files are always empty. -
Cannot import settings module in django
I am building a user interface with the help of Django's authentication infrastructure. However, when i try to import any module (such as the 'User' model or the 'authenticate' function) that needs access to the settings module, i get such error: c:/Users/Lorenzo/Desktop/progetto_mondodb_di_lorenzo_giaretta/Bit4All/BitEx/main.py Traceback (most recent call last): File "c:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\Bit4All\BitEx\main.py", line 4, in <module> from views import mainWindow File "c:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\Bit4All\BitEx\views.py", line 3, in <module> from models import Profile File "c:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\Bit4All\BitEx\models.py", line 2, in <module> from django.contrib.auth.models import User File "C:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\myvenv\lib\site-packages\django\contrib\auth\models.py", line 2, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "C:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\myvenv\lib\site-packages\django\contrib\auth\base_user.py", line 47, in <module> class AbstractBaseUser(models.Model): File "C:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\myvenv\lib\site-packages\django\db\models\base.py", line 107, in __new__ app_config = apps.get_containing_app_config(module) File "C:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\myvenv\lib\site-packages\django\apps\registry.py", line 252, in get_containing_app_config self.check_apps_ready() File "C:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\myvenv\lib\site-packages\django\apps\registry.py", line 134, in check_apps_ready settings.INSTALLED_APPS File "C:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\myvenv\lib\site-packages\django\conf\__init__.py", line 79, in __getattr__ self._setup(name) File "C:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\myvenv\lib\site-packages\django\conf\__init__.py", line 66, in _setup self._wrapped = Settings(settings_module) File "C:\Users\Lorenzo\Desktop\progetto_mondodb_di_lorenzo_giaretta\myvenv\lib\site-packages\django\conf\__init__.py", line 144, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File **"C:\Users\Lorenzo\AppData\Local\Programs\Python\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) ModuleNotFoundError: No module named 'Bit4All'** It looks like in the _init_.py file, inside django/conf, which currently resides inside my virtual environment, something wrong happens while trying to import the setting module (with importlib.import_module). The snippet of code responsible for the problem: class Settings: def __init__(self, settings_module): … -
How to view all Feature Flags in views.py
I have added feature flags in my django. I defined a switch in django admin panel. The default Switch model provides all the necessary functionality.To list all the switches using manage.py, we use this command: ./manage.py waffle_switch -l How to list all the switches in views.py? -
Automatic documentation of api roles and permissions (django rest framework)
I have a Django project with various REST APIs. The permission to access those APIs are defined throught rest_framework permission classes and django.contrib.auth.models Permission model. The documentation of those apis is automatically generated using drf_yasg library, i need to find a way to inlcude in the schema generated from drf-yasg the needed permission to access every api without the need to write id down manually. Anyone can give me an hint? -
Django save form with foreign key
I am currently trying to create a form where users get to fill in their details after creating an account. The idea is that every user, after registration, gets redirected to this form page to fill it out. To achieve this, i'm using foreign keys.However it doesn't save to database. models.py class User(AbstractUser): pass def __str__(self): return self.username class Detail(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, default="") first_name = models.CharField(max_length=200, default="") last_name = models.CharField(max_length=255, default="") class Meta: verbose_name_plural = "Detail" def __str__(self): return self.first_name+ " "+self.last_name forms.py class Details(forms.ModelForm): class Meta: model = Detail fields = "__all__" widgets={ "user": forms.TextInput() } views.py def details(request): if request.method =="POST": form = Details(request.POST) if form.is_valid(): detail = form.save(commit=False) detail.user = request.user detail.first_name = detail.first_name.lower() detail.last_name = detail.last_name.lower() detail.save() return redirect("admin:index") else: form = Details(initial={"user":request.user.username}) return render(request, "details.html", {"form":form}) -
Set default author to logged in user
I have already tried this, this and this to no avail. When submitting a comment I want to default the author field to be the currently logged in user. I am using class based views and haven't found many questions and answers besides trying to implement the above. views.py class CommentPost(SingleObjectMixin, FormView): model = Article form_class = CommentForm template_name = "article_detail.html" def post(self, request, *args, **kwargs): self.object = self.get_object() return super().post(request, *args, **kwargs) def form_valid(self, form): comment = form.save(commit=False) form.instance.author = self.request.user comment.article = self.object comment.save() return super().form_valid(form) def get_success_url(self): article = self.get_object() return reverse("article_detail", kwargs={"pk": article.pk}) models.py class Comment(models.Model): article = models.ForeignKey(Article, on_delete=models.CASCADE) comment = models.CharField(max_length=140) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) def __str__(self): return self.comment def get_absolute_url(self): return reverse("article_list") article_detail.html <!-- templates/article_detail.html --> {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <body class="d-flex h-100"> <div class="container"> <div class="col-8 mx-auto"> <h3 class="pb-4 mb-4 fst-italic border-bottom">Article detail</h3> <div class="article-entry"> <h2>{{object.title}}</h2> <p class="text-black-50 fst-italic">by {{object.author}} | {{object.date}}</p> <p>{{object.body}}</p> </div> {% if user.is_authenticated and user == article.author or user.is_superuser %} <p> <button class="btn"> <a class="text-decoration-none text-white" href="{% url 'article_edit' article.pk %}">edit</a> </button> <button class="btn"> <a class="text-decoration-none text-white" href="{% url 'article_delete' article.pk %}">delete</a> </button> </p> {% endif %} <br/> …