Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Custom CSRF Failure View: Referer checking failed - no Referer
I've overridden the Django CSRF_FAILURE_VIEW with the following: def csrf_failure(request, reason="Failed login due to CSRF error"): logger.warning(reason) return render(request, 'csrf_failure.html') However, I've started noticing the following warning since implementing this: Referer checking failed - no Referer It seems like it is trying to show the custom error template when there is a CSRF forbidden error, but there is no referrer. What should I be doing to remove resolve this? -
How to prefetch_related GenericForeignKey with self reference ForeignKey in restframwork
I am going mad with restframework because of the N+1 problem. For example, I have following models: class User(models.Model): username = ... email = ... avatar = ... last_login = ... class Article(models.Model): user = models.ForeignKey(User) title = ... abstract = ... content = ... category = ... class Comment(models.Model): user = models.ForeignKey(User) article = models.ForeignKey(Article) content = ... ## This field! ## reply_to = models.ForeignKey('self', null=True) time = ... That is, user can comment an article or a comment of an article. And now I need to build a notification system, so I add: class Notification(models.Model): actor_type = models.ForeignKey( ContentType, related_name='notify_actor', on_delete=models.CASCADE) actor_id = models.PositiveIntegerField() actor = GenericForeignKey('actor_type', 'actor_id') verb = models.CharField(max_length=255) receiver = models.ForeignKey( User, on_delete=models.CASCADE, related_name='notifications') is_read = models.BooleanField(default=False, db_index=True) target_type = models.ForeignKey( ContentType, related_name='notify_target', blank=True, null=True, on_delete=models.CASCADE ) target_id = models.PositiveIntegerField() target = GenericForeignKey('target_type', 'target_id') time = models.DateTimeField(auto_now_add=True) source_type = models.ForeignKey( ContentType, blank=True, null=True, related_name='notify_subject_object', on_delete=models.CASCADE ) source_id = models.PositiveIntegerField() source = GenericForeignKey('source_type', 'source_id') The notification looks like: Yriuns commented Article 1: good job <actor> <verb> <target> <source> or: Yriuns commented Your Comment of Article 1: I doubt it <actor> <verb> <target> <source> And the serializers: class UserSeriazlier(serializers.ModelSerializer): class Meta: model = User fields = ('username', β¦ -
Invalid email in Django Password Reset
I am implementing Django Password Reset to send a recovery password link when the user type his/her email id using django.contrib.auth.urls, which works as perfectly. This is from Django Documentation, If the email address provided does not exist in the system, the user is inactive, or has an unusable password, the user will still be redirected to this view but no email will be sent. My question is, If I add something like EmailValidation to check if the user typed email exists in the database or not and raise ValidationError, will that be a security problem? -
Extending the Django User Model OneToOne - User profile not saving
I am trying to build an application that allows users to register and meet other users with similar interests. I am extending the user model using a OneToOne field but I run into a problem when I try to register some users: The profile does not save. The user data saves, but the profile data does not. I do not understand what I am doing wrong, as I followed a tutorial to write the program. This is my Models.py file: class Profile(models.Model): GENDERS = ( ('M', 'Male'), ('F', 'Female'), ) user = models.OneToOneField(User, on_delete=models.CASCADE) email = models.EmailField(max_length=254, blank=True) gender = models.CharField(choices=GENDERS, max_length=1, null=True, default='') dob = models.DateField(auto_now=False, auto_now_add=False, blank=True, null=True) hobby = models.ManyToManyField(Hobby) def __str__(self): return self.user.username @receiver(post_save, sender=User) def create_user_profile(sender, instance, created, **kwargs): if created: Profile.objects.create(user=instance) @receiver(post_save, sender=User) def save_user_profile(sender, instance, **kwargs): instance.profile.save() post_save.connect(create_user_profile, sender=User) This is my forms.py file: class UserForm(forms.ModelForm): class Meta: model = User fields = ('username', 'password', 'first_name', 'last_name') class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('email', 'gender', 'dob', 'hobby') This is my view function: def register(request): if request.method =="POST": userForm = UserForm(request.POST) profileForm = ProfileForm(request.POST) if userForm.is_valid() and profileForm.is_valid(): userForm.save() profileForm.save() return redirect('/') else: return render(request, 'QMLove/register.html', {'userForm': userForm, 'profileForm': profileForm}) else: β¦ -
implementing video streaming with django
I am trying to implement this project using django. What I want to do is once the server is started, I should be able to start the camera from any system that is connected to network and display the feed in that system. I am using Django because I have written other modules of my project with django This is my code so far views.py def index(request): return render(request, 'index.html') # the gen() is part of the server.py code. This has to be added to the start_server() function. # the start_server() function should be rectified def gen(): streamer = Streamer('localhost', 8000) streamer.start() while True: if streamer.client_connected(): yield (b'--frame\r\n'b'Content-Type: image/jpeg\r\n\r\n' + streamer.get_jpeg() + b'\r\n\r\n') def start_server(request): return render_to_response(gen(), mimetype='multipart/x-mixed-replace; boundary=frame') def start_client(request): cap = cv2.VideoCapture(0) clientsocket=socket.socket(socket.AF_INET,socket.SOCK_STREAM) clientsocket.connect(('localhost',8000)) while(cap.isOpened()): ret,frame=cap.read() memfile = StringIO() np.save(memfile, frame) memfile.seek(0) data = json.dumps(memfile.read().decode('latin-1')) clientsocket.sendall(struct.pack("L", len(data))+data) if cv2.waitKey(1) & 0xFF == ord('q'): break cv2.imshow('frame', frame) cap.release() The client.py file from the repo is placed under start_client() function in views.py I have made a small change to the client.py file from the repo. I added cv2.imshow('frame', frame) to display the feed in the client's system index.html <html> <head> </head> <body> <div class='container'> <a href='/start_server'><button>Start Server</button></a> <a href='/start_client'><button>Start Client</button></a> β¦ -
Create Activity Logs in Django Social Auth Login
I want to trace login/logout Logs for Students.How to trace if student login through Social Auth? -
reading json getting null values using jquery django python
Here is the template and the sample file : <html> {% load static %} <head> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script> $.getJSON("{% static "logging/log0.json" %}", function (data) { <!-- $.each(data, function (index, value) { --> <!-- console.log(value); --> <!-- }); --> console.log(data) }); </script> </head> <body> Hello </body> </html> To get the sample file click. The output when I see the console log I get the following: The highlighted part is missing in the output. The json file has values for that. But the reading is not showing the output. Please help. -
django Edit records in Listview
I have a ListView that lists all questions from the Question model. the models.py is: class Question(models.Model): question_text = models.CharField(max_length=200, unique=True) pub_date = models.DateField(verbose_name='date published') def __str__(self): return self.question_text now I want users can edit question_text. I tried this in views.py: class UpdateDirectry(generic.list.ListView, generic.edit.FormMixin): model = Question template_name = 'accounts/editable_directory.html' form_class = forms.EditListForm def get_context_data(self, *, object_list=None, **kwargs): context = super(UpdateDirectry, self).get_context_data() context['object_list'] = Question.objects.filter(question_text__startswith='Who') return context and in the template: <form method="post"> {% csrf_token %} <table class="table"> <thead> <tr> <th scope="col">#</th> <th scope="col">Q</th> <th scope="col">D</th> </tr> </thead> <tbody> {% for object in object_list %} <tr> <th scope="row">{{ forloop.counter }}</th> <td><input type="text" value="{{ object.question_text }}"></td> <td>{{ object.pub_date }}</td> </tr> {% endfor %} </tbody> </table> <input type="submit" value="Submit"> </form> I can edit the question_text but when I click submit button nothing happens (just a white page) and no records change in the database. How can I really edit records with the submit button? This is what the template shows: enter image description here -
Django: Validate GET parameter
I offer discount codes in my checkout. I created form where users can type in the discount code and click on apply. The form checks if the discount code is valid and then applies it. Now I want to add the functionality to add to the url domain.com/event/?discount=ABC I want to check if request.GET is set an then somehow redirect it to the 'form' / transform it into a request.POST, so I can validate it. I am currently struggling to find the right approach to do that. Do you have any suggestions on how I could use the GET-parameter and validate it the same way as I would use the form? views.py def dispatch(self, request, *args, **kwargs): # Provide discount_code to all functions self.discount_code = None # Check if discount code is saved as a session self.discount_code_session = request.session.get( request.event.discount_code_cookie(), None) if self.discount_code_session: self.discount_code = Discount.objects.filter( code=self.discount_code_session, event=self.request.event.pk ).first() @transaction.atomic def post(self, request, *args, **kwargs): # Discount Code if self.discount_form.is_valid(): discount_code = self.discount_form.cleaned_data['code'] request.session[request.event.discount_code_cookie()] = discount_code return redirect('events:detail', request.organizer.slug, request.event.slug) forms.py class DiscountFormEventPage(forms.ModelForm): # Remove required attribute from HTML elements use_required_attribute = False class Meta: model = Discount fields = ( 'code', ) def __init__(self, *args, **kwargs): self.event = kwargs.pop('event') β¦ -
Django CSS is displayed different on local and production environment
Edit Form is not editable on production and the image button in the left, while on development it is editable and image button on the right. What could be the issue? The code is exactly the same. Checked on Chrome, IE and Firefox - same issue Cleaned cache - didn't help. -
Should my soft-deletion-honouring model manager be my model's default manager?
I am building soft-deletion functionality for my Django project. I have implemented this using a custom model manager (i.e. performing an initial filter on get_queryset(), plus overriding Model / Manager / QuerySet delete(). Django documentation (1.11): If you use custom Manager objects, take note that the first Manager Django encounters (in the order in which theyβre defined in the model) has a special status. Django interprets the first Manager defined in a class as the βdefaultβ Manager, and several parts of Django (including dumpdata) will use that Manager exclusively for that model. As a result, itβs a good idea to be careful in your choice of default manager in order to avoid a situation where overriding get_queryset() results in an inability to retrieve objects youβd like to work with. My soft delete-honouring manager is currently my model's default manager (first manager declared on the model class). It's also assigned to objects. This is convenient for me as a lot of Django code uses the default model manager (e.g. MultipleObjectMixin.get_queryset() if your MultipleObjectMixin-inheriting View just has the model attribute defined). However the fact that dumpdata also uses the custom model manager has scared me off. In the event that I perform β¦ -
django application giving 404 error while reading json file python
Here is the code: views.py: @csrf_exempt def post_list(request): return render(request, 'blog/post_list.html', {}) @csrf_exempt def show(request): return render(request, 'tt/readjson.html', {}) urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.post_list), path('test/', views.data_return), path('tt/', views.show), ] readjson.html: <html> <head> <script src="https://code.jquery.com/jquery-1.10.2.js"></script> <script> $.getJSON("log0.json", function (data) { $.each(data, function (index, value) { console.log(value); }); }); </script> </head> <body> Hello </body> </html> The output I am getting is hello on the screen. But in the console log I see this: jquery-1.10.2.js:8706 GET http://127.0.0.1:8000/tt/log0.json 404 (Not Found) send @ jquery-1.10.2.js:8706 ajax @ jquery-1.10.2.js:8136 jQuery.(anonymous function) @ jquery-1.10.2.js:8282 getJSON @ jquery-1.10.2.js:8265 (anonymous) @ (index):5 jquery-1.10.2.js:8706 XHR failed loading: GET "http://127.0.0.1:8000/tt/log0.json". The json file is in the same folder where the html template is kept, that is in the tt folder. Please let me know what might I do to avoid the missing part. -
How to filter and all the categories in a single statement using django
I have prog, associateprof, assistantprof, research scholar and mtech categories and to get count of those I am using each statement for each. Instead is there any chance to know in a single statement or using for loop. I am doing like this : count= Snippet.objects.all().count() count1 = Snippet.objects.filter(designation = 'Prof').count() count2 = Snippet.objects.filter(designation = 'RA').count() count3 = Snippet.objects.filter(designation = 'MTech').count() count4 = Snippet.objects.filter(designation = 'Asstprof').count() count5 = Snippet.objects.filter(designation = 'Assocprof').count() -
how to create a django model form that will dyanamically render fileds by counting specific models atrribute
I am new to Django, I want to create a model and a model forms where it has three field tow of them are specified and one of them will create dynamically. This dynamic filed can be multiple inputs filed(integer).Further understand you can see this video. My Code For This models.py class SubjectCombination(models.Model): get_class_name = models.CharField(max_length=20) get_subject_name = models.CharField(max_length=20) class Result(models.Model): class_name = models.CharField(max_length=20) student_name = models.CharField(max_length=20) marks = # here i want to get dyanamic filed for all subjects in SubjectCombination model. forms.py class SubjectCombinationForm(forms.ModelForm): class Meta: model = SubjectCombination fields = '__all__' class ResultForm(forms.ModelForm): class_name = forms.CharField(required=True) student_name = forms.CharField(required=True) marks = # What Shoud i write here ? views.py def add_result(request): sbjcmb = SubjectCombination.objects.order_by('id') students = Student.objects.order_by('id') if request.method == 'POST': resultForm = ResultForm(request.POST) for data in resultForm: print(data) else: resultForm = ResultForm context = {'subcom':sbjcmb, 'students':students, 'form':resultForm} return render(request, 'add-result.html', context) HTML Template <form class="form-horizontal" method="post"> {% csrf_token %} {{ form.non_field_errors }} <div class="form-group"> <label for="{{ form.class_name.id_for_label }}" class="col-sm-2 control-label">Class</label> <div class="col-sm-10"> <select name="{{ form.class_name.name }}" class="form-control clid" id="{{ form.class_name.id_for_input }}" onChange="getStudent(this.value);" required="required" > <option value="">Select Class</option> {% for class in subcom %} <option value="{{ class.get_class_name }}">{{ class.get_class_name }}</option> {% endfor %} </select> </div> </div> <div β¦ -
Celery/Django is running task trying to run when timezone has been set
I am running into the issue that, when using a timezone inside my celery.py tasks run every chance it gets, thus running not according to schedule. This is the output: scheduler_1 | [2018-11-29 11:00:09,186: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,199: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,204: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,210: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,220: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,228: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,231: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,236: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,239: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,247: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) scheduler_1 | [2018-11-29 11:00:09,250: INFO/MainProcess] Scheduler: Sending due task Suppliers (biko.supplier.tasks.pull_supplier_data) My celery.py: import os from celery import Celery from celery.schedules import crontab from django.conf import settings os.environ.setdefault("DJANGO_SETTINGS_MODULE", "config.settings") # app = Celery('biko') task_apps = [ 'biko.supplier.tasks', 'biko.common.tasks', 'biko.commerce.tasks', 'biko.shop.tasks' ] app = Celery('biko', include=task_apps) app.config_from_object('django.conf:settings') app.conf.timezone = 'Europe/Amsterdam' app.autodiscover_tasks() app.conf.ONCE = { 'backend': 'celery_once.backends.Redis', 'settings': { 'url': 'redis://' + β¦ -
Configure IIS to Serve Django Applications
I'm trying to publish a Django web application (created with Python 2.7.15) via IIS. First of all I installed the application: :: setup folders mkdir C:\Software\MyApp\ cd C:\Software\MyApp\ :: clone the git Repository git clone https://gitlab.com/blablabla.git C:\Software\MyApp\MyAppServer :: create the virtualenv python -m pip install --upgrade pip pip install virtualenv virtualenv py2_env call py2_env\Scripts\activate.bat :: install the python-requirements in the virtualenv pip install -r C:\Software\MyApp\MyAppServer\requirements.txt :: copy all static files in C:\var\www python C:\Software\MyApp\MyAppServer\manage.py collectstatic :: just to check if the app works (and it works!) python C:\Software\MyApp\MyAppServer\manage.py runserver At this point, my folders organization is: C:\ βββ Software\ βββ MyApp\ βββ py2_env\ β βββ Include\ β βββ Lib\ β βββ Scripts\ β βββ tcl\ βββ MyAppServer\ βββ manage.py βββ ... βββ myapp_django_server\ βββ urls.py βββ wsgi.py βββ ... And the packages installed in my py2_env virtual env are: (py2_env) C:\Software\MyApp\py2_env\Scripts>pip freeze --local Django==1.11.2 djangorestframework==3.6.3 numpy==1.12.1 pytz==2018.7 wfastcgi==3.0.0 At this point I configure IIS following this guide (I jumped to the Configure IIS to Serve Django Applications chapter) but, at the end, if I browse to http://localhost:81 I get this error: Error occurred while reading WSGI handler: Traceback (most recent call last): File "C:\Software\MyApp\py2_env\Lib\site-packages\wfastcgi.py", line 791, in main env, handler β¦ -
How to check input username and password match with postgres database in login page?
I have a user login page with code below: {% extends "base_generic.html" %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login" /> <input type="hidden" name="next" value="{{ next }}" /> </form> {% endblock %} I have a table named user in postgres database with username and password field.Here is my model: class User(models.Model): name = models.CharField(db_column='Name', max_length=100) password = models.CharField(db_column='Passwd', max_length=30, ) class Meta: db_table = 'User' How can i check the input username and password whether is match with the table 'user'? -
Looking for Django equivalent of Flask's request.get_data() (for Slack request verification with raw request body)
I need equivalent of Flask's request.get_data() for Django / DRF. Got it almost working with str.encode(json.dumps(request.data)), but the output contains spaces between pairs key: value and existing link's signs are not escaped. Flask output (that works for me): b'{"token":"xxxx","team_id":"TDB6U9XM1","api_app_id":"yyyyyy","event":{"type":"link_shared","user":"UDC5TRW0M","channel":"CE9GC5C4R","message_ts":"1543451681.002600","links":[{"url":"http:\\/\\/testing.serv-dev.pl\\/viewer\\/3\\/24","domain":"serv-dev.pl"}]},"type":"event_callback","event_id":"EvEE40NTSM","event_time":1543451682,"authed_users":["UDC5TRW0M"]}' Current Django output: b{"token": "xxxx", "team_id": "TDB6U9XM1", "api_app_id": "yyyyyy", "event": {"type": "link_shared", "user": "UDC5TRW0M", "channel": "CE9GC5C4R", "message_ts": "1543452606.003600", "links": [{"url": "http://testing.serv-dev.pl/viewer/3/24", "domain": "serv-dev.pl"}]}, "type": "event_callback", "event_id": "EvEENV65TU", "event_time": 1543452607, "authed_users": ["UDC5TRW0M"]}'. This is specifically for slack request signature verification that specifically requires raw request body to be passed. Accessing request.body throws an error django.http.request.RawPostDataException: You cannot access body after reading from request's data stream probably due to POST method. -
Why it's not working? What should be done to make the user login work?
Tried many ways but still not working. How to make this work? class LoginView(View): templates = "#/signin.html" context = ModelUser.objects.all() def get(self, *agrs, **kwargs): return render(self.request, self.templates, {'context' : self.context}) def post(self, *args, **kwargs): login = ModelUser() if self.request.method == 'POST': if self.request.POST.get('username') and self.request.POST.get('password'): login.username = self.request.POST.get('username') login.password = self.request.POST.get('password') for verify in self.context: if self.context.filter(username=self.request.POST.get('username')).exist() and self.context.filter(password=self.request.POST.get('password')).exist(): return HttpResponse('You are logged in') else: return HttpResponse('Error password or username') -
How to search django queryset without connect db
How to search django queryset without connect db. I am sorry, my English is not good. Example: items_list = Items.object.all() Items.object.filter(pk=1).delete() items_list.filter(pk=1) # result is None for item in items_list: # I do not want to get a new queryset like this if item.id == 1: new_items_list= item -
Make a prediction on the selected rows in the HTML table using the Django techniques
From an HTML Data table as the one below, I would like for each row selected via a checkbox make a prediction using SVM classifier. Before, I used the same classifier to predict all the dataset containing in CSV file. Now, I want to make the same prediction on only selected rows in the HTML table. Below is my SVM code to make the prediction. import numpy as np import matplotlib.pyplot as plt import pandas as pd from sklearn.svm import SVC from sklearn.metrics import roc_curve, auc from sklearn.cross_validation import cross_val_score from sklearn.cross_validation import train_test_split from sklearn.metrics import accuracy_score from sklearn.metrics import confusion_matrix from sklearn import metrics #Loading dataset train=pd.read_csv('Data.csv') features_col=['Changed_file','Num_commits_before_Closed','Num_lines_added','Num_lines_deleted'] X=train[features_col].dropna() y=train.classes test_size=0.4 #could also specify train_size=0.7 instead random_state=0 #train_test_split convenience function X_train,X_test,y_train,y_test=train_test_split(X,y,random_state=random_state,test_size=test_size) clf = SVC(probability=True, random_state=5) clf=clf.fit(X_train,y_train) y_pred=clf.predict(X_test) #Confusion matrix print(confusion_matrix(y_test,y_pred)) #Print the classification report from sklearn.metrics import classification_report print (classification_report(y_test,y_pred)) -
Django creating model instances(?), newbie
I'm learning some django basics and I have question about models. class album(models.Model): name = models.CharField(max_length=30) datecreated = models.DateTimeField(auto_now_add=True, blank=True) email = models.EmailField() class photo(models.Model): pic_url = models.TextField(default="http://some.url/pic.png") name = models.DateTimeField(auto_now_add=True, blank=True) When creating new album I would like it to have 1000 photos with default picture. Is that possible? How? Thanks! -
Raise validation error in inline field Django
I have a model that contains a TabularInline, and I want to raise a validation error when a condition is not valid. My parent model: @admin.register(Even) class EventAdmin(admin.ModelAdmin): list_display = ['id', 'title'] list_display_links = ['id', 'title] inlines = [EventSpecialPriceInline] And my TabularInline: class EventSpecialPriceInline(admin.TabularInline): model = EventSpecialPrice extra = 0 can_delete = True The error I want to raise is when a price of a row is negative EventSpecialPrice.price < 0 -
curl: (7) Failed to connect to 127.0.0.1 port 8000: Connection refused
I try to run this command on pycharm terminal: curl -X POST -d "username=admin&password=123" http://127.0.0.1:8000/ap i-token-auth/ But I get this error: curl: (7) Failed to connect to 127.0.0.1 port 8000: Connection refused I searched internet but there is no good solution for it -
Django, How do have Post details and a comment form with comments on the same page?
I am trying to have a Post description and an ability to add comments below on the same page. What i have written feels like it should work, i just dont know what im missing. Currently everything works except for the add comment form, it wont display on screen and says Method Post Failed. My issue is somewhere in my 2 views that appear on my detail.html page. The details of the post, and then the partial New Comment form below it. Views.py from django.shortcuts ... ... import NewPostForm class IndexView(ListView): ... class Detail(DetailView): model = Post template_name = 'posts/detail.html' class CommentView(TemplateView): model = Post template_name = 'posts/detail.html' def post(self, request): commentform = AddCommentForm(request.POST) if request.user.is_authenticated: if commentform.is_valid(): comment = commentform.save(commit=False) comment.comment_user = request.user comment.save() comment.comment_date = timezone.now() comment.comment_title = commentform.cleaned_data['comment_text'] commentform = AddCommentForm() args = {'commentform': commentform,} return render(request, self.template_name, args) class NewPostView(TemplateView): ... And My Model that it uses Model.py from django.db import models from django.utils import timezone from django.contrib.auth.models import User import datetime # Create your models here. TYPE_CHOICES = ( ) class Post(models.Model): post_title = models.CharField(max_length=100, default="") post_text = models.CharField(max_length=2500, default="") post_user = models.ForeignKey(User,on_delete=models.CASCADE) pub_date = models.DateTimeField('Date Posted') post_type = models.CharField(max_length=1, choices = TYPE_CHOICES, default="M") def β¦