Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
API not working after giving authentication permission
I created an API to list the employees and applied authentication permission. when I tried to load the page it shows a login page. After giving the login credentials it shows a page not found error. Before the authentication the url's was working perfectly. views.py from rest_framework.permissions import IsAdminUser class EmpListView(ListAPIView): queryset = Employee.objects.all() serializer_class = EmpModelSerializer filter_backends = [filters.SearchFilter] search_fields = ['Ename', 'Position'] permission_classes = [IsAdminUser] urls.py urlpatterns = [ path('admin/employee/', EmpListView.as_view(), name='emp-list'),] -
Custom serializer.py failed django.db.utils.IntegrityError: null value in column violates not-null constraint
What i am trying to do - is to save post to the model with custom conditions. But each time im trying to save - i receive this error django.db.utils.IntegrityError: null value in column violates not-null constraint So far, i have tried editting my models, and adding null=True in parameters, but it doesn't see to help. So what is the best way to solve the problem here? serialier.py: class EventSerializers(serializers.ModelSerializer): class Meta: model = Events fields = ["cam_id", "vehicle_plate", "is_recognition", "is_confirmation", "vehicle_plate", "transit_block_time_min"] def save(self, **kwargs): instance = super().save(**kwargs) is_recognition = instance.is_recognition is_confirmation = instance.is_confirmation vehicle_plate = instance.vehicle_plate if CarParkItem.objects.filter(vehicle_plate=vehicle_plate).exists(): instance.event_code = 1008 elif BlackListItem.objects.filter(vehicle_plate=vehicle_plate).exists(): instance.event_code = 1004 elif is_recognition == False: instance.event_code = 1003 elif is_recognition == True and is_confirmation == False: instance.event_code = 1006 elif is_recognition == True and is_confirmation == True: instance.event_code = 1007 instance.save() return instance I have read about different approaches, but editing serializer - looks like standard thing here models that are used for it: class BlackListItem(models.Model): vehicle_plate = models.CharField(max_length=999, db_index=True) valid_until = models.DateTimeField(db_index=True) description = models.CharField(max_length=999) def __str__(self): return self.vehicle_plate class CarParkItem(models.Model): vehicle_plate = models.CharField(max_length=999, db_index=True) valid_until = models.DateTimeField(db_index=True) description = models.CharField(max_length=999) def __str__(self): return self.vehicle_plate class WorkingMode(models.Model): PASSMODE_CHOICES = [ ('pay_by_hour', 'pay_by_hour'), … -
How to add these constraints to Django models?
Help me please. How to make constraints in the database? I am using sqlite, django 3.2, python 3.7 I have three models: Refbook, Versions of refbooks, Elements of refbook from django.db import models class Refbook(models.Model): code = models.CharField(max_length=100, unique=True) name = models.CharField(max_length=300) description = models.TextField() class VersionRefbook(models.Model): refbook_id = models.ForeignKey('Refbook', on_delete=models.CASCADE, related_name='versions') version = models.CharField(max_length=50) date = models.DateField() class Meta: unique_together = ('refbook_id', 'version') class Element(models.Model): version_id = models.ManyToManyField('VersionRefbook') code = models.CharField(max_length=100) value = models.CharField(max_length=300) The following constraints must be added to these models: There cannot be more than one Refbook with the same value in the "code" field. There cannot be more than one Version with the same set of values "refbook id" and "version" One Refbook cannot have more than one Version with the same date In one Version of refbook, there cannot be more than one Element of refbook with the same value in the "code" field OK. I solved the first point by adding the «unique=true» parameter to the «code» field in the Refbook class. It seems that I solved the seconf point by adding the «unique_together = ('refbook_id', 'version')» parameter to the Meta class. Third point. I think need to override the save method. But … -
Django: how to access inline fields from parent model form
I am working on a simple quiz application. There will be questions which are either multiple choice or open. From the admin site, I want to be able to add questions along with their related answers, while having the following validation: If a question's type is multiple choice, then it must have 4 possible answers and only of them should be marked as correct. If a questions's type is open then it must have only 1 answer and it must be marked as correct. Here is the relevant part of the Question and Answer models that I have. class Question(models.Model): class QuestionType(models.TextChoices): MULTIPLE_CHOICE = "MC" OPEN = "OP" text = models.CharField(max_length=250) topic = models.ForeignKey(Topic, on_delete=models.PROTECT) class Answer(models.Model): text = models.CharField(max_length=150) is_correct = models.BooleanField() question = models.ForeignKey(Question, on_delete=models.CASCADE) And here is what I have in admin.py class AnswerInline(admin.TabularInline): model = Answer class QuestionAdmin(admin.ModelAdmin): fields = ["text", "topic", "type", "difficulty"] inlines = [AnswerInline] def clean(self): """ How do I access the is_correct values of the items which are in the AnswerInline instance? """ I dont'know how to access the contents of the inline instance in the parent form(QuestionAdmin). How can I do that? Or perhaps, is there another way to achieve the … -
Why am I getting "Volumes must be mapping" error
Trying to add Django app with a PostgreSQL db to a Docker container. When trying to run "docker-compose build", I am getting a "Volumes must be mapping" error. Not sure what I'm doing wrong as it looks like the : syntax signified a mapping. When I remove the volumes sections entirely the build continues (with or without a Dockerfile reference so I've omitted that part). See docker-compose.yml: version: "3.9" services: app: build: context: . args: - DEV=true ports: - "8000:8000" volumes: - dev-static-data:/backend/django_static command: > sh -c "python manage.py wait_for_db && python manage.py migrate && python manage.py runserver 0.0.0.0:8000" environment: - DB_HOST=db - DB_NAME=devdb - DB_USER=devuser - DB_PASS=changeme - DEBUG=1 depends_on: - db - redis db: image: postgres:15-alpine volumes: - dev-db-data:/var/lib/postgresql/data environment: - POSTGRES_DB=devdb - POSTGRES_USER=devuser - POSTGRES_PASS=changeme volumes: - dev-db-data: - dev-static-data: Any ideas? -
Celery in production raise ModuleNotFoundError: No module named 'celery'
In developement all is good, app starts without any problems. However, in production, Gunicorn can't start due ModuleNotFoundError: No module named 'celery' Celery is installed properly >>> from celery import Celery >>> print(Celery) <class 'celery.app.base.Celery'> already tried changing file name to anything other than celery.py - did not help Any thoughts? -
setting up database for @shared task using celery django
The application I am working on is a multitenant application. I am using celery to run background tasks. The background tasks that get pushed to Queue (rabbitmq) are getting executed properly when run on the default db setting configured in the settings. But when I submit the background jobs from other tenants, i.e. settings other than default they fail. This is because, in normal sync flow, I am using a custom router that sets the DB to be used based on the request URL( which contains the tenant details). but the same context is lost when the job is submitted as a background task. Any suggestions ? -
Test django template equality with pytest(HTML strings)
Let me know if there is any limitation to the test below? import pytest from html.parser import HTMLParser from django.template import Template, Context # ... def test_render(settings): context = Context() template = Template('{% include 'test.html' %}') assert HTMLParser().feed(template.render(context)) == HTMLParser().feed( '<html><head><title>Testing</title></head> ' '<body><h1>This is a test!</h1></body></html> ' ) I'm using pytest without pytest-django plugin. And I just wanted to check html template equality. -
django admin interface text box size customizing
I want the Charfield box in the admin interface to be larger so that you can see your text more clearly when you write it in. heres my code in models.py from django.db import models from datetime import date # Create your models here. class BlogPost(models.Model): `created_at = models.DateField(default = date.today)` `Title = models.CharField(max_length=100)` `Tag = models.CharField(max_length=100)` `Text = models.CharField(max_length = 1000)` and here is the code in admin.py from django.contrib import admin from .models import BlogPost # Register your models here. admin.site.register(BlogPost) i looked trought the stackoverflow questions and i didnt understand it -
Safari does Preflight Request for same origin
I am currently testing my Web Application with different devices and for most of them everything works as intended. Sadly with my IPhone and Safari i am experiencing a weird issue, that it does a Preflight Options Request, when its the same origin. To my Knowledge this is not required. Sadly the Options fails. When testing with Chrome on the same device everything worked. I also tested Safari on a different Iphone and it worked there. Now the really confusing part is, when clicking on a link to the website in Discord for example with safari it works aswell without doing a Options. I know that in a "perfekt" World the Options should not fail, but that is another struggle when i was deploying the app. Currently frontend runs under https://example.com and the API under https://example.com/api. I am a absolute beginner with CORS and i am quite confused why this error happens. Another problem is that i cant really use devtools on the iphone to have a exact error message. I can only see the Options in the nginx logs and then the missing follow up request. -
How to save subform in parent form django ModelForm?
I have these models, enter image description here enter image description here with the following forms.py enter image description here I am have subform which is Bill form inside Transaction form, upon submission of transaction form, I want my bill form to be saved as well, please advice here is the view im trying enter image description here -
GenericRelation: You might need to add explicit type casts
I have a model Link: class Link(models.Model): tags = TaggableManager(through=LinkTag) actions = GenericRelation( Action, related_query_name='link', content_type_field='action_object_content_type', object_id_field='action_object_object_id', ) The Action model is here. I need to find all actions on links with tag "test1": tag=Tag.objects.filter(name="test1").first() Action.objects.filter(link__tags__name__in=[tag]) # also tried with: Action.objects.filter(link__tags__name__in=[tag.name]) However, this gives an error: Traceback (most recent call last): File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedFunction: operator does not exist: character varying = integer LINE 1: ... ON ("actstream_action"."action_object_object_id" = "links_l... ^ HINT: No operator matches the given name and argument type(s). You might need to add explicit type casts. The above exception was the direct cause of the following exception: Traceback (most recent call last): File "<console>", line 1, in <module> File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 256, in __repr__ data = list(self[:REPR_OUTPUT_SIZE + 1]) File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 262, in __len__ self._fetch_all() File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 1324, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "/usr/local/lib/python3.9/site-packages/django/db/models/query.py", line 51, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File "/usr/local/lib/python3.9/site-packages/django/db/models/sql/compiler.py", line 1175, in execute_sql cursor.execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 98, in execute return super().execute(sql, params) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 66, in execute return self._execute_with_wrappers(sql, params, many=False, executor=self._execute) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 75, in _execute_with_wrappers return executor(sql, params, many, context) File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, in _execute return … -
What is the most simple solution to run python script in the background in Django
What I need I have a Django project. And it has one python script that need to be run in the background I used supervisor for this. But now I need to add to buttons in the admin: Start. This button should run the script in the background Stop. This button should stop the script Problem What is the best way to run my script in the background. I have read some articles about background jobs in Django. And they say the best way to do it is Celery + Redis. But I think that Celery is to complex for this small task and there should be some other solution, some simple solution Question What is the best simple solution to run and stop my script with 2 buttons in the Django admin? -
Django Update of table doesn't work because of clean method in modelForm
Here is my form class TypeCompteForm(forms.Form): LIBELLES = (("xxxxx","xxxxxxx"),("xxxxxxxx","xxxxxxxxxx")) libelle = forms.ChoiceField(required=True,choices=LIBELLES,error_messages=err_msg,widget=forms.Select(attrs={"class":"form-control","placeholder": "Libellé du type"})) code = forms.CharField(required=True, max_length=50,widget=forms.TextInput(attrs={"class":"form-control","placeholder": "Code de du type"})) def clean_libelle(self): data = self.cleaned_data["libelle"] if TypeMagasin.objects.filter(libelle=data).exists(): raise ValidationError("Un type de magasin avec ce libellé existe déjà !") return data With this form I manage to insert the data in the data base. But when I try to modify one record the clean_libelle method executes. Below is the view I use for updating def updateView(request,id): instance = MyModel.objects.get(pk=id) form = ModelForm(instance=instance) if request.method == "POST": form = ModelForm(request.POST, instance=instance) if form.is_valid(): form.save() else: print(form.errors) return render(request,"template.html") return render(request,"reconciliation/template.html",{"form":form}) -
I would like csv file to update the information in existing field django
I have uploaded csv file through POST method in django but unable to store csv file filed in the existing field. i mean to say already table record in db. username, userpassword, urloc, scode. i would like to check if scode value and positing csv scode value equal then only update the record. views.py if request.method == 'POST': # up = request.FILES.get('uploadfile', '') csv_file = request.FILES.get('uploadfilec', '') print(csv_file) # lets check file is csv or not if not csv_file.name.endswith('.csv'): messages.error(request, 'This is not a csv file') data_set = csv_file.read().decode('UTF-8') # set up a stream which is when we loop through each line we are able to handle a data in stream io_string = io.StringIO(data_set) print(io_string) next(io_string) cy = EmailDb.objects.all() for column in csv.reader(io_string, delimiter=',', quotechar="|"): # pt = EmailDb.objects.all().filter(scode=column[3]).values_list('scode', flat=True) # for i in pt: # print(i) # print('don') # print(pt) for i in cy: co = i.scode print("co",co) print("column",column[3]) if co == column[3]: _, created = EmailDb.objects.all().filter(scode=column[3]).update( useremail = column[0], userpassword = column[1], urloc = column[2], scode = column[3] ) return render(request, 'NEC/crupload.html') -
error 'function' object has no attribute 'objects' when i try to create a record in the model in veiws.py
I want to create a record in the register model immediately after creating user But unfortunately, an error 'function' object has no attribute 'objects' shows me views.py code: from django.shortcuts import render,redirect from .forms import userregister from django.contrib.auth.models import User from testapp.models import register def register(request): if request.method == 'POST': form = userregister(request.POST) if form.is_valid(): cd = form.cleaned_data User.objects.create_user(cd['username'],cd['email'],cd['password']) register.objects.create(address='NONE' , phone = 'NONE' ,username_id= cd['id']) return redirect('testapp:index') else: form = userregister() context = {'form' : form} return render(request,'register.html',context) models.py code from django.db import models from django.contrib.auth.models import User class register(models.Model): address = models.CharField(max_length=200) phone = models.CharField(max_length=11) username = models.OneToOneField(User,on_delete = models.CASCADE) def __str__ (self): return str(self.username) I want to create a record in the register model immediately after the user is added, with the value NONE and the foreign key should be the same user as the one created now. -
Django login authentication always returns none
I am using django contrip auth for authenticate user. Signup function always working and register and login user successfully but after that I m logged out and try to login again but this time login function doesnt work. I add this codes my settings file AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) AUTH_USER_MODEL = 'app.User' My User model seems like that in models.py class User(AbstractUser): pass My Login and Register function def dlogin(request): if request.method=='GET': return render(request, "login.html") if request.method == "POST": username = request.POST['username'] password = request.POST['password'] # Attempt to sign user in user = authenticate(request, username=username, password=password) print(user) # Check if authentication successful if user is not None: login(request, user) cur_user = request.user return render(request,'index.html',{ 'success':'login successful', 'user':cur_user }) else: return render(request,'login.html',{ 'error':'Invalid username and/or password.' }) @csrf_exempt def signup(request): if request.method != "POST": return render(request, 'signup.html') # Get form information username = request.POST["username"] password = request.POST["password"] confirmation = request.POST["confirmation"] # Ensure password matches confirmation if password != confirmation: return render(request,'register.html',{ 'message':'Passwords dont match' }) # Attempt to create new user user = User.objects.create_user(username,password) user.save() login(request, user) return redirect('index') I did some research and couldn't find any problem in my code. Does anyone can help me? -
Page not found After using UpdateView class
I have a project that requires an update form, I am using the Django generic views, specifically the UpdateView. I Think this is an error with the URL, but I dont find where it is. Eror also refers to the url The current path, actualizar_empleado/, didn’t match any of these. My code is the following: Views.py `from django.shortcuts import render, get_object_or_404 from django.views.generic import ( CreateView, DetailView, ListView, UpdateView, ListView, DeleteView ) from . models import EmployeesInfo from . forms import EmployeeForm class EmployeeCreate(CreateView): form_class = EmployeeForm template_name = 'employeeCreate.html' success_url = '/lista_empleados/' def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) class EmployeeList(ListView): model = EmployeesInfo template_name = 'employeeList.html' success_url = 'lista-empleados/exitoso' class EmployeeDetail(DetailView): model = EmployeesInfo template_name = 'employeeDetail.html' success_url = 'detalle-empleado/exitoso' def get_object(self): id_ = self.kwargs.get("pk") return get_object_or_404(EmployeesInfo, pk=id_) class EmployeeUpdate(UpdateView): form_class = EmployeeForm queryset = EmployeesInfo.objects.all() template_name = 'employeeUpdate.html' success_url = '/listaempleados/' def form_valid(self, form): print(form.cleaned_data) return super().form_valid(form) def get_object(self): id_ = self.kwargs.get("pk") return get_object_or_404(EmployeesInfo, pk=id_)` -
After submitting data to server, redirect to specific part of page?
I want to redirect to specific part of page after submitting data to server not to default view of current page instead when I am working on section plan for growth and I am working of this part of page if I submit the data from this part after I submit the data to server I want to be in this section which by default it shows me the introduction section and I don't want this. Is there any solution to this? I want to stay in section plan for growth when I submit the data. -
is there a way for me to merge two Django functions calls?
I'm trying to merge two python functions, with their corresponding AJAX JS requests. So, I have two JS functions that call two different views. I need to merge everything in aa single request to optimise server's trafic. <script> $(document).ready(function() { function imgMarkup(model) { if (model.media) {//mediasrc return `<img class='imgchat' src=${window.location.origin}/static/${model.mediasrc}.png>` } return ''; } function csvMarkup(model) { if (model.excel) { return `<p><a href="${window.location.origin}/static/${model.mediasrc}" class="dl-csv">[Download]</a></p>` } return ''; } function botCheck(model) { if (model.bot) { return 'gpt.jpeg' } return 'user.jpeg'; } setInterval(function() { $.ajax({ type: 'GET', url: "/checkview", success: function go(response) { console.log(response); $("#display").empty(); for (var model of response.models_to_return) { let botclass = model.bot ? 'right' : ''; const temp = ` <div class='chat-c ${botclass}'> <div class=" picture-c"><img src="${window.location.origin}/static/AAA/${botCheck(model)}" class="picture"></div> <div class='chat'> <p class='${botclass} p-chat'>${model.room}</p> ${imgMarkup(model)} ${csvMarkup(model)} </div> </div>`; $("#display").append(temp); $('#screen').css({ 'display': 'none', }); } }, error: function(response) { //alert('An error occured') } }); }, 10000); }) </script> <script> $(document).ready(function() { setInterval(function() { $.ajax({ type: 'GET', url: "/workspace", success: function check(response) { console.log(response); $("#variat").empty(); for (var model of response.memory_return) { const temp = ` <span class='a-items'>${model.date1} : ${model.date2}</span> <span class='a-items'>${model.symbols}</span>`; $("#variat").append(temp); } }, error: function(response) { //alert('An error occured') } }); }, 10000); }) </script> And their corresponding views.py: Python: def … -
Django ORM JOIN of models that are related through JSONField
If I have 2 models related through ForeignKey I can easily get a queryset with both models joined using select_related class Foo(Model): data = IntegerField() bar = ForeignKey('Bar', on_delete=CASCADE) class Bar(Model): data = IntegerField() foos_with_joined_bar = Foo.objects.select_related('bar') for foo in foos_with_joined_bar: print(foo.data, foo.bar.data) # this will not cause extra db queries I want to do the same thing but in the case where Foo keeps it's reference to bar in a JSONField class Foo(Model): data = IntegerField() bar = JSONField() # here can be something like {"bar": 1} where 1 is the ID of Bar class Bar(Model): data = IntegerField() foos_with_joined_bar = ??? Is it possible to get foos_with_joined_bar in this case using Django ORM? P.S. We're not discussing the reasoning behind storing foreign keys in the JSONField, of course it's better to just use ForeignKey. -
What I have to learn Flutter or React Native?
I have learned Django and HTML, CSS, and Bootstrap for web Development but now I want to learn App Development also, I am confused about what I have to choose with Django, whether I have to learn Flutter or React Native or something else give I have knowledge of OOP as well as Front End HTMl CSS and Bootstrap -
ImportError: libstdc++.so.6: cannot open shared object file: No such file or directory
I am trying to deploy my Django project that uses React on the frontend inside Django app to railway. The app was deployed on Heroku before but after adding a whisper package from openAI the slug size became too big to use it there so I opted to use railway instead. I have another Django project with React running there so the problem comes from the packages. The problem comes from package called gpt-index which uses pandas package and that's where the error occurs. What can I do to fix this? Nix-packs setup: [phases.setup] nixPkgs = ['nodejs-16_x', 'npm-8_x ', 'python310', 'postgresql', 'gcc '] [phases.install] cmds = ['npm i ', 'python -m venv /opt/venv && . /opt/venv/bin/activate && pip install -r requirements.txt'] [phases.build] cmds = ['npm run build'] [start] cmd = '. /opt/venv/bin/activate && python manage.py migrate && gunicorn backend.wsgi' Full traceback: Traceback (most recent call last): File "/app/manage.py", line 22, in <module> main() File "/app/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/opt/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/opt/venv/lib/python3.10/site-packages/django/core/management/__init__.py", line 420, in execute django.setup() File "/opt/venv/lib/python3.10/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/opt/venv/lib/python3.10/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/opt/venv/lib/python3.10/site-packages/django/apps/config.py", line 193, in create import_module(entry) File "/nix/store/al6g1zbk8li6p8mcyp0h60d08jaahf8c-python3-3.10.9/lib/python3.10/importlib/__init__.py", line … -
Return all active comment in a post
i have this blog site,i want to return all acvtive comments associated to a post. def post_detail(request,year, month,day, post): post = get_object_or_404(Post,status=Post.Status.PUBLISHED,slug=post,publish__year=year,publish__month=month,publish__day=day) #list of active comments for this post comments = post.comments.filter(active=True) #form for users to comment form = CommentForm() #List of similar posts post_tags_ids = post.tags.values_list('id',flat=True) similar_posts = Post.published.filter(tags__in=post_tags_ids).exclude(id=post.id) [:4] return render(request,'blog/post/detail.html',{'post':post,'comments':comments,'form':form}) Its returning null response, -
I cannot post comment in Django, no error
I'm working on a Django blog and I'm stuck here... I want to post comment and when I do that it just refresh the page and nothing happens. I have no idea where I'm making a mistake, please see my code below: this is views.py def post_detail(request, slug): post = get_object_or_404(Post, slug=slug) related_posts = post.tags.similar_objects()[:3] comments = post.comments.filter(active=True) new_comment = None if request.method == 'POST': if request.user.is_authenticated: comment_form = CommentForm(data=request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) new_comment.post = post new_comment.author = request.user new_comment.save() else: messages.warning(request, 'You need to be logged in to add a comment.') else: if request.user.is_authenticated: comment_form = CommentForm(initial={'author': request.user}) else: comment_form = CommentForm() context = {'post': post, 'related_posts': related_posts, 'comments': comments, 'new_comment': new_comment, 'comment_form': comment_form} return render(request, 'post_detail.html', context) this is comment part post_detail.html {% if user.is_authenticated %} <!--comment form--> <div class="comment-form"> <h3 class="mb-30">Leave a Reply</h3> <form class="form-contact comment_form" action="{% url 'post_detail' post.slug %}" method="post"> {% csrf_token %} <div class="row"> <div class="col-12"> <div class="form-group"> {{ comment_form | crispy }} </div> </div> </div> <div class="form-group"> <button type="submit" class="button button-contactForm">Post Comment</button> </div> </form> </div> {% else %} <div class="alert alert-danger" role="alert"> Please log in to post a comment. </div> {% endif %} this is models.py class Comment(models.Model): post = models.ForeignKey(Post, …