Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pass request.user to dispatch method
Env: Python 3.6, Django 3.0, DRF 3.11, JWT Authorization Hello everybody. I have a simple class in my API where I want to check user permissions in each method get, pass etc. I planned to check user privileges at dispatch but it doesn't work. Simplify code, my current class looks more or less like this: class ExampleClassName(APIView): can_do_sth = False def dispatch(self, request, *args, **kwargs): print(request.user) # Here is AnonymousUser if request.user.username == "GreatGatsby": self.can_do_sth = True return super(ExampleClassName, self).dispatch(request, *args, **kwargs) def get(self, request): print(request.user) # Here is correctly Logged user if self.can_do_sth: return Response("You can do it") return Response("You can't") def post(self, request): print(request.user) # Here is correctly Logged user if self.can_do_sth: return Response("You can do it") return Response("You can't") How can I pass request.user to dispatch method? -
413 Request Entity Too Large - Regular Fix Not Working
I'm deploying a Django application online using AWS Elastic Beanstalk. It worked fine for a while, but some change is causing the application to throw a '413 Request Entity Too Large nginx/1.18.0' error when I try to upload a file. Here are my logs: stdout log: ---------------------------------------- /var/log/web.stdout.log ---------------------------------------- Sep 8 19:59:39 ip-172-31-16-39 web: Bad Request: / Sep 8 21:27:14 ip-172-31-16-39 web: Not Found: /static/tinymce/css/prism.css Sep 8 21:27:14 ip-172-31-16-39 web: Not Found: /static/tinymce/js/prism.js Sep 8 21:27:14 ip-172-31-16-39 web: Not Found: /favicon.ico Sep 8 21:27:16 ip-172-31-16-39 web: Not Found: /static/tinymce/css/prism.css Sep 8 21:27:16 ip-172-31-16-39 web: Not Found: /static/tinymce/js/prism.js access log: ---------------------------------------- /var/log/nginx/access.log ---------------------------------------- 192.241.237.101 - - [07/Sep/2020:09:35:44 +0000] "GET /hudson HTTP/1.1" 400 59666 "-" "Mozilla/5.0 zgrab/0.x" "-" 3.134.93.214 - - [07/Sep/2020:10:07:18 +0000] "HEAD /robots.txt HTTP/1.0" 404 0 "-" "-" "-" 189.39.247.131 - - [07/Sep/2020:11:25:33 +0000] "GET / HTTP/1.1" 400 59689 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_11_6) AppleWebKit/601.7.7 (KHTML, like Gecko) Version/9.1.2 Safari/601.7.7" "-" 195.54.160.21 - - [07/Sep/2020:12:20:29 +0000] "GET /solr/admin/info/system?wt=json HTTP/1.1" 400 60308 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 Safari/537.36" "-" 195.54.160.21 - - [07/Sep/2020:12:21:47 +0000] "GET /?XDEBUG_SESSION_START=phpstorm HTTP/1.1" 400 60242 "-" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/78.0.3904.108 … -
How do I return custom response/status code in Django?
I want to return status code different from 100 <= self.status_code <= 599, as written in Django's HttpResponseBase class. Is there are any easy way to bypass this restriction? -
Django: Use JSON and requests in my django app
I am using JSON, re and requests to get the number of followers from an instagram page: import json import re import requests PROFILE = 'espn' response = requests.get('https://www.instagram.com/' + PROFILE) json_match = re.search(r'window\._sharedData = (.*);</script>', response.text) profile_json = json.loads(json_match.group(1))['entry_data']['ProfilePage'][0]['graphql']['user'] print(profile_json['edge_followed_by']['count']) I am wondering how I can then add this to my django project to use that number to display on my website, updating each time someone vists the page to reflect the dynamic number. I had a look around but I dont really understand where you would add this code. I would image it would be added in the views section to then be rendered in the html page but not sure what the format would be. The view for the page I would like it to be used for example is View.py: def index(request): post = Post.objects.all()[0] recent_posts = Post.objects.all()[1:4] latest_posts = Post.objects.all()[:5] data = {"post":post, "recent_posts":recent_posts, "latest_posts":latest_posts} return render(request, 'index.html', data) Also as an extra question - how would the process differ if I was using a Generic Class-Based view vs a function view. Thank you very much. -
columns from django.db.models.query.QuerySet
With a raw query the columns for the SQL that will be executed can be accessed like this. query_set = Model.objects.raw('select * from table) query_set.columns There is no columns attribute for django.db.models.query.QuerySet. How do you get the columns or the SQL that will be executed from a django.db.models.query.QuerySet instance? -
Django 3. Having trouble passing dropdown menu selection from .html to forms
I'm still new to Django (2 weeks or so). I've been struggling the past few days with passing a string from an html file to forms. My project lets the user choose a state from a dropdown menu (Michigan and Ohio for now, I'll add the rest later). When the state is selected, it will take that string and pull a list of counties of that state from a spreadsheet. This is where the problem lies. I've searched far and wide and I just can't seem to find a solution. The major holdback to many of these solutions is I don't want to "submit" with a button. I want the user to "select" a state, then select a county without a page refresh. I've also included a screenshot of the webpage. So far the dependent dropdowns work perfectly thanks to a youtube tutorial. The "submit" button in the picture is cosmetic for now. Thanks in advance for helping out. Let me know if you have any questions regarding models or anything else regarding the code. views.py def StateForm_Page(request): context = {} stateChoice = 'Michigan' //hardcode a state so if the post fails, the function can still find an excel sheet … -
Django - How do I get the files submitted to a form?
In my Django project, I have this view: def create_format(request, **kwargs): if request.method == 'POST': form = FormatUpdateForm(request.POST) if form.is_valid(): business_type = int(request.POST.get('business_type')) ... more fields ... constitutive_act_copy = clean_str(request.POST.get('constitutive_act_copy')) return HttpResponseRedirect(reverse('formats:formats')) elif request.method == 'GET': form = FormatUpdateForm() return render(request, 'format_form.html', context={'form': form, 'autocomplete': SearchableData.objects.all()}) I have many fields, some of which are FileFields. I want to create an object with the data obtained from the form, and I can do that for all fields except the FileFields. What is the correct way to obtain the Files uploaded in the form and use them as attributes when creating an object? -
How to keep a modal open in an if statement in template
<div class="modal fade" id="exampleModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">Order Completed</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> {% if accepted_order %} <div class="collapse" id="collapseAcceptedCreatorOrders"> <div class="card card-body"> <h1>Buyer: <a href="{% url 'buyer_page'%}">{{ accepted_order }}</a></h1> <a href="{% url 'dashboard' %}"> <button type="button" class="btn btn-primary" data-toggle="modal" data-target="#exampleModal"> Mark As Bought </button> </a> <a href="{% url 'dashboard_withdraw_order' %}"><button>Withdraw</button></a> </div> </div> {% endif %} I am trying to show a modal when a user clicks a button, inside this if statement. The only issue is when the button is clicked, the modal pops up for a split second and then disappears. When I use the button outside of the if statement it works fine, but I need to use it in the if statement. How can I do this? Thanks. -
Django command line logging on AWS elastic beanstalk
I have deployed a django web app to AWS via elastic beanstalk, and am having trouble finding relevant logs. Where can I find logs that would have the same content as if I was running "python manage.py runserver" locally in my terminal. Thanks! -
Django-import save the file used to upload data
I am new to django and looking for help to save file used to import data in django. In django admin interface, under booksmanagement i am able to upload csv file and data is uploaded into booksmanagement table. But i need help to save the uploaded file into FileImported Trying to store the uploaded file, books.csv to file field under FileImported table. I am doing this first time, may be i am not passing the rite attribute to obj = kwargs['file_name']. Any help will be appreciated. Thank you ! import_export_books.py class Resourcebooks(resources.ModelResource): def get_instance(self, instance_loader, row): try: params = {} for key in instance_loader.resource.get_import_id_fields(): field = instance_loader.resource.fields[key] params[field.attribute] = field.clean(row) return self.get_queryset().get(**params) except Exception: return None def before_import(self, dataset, *args, **kwargs): #for i, v in kwargs.items(): # print (" ", i, ": ", v) #output = file_name : books.csv user : test obj = kwargs['file_name'] print(obj) file_name = kwargs.get('file_name', 'unknown') name = os.path.splitext(file_name)[0] file_size = kwargs.get('file_size', '0') file_extension = kwargs.get('file_extension', 'unknown') user = kwargs.get('user', 'unknown') file_name_model_object = FileImported.objects.get_or_create(file=obj,filename=file_name, name=name, size=file_size, extension=file_extension, user=user) models.py class FileImported(models.Model): filename = models.CharField(max_length=30) name = models.CharField(max_length=30) size = models.FloatField(default="1") extension = models.CharField(max_length=30) date = models.DateField(auto_now_add=True) time = models.TimeField(auto_now_add=True) timestamp = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(Cuser, on_delete=models.CASCADE) … -
How can resolve problem between models.py?
I have a problem with a model and its table in Django. It is possible that for some installed applications I use one type of model and for another I use another model, since when I change the table it gives me this error: (1146, "Table 'dsa_dj.lab_sampletests' doesn't exist") I change the table again, this error goes away, but if I do another action it throws me the following: (1146, "Table 'dsa_dj.lab_sample_tests' doesn't exist") How can I solve this problem between Models? From already thank you very much -
Architecture suggestions - How to implement autoscaled async tasks
We have a large application, which uses django as an ORM, and celery as a task running infrastructure. We run complex pipelines triggered by events (user driven or automatic), which look something like this: def pipeline_a: # all lines are synchronous, so second line must happen after first is finished successfully first_res = a1() all_results = in_parallel.do(a2, a3, a4) a5(first_res, all_results) We wish to run a1, a2, ... on different machines (each task may need different resources), and the number of parallel running pipelines is always changing. Today we use celery which is super convenient for implementing the above - but isn't suitable for auto-scaling (we hacked it to work with kubernetes, but it doesn't have native support with it). Mainly the issues I want to solve are: How to "run the next pipeline step" only after all previous ones are done (I may not know in advance which steps will be run - it depends on the results of previous steps, so the steps are dynamic in nature) Today we try and use kubernetes (EKS) to autoscale some of the tasks (SQS queue size is the hpa metric). How to make kubernetes not try and terminate currently running tasks, … -
Django select options value getting empty value with original values
how can i define select option in html using django tags for loops. i am getting empty values with for loop values. how can i solve this bug? create.html <select class="form-control" name="books" required="" id="id_books"> {% for book in form.books %} <option value="{{ book.id }}">{{ book }}</option> {% endfor %} </select> output.html <select class="form-control" name="books" required="" id="id_books"> <option value=""></option> <option value="1">django</option> <option value=""></option> <option value="2">python</option> <option value=""></option> <option value="3">java</option> <option value=""></option> <option value="4">reactjs</option> </select> -
Avoiding N+1 Queries When Serializing Model With Property Referencing Reverse Foreign Key Relationship
I currently have an issue where neither Django's prefetch_related() nor prefetch_related_objects() are sufficient in optimizing a Django Rest Framework serialization and I'm curious if anyone here has some ideas! To visualize the situation I'm in, suppose I have three models, linked as such: class VotableObjectExampleParent(models.Model): #several other fields redacted here# class VotableObjectExample(models.Model): #several other fields redacted here# votableobjectexampleparent = models.ForeignKey('VotableObjectExampleParent', on_delete=models.CASCADE, related_name = 'votableobjectexamples') @property def total_votes(self): return self.votableobjectexample_votes.aggregate(sum = Sum("vote"))["sum"] or 0 class VotableObjectExample_Vote(models.Model): #several other fields redacted here# votablebjectexample = models.ForeignKey('VotableObjectExample', on_delete=models.CASCADE, related_name = 'votablebjectexample_votes') vote = models.IntegerField(choices = [(-1, "down"), (1, "up")]) I then have appropriate (and functional!) DRF serializers such as the ones shown: class VotableObjectExampleParent_Serializer(serializers.ModelSerializer): related_votableobjectexamples = Idea_Proposal_Serializer(source = "votableobjectexamples", many=True, read_only=True) class Meta: model = VotableObjectExampleParent fields = ['related_votableobjectexamples'] #other fields would normally be in this array read_only_fields = fields class VotableObjectExample_Serializer(serializers.ModelSerializer): class Meta: model = VotableObjectExample fields = ['total_votes'] #other fields would normally be in this array read_only_fields = fields At first, I would simply call the parent serializer (VotableObjectExampleParent_Serializer) in the view: #assume a variable I already have called this_pk is correct and available for use serializer = VotableObjectExampleParent_Serializer(VotableObjectExampleParent.objects.get(pk = this_pk), many = True) JSONRenderer().render(serializer.data) This produces 100% correct JSON for my … -
virtualenv or venv? which one should be used?
I am a windows 10 user. Usually I use $-- python -m venv venv_name to create a virtual environment and activate it by venv_name\Scripts\activate.bat. But today when I did the same, I saw there wasn't any Scripts folder rather a bin folder. So I tried this commands -> $-- venv_name\bin\activate.bat $-- venv_name\bin\activate $-- venv_name\bin\activate.ps1 $-- source venv_name\bin\activate but none of them worked. What was wrong actually and why there wasn't any Scripts folder? -
Date on which maximum number of tasks were completed in a single day django
I have 2 models like this. one user can have multiple tasks class User(models.Model): userCreated_at=models.DateTimeField(blank=True) class Tasks(models.Model): owner=models.ForeignKey(User , on_delete=models.CASCADE) title = models.CharField(max_length=100,null=True,blank=True) completion_date_time = models.DateTimeField(blank=True) So I want to calculate . Since time of account creation of user , on what date, maximum number of tasks were completed in a single day . Any help would be highly appericiated -
How to link "Searchbar" to Search view Django
I create a post_searchview : def post_search(request): form = SearchForm() query = None results = [] if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] search_vector = SearchVector('title', 'body') search_query = SearchQuery(query) results = Post.published.annotate( search=search_vector, rank=SearchRank(search_vector, search_query), ).filter(search=search_query).order_by('-rank') context = {'form': form, 'query': query, 'results': results} return render(request, 'blog/post/search.html', context) And i want to link that to my base.html where i have located an html code for the searchbar (look in the bottom of the file): <body> <nav class="navbar navbar-expand-md navbar-dark bg-dark mb-4"> <a class="navbar-brand" href="{% url 'blog:post_list' %}"> My Blog</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarCollapse" aria-controls="navbarCollapse" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span></button> <div class="collapse navbar-collapse" id="navbarCollapse"> <ul class="navbar-nav ml-auto"> <li class="nav-item mr-2"> <input class="form-control" type="text" placeholder="Search" aria-label="Search"> </li> Also, now i have a search.html file to make the searchs, idk if i should delete it : {% extends "blog/base.html" %} {% block title %}Search{% endblock %} {% block content %} {% if query %} <h1>Posts containing "{{ query }}"</h1> <h3> {% with results.count as total_results %} Found {{ total_results }} result{{ total_results|pluralize }} {% endwith %} </h3> {% for post in results %} <h4><a href="{{ post.get_absolute_url }}">{{ post.title }}</a></h4> {{ post.body|safe|truncatewords_html:5 }} {% empty %} <p>There … -
I am new to django , my code is working fine in local server , but when deployed on heroku , its showing the following error
Exception Type: ProgrammingError at / Exception Value: relation "main_tutorial" does not exist LINE 1: ...ntent", "main_tutorial"."tutorial_published" FROM "main_tuto. -
How to handle external API tokens after logout
This is a higher level conceptual question. I use token authentication on my django - react app and I handle the token by saving, retrieving it, and removing it from local storage as necessary. The flow is sort of like this: user registers- generate token and save it to local storage user logs in - same thing user logs out - token is destroyed and removed from local storage The external API I use also uses token authentication, however I would like to treat it differently as to enhance the user experience. I do not want (aka it is not correct) to generate a new token for the external api every time the user logs in. Upon logging in I would like to retrieve the previously generated token from somewhere, preferably local storage. Saving a token like this in local storage when the user is not logged in is also bad practice. Where is a good place to save this token? Right away I think my django server. However, I feel like it is overkill to generate a whole model for it, or even to create a new attribute for my user, since I would have to create a custom … -
Not able to update a model with image field, with out passing an image file with dango rest framework
Using partial_update,trying to update the model with an image field, without giving an image file, no matter how much I try, I end up with this error. 'memoryview' object has no attribute '_committed' models.py class mymodel(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=200) image_file = models.ImageField(max_length=255, upload_to=/images/id, blank=True, null=True) is_production_ready = models.BooleanField(blank=True, null=True) Serializers.py class imageSerializer(serializers.ModelSerializer): class Meta: model = mymodel fields = '__all__' depth = 1 API.py class imageViewSet(viewsets.ModelViewSet): queryset = mymodel.objects.all() permission_classes = [permissions.AllowAny] serializer_class = imageSerializer parser_classes = ( MultiPartParser, FormParser, FileUploadParser, ) def partial_update(self, request, pk=None): ---instance = self.get_object() data = {} data['id'] = request.data['id'] data['is_production_ready'] = request.data['is_production_ready'] ---data['image_file'] = instance.image_file serializer = imageSerializer(instance, data=data, partial=partial) if serializer.is_valid(): print("serializer is valid...") print("serializer :: ", serializer) serializer.save() return JsonResponse(serializer.data, status=201) return JsonResponse(serializer.errors, status=400) -
psycopg2 installation Error in virtualenv(django_project)
Building a simple blog project with django Problem happened when deployment part. Help me to get rid of this situation advance Tnx Collecting psycopg2 Using cached psycopg2-2.8.6.tar.gz (383 kB) Building wheels for collected packages: psycopg2 Building wheel for psycopg2 (setup.py) ... error ERROR: Command errored out with exit status 1: command: '/home/sium/Documents/django/sample (another copy)/bin/python' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-reak32wu/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-reak32wu/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-onebo_jx cwd: /tmp/pip-install-reak32wu/psycopg2/ Complete output (40 lines): running bdist_wheel running build running build_py creating build creating build/lib.linux-x86_64-3.8 creating build/lib.linux-x86_64-3.8/psycopg2 copying lib/errorcodes.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/__init__.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_ipaddress.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/errors.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/extras.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/tz.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_range.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/extensions.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_json.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/_lru_cache.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/compat.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/sql.py -> build/lib.linux-x86_64-3.8/psycopg2 copying lib/pool.py -> build/lib.linux-x86_64-3.8/psycopg2 running build_ext building 'psycopg2._psycopg' extension creating build/temp.linux-x86_64-3.8 creating build/temp.linux-x86_64-3.8/psycopg 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 -DPSYCOPG_VERSION=2.8.6 (dt dec pq3 ext lo64) -DPG_VERSION_NUM=120004 -DHAVE_LO64=1 -I/home/sium/Documents/django/sample (another copy)/include -I/usr/include/python3.8 -I. -I/usr/include/postgresql -I/usr/include/postgresql/12/server -c psycopg/psycopgmodule.c -o build/temp.linux-x86_64-3.8/psycopg/psycopgmodule.o -Wdeclaration-after-statement In file included from psycopg/psycopgmodule.c:28: ./psycopg/psycopg.h:36:10: … -
ModuleNotFoundError: No module named 'account.apps.AccountConfigdjango'; 'account.apps' is not a package
from django.apps import AppConfig class AccountConfig(AppConfig): name = 'account' As a whole, I have two files the code above is from apps.py, but it does not work. What and where do I have to import the file apps.py to make my code run? -
Why is Django not displaying all attributes of an object?
I have the problem that I have a model with two fields, but only one is shown in the output. I have this code in my views.py class Update_Org(UpdateView): model = OrgKlass form_class = form_update_org template_name = templ_folder_name + 'update_org.html' success_url = reverse_lazy(url_app_name + 'list_org') def get_object(self, queryset=None): self.queryset = OrgKlass.objects.get(id = self.to_update) return self.queryset def post(self, request, pk): if self.request.POST.get('action', False) == 'update': self.to_update = pk self.object = self.get_object() print(self.object.ok_beschreibung) return super(Update_Org, self).post(request, pk) else: pass # because I do not need that right now The form looks like this: class form_update_org(forms.ModelForm): ok_bezeichnung = forms.CharField(required=True, label="Org-Bezeichnung", widget=forms.TextInput(attrs={'class':'form-control',})) ok_beschreibung = forms.CharField(required=False, label="Beschreibung des Tätigkeitsfeldes des Bereichs", widget=forms.Textarea(attrs={'class':'form-control',})) class Meta: model = OrgKlass fields = ('ok_bezeichnung', 'ok_beschreibung') And this is part of the html template: {% block content %} {% for label, value in object.get_fields %} label: {{label}}<br> value: {{value}}<br> {% endfor %} {% endblock %} The output however looks like this: label: ID value: 9 label: Org-Bezeichnung value: Company A label: Beschreibung des Tätigkeitsfeldes value: However, if you look at the print statement in the def post part, then this prints correctly the value of the ok_beschreibung field. Do you have any idea what is the problem with the html … -
best way to compare querysets against a queryset
Hello guys I have this problem I have been avoiding to post it here now I am back begging the god of stackoverflow; I have a queryset that I want to compare with querysets. say I have queryset like this: x = Thing.objects.get(user=request.user).thing_response.all() Then I have querysets that fetches every "Thing" and related response like this all = Things.objects.all() i = [x.id for x in all.thing_response.all()] I have built a list of ids with x and i now I want to get an exact match of i in x: it works for small data, but when data grows matching stops i use set for matching: if set(x) == set(i) in a loop but it doesn't work when the data gets large is there a better way to accomplish this? -
Why Django Is Not Accepting Data From A Form Even Data Is Valid? Django-python
I am Working With Modals And Forms In Django I Created A Comment Modal For My Post Modal I Used A ForeignKey To Associate My Comments With Posts, It Works All Fine By Manually Adding Comments To Posts From Admin Sections Of My Webpage, But As Soon As I Try To Do The Same Thing Using A Front-End Represtantion Of My Form So That User Could Add Comments To Posts, It Doesn't Work As Expected And I Am Also Unable To Automatically Associate My Posts With My Comments, I Have Been Changing The Things Form 2 Days Now And Still The Result Is Still Same. Can Anyone Help Me :{ This Is How My Modal Look Like: class Comment(models.Model): post = models.ForeignKey(Article, on_delete=models.CASCADE, related_name='comments') author = models.CharField(max_length=200) text = RichTextField() created_date = models.DateTimeField(auto_now_add= True) active = models.BooleanField(default=False) The Form: class CommentForm(forms.ModelForm): class Meta: model = models.Comment fields = ['author', 'text'] And This My View in Views.py: def article_detail(request, slug): article = Article.objects.get(slug = slug) articles = Article.objects.all() comment_form = CommentForm() post = get_object_or_404(Article, slug=slug) comments = post.comments.filter(active=True) if request.method == 'POST': form = forms.CreateArticle(request.POST, request.FILES) if form.is_valid(): # Create Comment object but don't save to database syet new_comment = form.save() …