Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to pass context value to specific input over the form.as_table in django template
i need to pass value from my view to specific label in the my form.as_tale in this case look at live output template i want assign t_v_a as context to t_v_a as quittanceForm.as_table view.py def Tva_Calculate(request): form_data=forms.QuittanceRegister(request.POST or None) t_v_a=0 if form_data.is_valid(): t_v_a=form_data.cleaned_data['loyer_acteul_411000']*9/100 context ={ 'quittanceForm': form_data, 't_v_a':t_v_a } return render(request,'quittance.html',context) template.py <center> <form action="" method="POST"> <h1>Register new Quittance</h1> {% csrf_token %} <table border="1"> {{quittanceForm.as_table}} </table> <button type="submit">Register now</button> <button type="submit">Calculate_tva</button> </form> {{t_v_a}} </center> live output template https://i.imgur.com/I5DFV.jpg -
Sending parts of list to API and then rendering the responses that arrive in a Django template while other responses are still in transit
I have a Django app that sends a large list (1000 elements) to an API which sends the list to another API service and then processes the returned results and in turn returns them to my app. All this happens when a user clicks on a link. My Django view has to render the results in a template as a column of a table and all this takes a lot of time and causes a timeout. So what I want to do is divide the large list into smaller chunks (of 50 elements) and send the lists and start rendering the 50 items in the first list that's returned. By the time the user clicks on Next, at least one more list would have returned so 50 more can be rendered. But I don't know how to transform my current process into this new process. Here's the relevant code in my view: queue = get_list() headers = {'API-KEY': key, 'content-type': 'application/json'} payload = {"emails": [{"email": e} for e in queue]} attempts = 10 while attempts: res = requests.post(scrubber_url, data = json.dumps(payload), headers = headers) try: for categ, categ_lst in ast.literal_eval(res.text).iteritems(): for entry in categ_lst: email = entry["email"] EmailModel.create(e = email) … -
building '_mysql' extension error: [WinError 2] The system cannot find the file specified
I have been trying to install mysqlclient to communicate with python but i always get this error below. I have tried installing from command prompt too but it says "module setup tools is not found" can someone tell show me what's wrong? Thanks I have been trying to install mysqlclient to communicate with python but i always get this error below. I have tried installing from command prompt too but it says "module setup tools is not found" can someone tell show me what's wrong? Thanks (venv) C:\Users\kesh\PycharmProjects\SplashSongs>pip3 install mysqlclient Collecting mysqlclient Using cached https://files.pythonhosted.org/packages/ec /fd/83329b9d3e14f7344d1cb31f128e6dbba70c5975c9e57896815dbb1988ad/ mysqlclient-1.3.13.tar.gz Installing collected packages: mysqlclient Running setup.py install for mysqlclient ... error Complete output from command C:\Users\kesh\PycharmProjects\SplashSongs\venv\Scripts\python.exe -u -c "import setuptools, tokenize;__file__='C:\\Users\\kesh\\AppData\\Local\\Temp\\ pip-install-3qsuf31w\\mysqlclient\\setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install - -record C:\Users\kesh\AppData\Local\Temp\pip-record-6eq7cdv9\install-record.txt --single-version-externally-managed --compile --install-headers \ Users\kesh\PycharmProjects\SplashSongs\venv\include\site\python3.5\mysqlclient:C:\Users\kesh\AppData\Local\Programs\Python\Python35\lib\distutils\dist.py:261: UserWarning: Unknown distribution option: 'long_description_content_type' warnings.warn(msg) running install running build running build_py creating build creating build\lib.win-amd64-3.5 copying _mysql_exceptions.py -> build\lib.win-amd64-3.5 creating build\lib.win-amd64-3.5\MySQLdb copying MySQLdb\__init__.py -> build\lib.win-amd64-3.5\MySQLdb copying MySQLdb\compat.py -> build\lib.win-amd64-3.5\MySQLdb copying MySQLdb\connections.py -> build\lib.win-amd64-3.5\MySQLdb copying MySQLdb\converters.py -> build\lib.win-amd64-3.5\MySQLdb copying MySQLdb\cursors.py -> build\lib.win-amd64-3.5\MySQLdb copying MySQLdb\release.py -> build\lib.win-amd64-3.5\MySQLdb copying MySQLdb\times.py -> build\lib.win-amd64-3.5\MySQLdb creating build\lib.win-amd64-3.5\MySQLdb\constants copying MySQLdb\constants\__init__.py -> build\lib.win-amd64-3.5\MySQLdb\constants copying MySQLdb\constants\CLIENT.py -> build\lib.win-amd64-3.5\MySQLdb\constants copying MySQLdb\constants\CR.py -> build\lib.win-amd64-3.5\MySQLdb\constants copying MySQLdb\constants\ER.py -> … -
Delete migeration in django
How do I delete migration In django 1.11 I have tried to delete the particular field in model and make migration again but it's still showing me that I have 3 unapplied migration How do I deal with it ? -
JWT Token Authentication with Django Rest Framework
I am having some issues with token authentication on my Django-Rest application with a react native frontend. I have always used Session Authentication, and this is my first time setting up a project with these requirements. I pip installed - rest_framework_simplejwt I know the tokens are being generated when I hit the endpoint api/token I am able to retrieve them on the front end. My problem occurs when I try to hit a list route in the backend and the error I get back is as follows. { "detail": "Authentication credentials were not provided." } I thought this could be a cors issue, or an issue with my axios request, but I am fairly certain they are setup correctly. The other issue is the authentication and permissions classes in my viewset which is where my intuition is telling me this problem is coming from. Relevant settings.py info -- MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'social_django.middleware.SocialAuthExceptionMiddleware', ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_METHODS = ( 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ) CORS_ALLOW_HEADERS = ( 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'x-requested-with', ) REST_FRAMEWORK = { 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', 'rest_framework.authentication.SessionAuthentication', ) … -
advanced filtering through django models
How can I avoid such an ugly serialization of nested fields? obj is ForeingKey('self') field in django model class FwdSerializer(serializers.ModelSerializer): class Meta: model = M fields = ('obj') class FwdSerializer1(serializers.ModelSerializer): obj = FwdSerializer(read_only=True) class Meta: model = M fields = ('obj') class DetailSerializer(serializers.ModelSerializer): obj = FwdSerializer1(read_only=True) class Meta: model = M fields = ('obj') -
Django for loop overwrites saved modelform
The following code saves to database but the values inputted to the form2 overwrites values inputted to Form1 in database. However the Assumptions.Name is not overwritten and has both values Form1 and Form2. Also, if I refresh the page form is expanding and have more rows with previously saved values in it. How to avoid and save Form1 and Form2 data to database correctly? views.py from django.shortcuts import render from .forms import modelformset_factory, AssumptionsForm from .models import Assumptions import pdb model_names = ['Form1', 'Form2'] def get_assumptions(request): AssumptionsFormset = modelformset_factory( Assumptions, form=AssumptionsForm, extra=5) if request.method == 'POST': print('Reached post') pdb.set_trace() for thing in model_names: formset = AssumptionsFormset(request.POST) if formset.is_valid(): if thing in request.POST: print('template name in model_names') for form in formset: print('in for loop' +thing) assumptions = form.save(commit='False') assumptions.Name = thing assumptions.save() else: formset = AssumptionsFormset() print('reached else') return render(request, 'assumptions.html', {'formset': formset, 'model_names': model_names}) models.py from django.db import models from django.forms import ModelForm class Assumptions(models.Model): Worst_Case = models.FloatField(null=True, blank=True, default=None) Grey_Case = models.FloatField(null=True, blank=True, default=None) Red_Case = models.FloatField(null=True, blank=True, default=None) Blue_Case = models.FloatField(null=True, blank=True, default=None) Green_Case = models.FloatField(null=True, blank=True, default=None) Best_Case = models.FloatField(null=True, blank=True, default=None) Name = models.TextField(null=True, blank=True, default=None) assumptions.html <div class="form"> <form action="" method="post"> {% csrf_token %} {{ … -
Trying to deploy Django in windows machine
Hellos guys I’m trying to deploy django in a Windows machine, I already change python versions and wsgi_mod many times and it seem to be correct the problem is when I try to add the application in settinf.py, if I only create the Project and I run 127.0.0.1 it works fine it show me the django welcome message but once I juts create the app and I add in the setting.py it show me 500 Internal Server Error error, could you guys help me with this issue? This is my apache error log. [Fri Jul 06 16:26:07.620085 2018] [mpm_winnt:notice] [pid 6032:tid 564] AH00455: Apache/2.4.33 (Win64) mod_wsgi/4.6.4 Python/3.5 configured -- resuming normal operations [Fri Jul 06 16:26:07.620085 2018] [mpm_winnt:notice] [pid 6032:tid 564] AH00456: Apache Lounge VC14 Server built: Mar 29 2018 12:12:07 [Fri Jul 06 16:26:07.620085 2018] [core:notice] [pid 6032:tid 564] AH00094: Command line: 'C:\\Apache24\\bin\\httpd.exe -d C:/Apache24' [Fri Jul 06 16:26:07.635705 2018] [mpm_winnt:notice] [pid 6032:tid 564] AH00418: Parent: Created child process 4604 [Fri Jul 06 16:26:08.541998 2018] [mpm_winnt:notice] [pid 4604:tid 564] AH00354: Child: Starting 64 worker threads. [Fri Jul 06 16:26:18.172721 2018] [wsgi:error] [pid 4604:tid 1096] [client 127.0.0.1:50432] mod_wsgi (pid=4604): Failed to exec Python script file 'C:/uno/dos/dos/wsgi.py'. [Fri Jul 06 16:26:18.172721 … -
Django 'Undefined' object has no attribute id when when working with legacy database
I have a django application that I'm trying to use with a legacy database. Whenever I try to pull down any data, I get this error: 'Undefined' object has no attribute 'id' This happens no matter what attribute I give it. I made sure that everything in the database is migrated with ./manage.py showmigrations. Here is my view: from django_mako_plus import view_function from django.conf import settings from homepage.models import Users, MyTable @view_function def process_request(): u = MyTable.objects.get(id=1) # print("User object: " + str(u.id)) context = { 'u':u, } # django mako plus changes the way you render a template return request.dmp.render('test-delete.html', context) Here is my template: <%inherit file="base.htm"/> <%block name="header"> </%block> <%block name="content"> <!-- DMP Changes the syntax here too. Default django is {{u.id}} but dmp is {u.id} --> ${u.id} </%block> Here are my models: class MyTable(models.Model): p_number = models.TextField(db_column='P NUMBER', blank=True, null=True) # Field name made lowercase. Field renamed to remove unsuitable characters. id = models.IntegerField(primary_key=True) class Meta: db_table = 'my_table' My models were generated with python manage.py inspectdb > models.py I assume that the error is occuring because django is failing to retrieve the MyTable object, so how can I get django to fetch it and display the … -
Minifying with global variables
The time is coming to push our application into production, and I have not had luck with finding the answer to this question. Unfortunately, some global variables have slipped into our project and I'm curious how to take care of them when compressing and minifying. Additionally, we are using Django, and sometimes to load our data into the js, it is written in script tags in the bottom of the template. This means that some variables get filled up in the HTML template, what will happen to these variables upon minification? Is there still a way we can obfuscate variable names? Or are we stuck on a path of minifying with variable and function names in place? Suggestions as to how to prevent this in the future are also welcome. -
Django REST Swagger gives 400 Error
I'm trying to run Django REST Swagger on (https://docs.djangoproject.com/en/2.0/intro/tutorial01/) to make sure I understand how it works, before trying to integrate Django REST Swagger into my larger project. What I've done: I took the code from the sample Django project and tried integrating Django REST Swagger. In setting.py I added rest_framework_swagger under INSTALLED_APPS. My stuff for static files is as follows: STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'static'), os.path.join(BASE_DIR, 'polls/static'), ) STATIC_ROOT = '/home/tengelbrecht/Documents/ENV/django-project' STATIC_URL = '/static/' In urls.py, I have: from django.conf.urls import include, url from django.contrib import admin from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='Polls API') urlpatterns = [ url(r'^$', schema_view), url(r"^polls/", include("polls.urls")), url(r"^admin/", admin.site.urls) ] When I run the project on localhost (using python manage.py runserver), The result is as in the attached screenshot. The relevant pieces are the localhost on the left screen, and the terminal on the far right. Screenshot of attempting to run this on localhost Any help would be apreciated. Please comment if you need any more information. I feel that there is a simple fix for this, as in I missed one step of integrating Django REST Swagger into the project, but I currently can't figure it out after hours of Googling. -
Why my [(True,"yes"),(False,"no")] acts like a string with form.ChoiceField()?
I can't find a proper way to describe this possible issue in the title. I have a form that has a ChoiceField(). class MyForm(forms.Form): CHOICES_LIST = [ (True,'Yes'), (False,'No'), ] keep_files = forms.ChoiceField(required=False,choices=CHOICES_LIST, widget=forms.RadioSelect()) def clean(self): cleaned_data = super(MyForm,self).clean() keep_files = cleaned_data.get('keep_files') I retrieve the value checked in templates. Let's suppose we have checked Yes in the form. When I do print(keep_files)) it shows True but as str type: print(keep_files,type(keep_files)) True <class 'str'> Do you know how to retrieve the value in its proper type as boolean? since in my list, I set Boolean value in the tuples. Django 1.11 Python 3.5 -
Identify Formset's model else raise error
I am new to Django. I have a code snippet in model admin's save_related method. There i have few inline admin's formsets available. Now i want to check some data of a specific formset. Currently i am doing something like this. for formset in formsets: if formset.model.__name__ == '<ClassName>': 'do something' But is there any cleaner or more pythonic way to do this. I may change the class name in future but this wont raise an error. Can any body help -
Django Formset.is_valid missing 1 required positional argument: 'self'
I was debugging my program and i noticed that on the line Formset.is_valid i am getting error missing 1 required positional argument: 'self'. Could you please advise how it could be solved to make formset and all the forms to validate successfully and save to database. Also is double validation (formset and form) necessary? Thank you for insights. views.py from django.shortcuts import render from .forms import modelformset_factory, AssumptionsForm from .models import Assumptions import pdb model_names = ['Form1', 'Form2'] def get_assumptions(request): if request.method == 'POST': print('Reached post') formset = modelformset_factory( Assumptions, form=AssumptionsForm, extra=5) pdb.set_trace() for thing in model_names: if thing in request.POST: print('template name in model_names') if formset.is_valid(): for form in formset: if form.is_valid(): print('in for loop after valid form1') assumptions = form.save(commit='False') assumptions.Name = thing assumptions.save() else: formset = modelformset_factory( Assumptions, form=AssumptionsForm, extra=5) print('reached else') return render(request, 'assumptions.html', {'formset': formset, 'model_names': model_names}) models.py from django.db import models from django.forms import ModelForm class Assumptions(models.Model): Worst_Case = models.FloatField(null=True, blank=True, default=None) Grey_Case = models.FloatField(null=True, blank=True, default=None) Red_Case = models.FloatField(null=True, blank=True, default=None) Blue_Case = models.FloatField(null=True, blank=True, default=None) Green_Case = models.FloatField(null=True, blank=True, default=None) Best_Case = models.FloatField(null=True, blank=True, default=None) Name = models.TextField(null=True, blank=True, default=None) assumptions.html <div class="form"> <form action="" method="post"> {% csrf_token %} {{ formset.management_form }} … -
srialize(form) in ajax with ImageField
So here's my problem, I have a forms.ImageField in my model called Post and When I create an instance of it I do it via Ajax while posting serialized data with data=$(this).serialize() to my PostCreateAPIView which is a generic API CreateView of Dango Rest Framework , but this method serializes data only and ignores my image. Here's my code: My CreateAPIView: class PostCreateAPIView(generics.CreateAPIView): serializer_class = PostModelCreateSerializer permission_classes = [permissions.IsAuthenticated] def perform_create(self, serializer): print(self) serializer.save(user = self.request.user) My Form: class PostModelCreateForm(forms.ModelForm): content = forms.CharField( label="", help_text="",#text to help widget=forms.Textarea( attrs={ 'cols' : "50", #size 'rows' : "6", #size 'placeholder' : 'Votre publication', 'style' : 'resize : none' })) group = forms.ChoiceField(choices=USER_GROUPS, label='') class Meta: model = Post #we define the model fields = [ "content", "group", "photo" ] $(document.body).on("submit", ".post_form_class",function(event){ event.preventDefault(); this_ = $(this); var formData = this_.serialize(); $.ajax({ method : "POST", url : createPostUrl, data : formData, success : function(data){ }, error : function(data){ } }); }); <script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script> <form id = 'post-form' class="post_form_class" method="POST" action="" enctype="multipart/form-data"> <input type='hidden' name='csrfmiddlewaretoken' value='6bgEU7jPVxXskBGJzP7KzSj9mz75k2dpSqG9Fn1kfghUeWQPTKCbm8JJc5za0ecl' /> <p></p> <div id="div_id_content" class="form-group"> <div class="controls "> <textarea name="content" cols="50" rows="6" placeholder="Votre publication" style="resize : none" class="textarea form-control" required id="id_content"> </textarea> </div> </div> <div id="div_id_group" class="form-group"> <label for="id_group" … -
How to Raise Multiple ValidationErrors (including custom ones) in Django Serializer Validation
I have a serializer class that raises a ValidationError in the validate() method. This ValidationError may have multiple error messages for multiple fields which seems to work alright. Some of my fields in the serializer have constraints which will also cause ValidationErrors to be raised, such as: start_date = DateField(input_formats=DATE_FORMATS_INPUT, error_messages=DATE_ERRORS) My problem is that when any of the errors caused by some sort of field argument (like having an invalid date format) is raised, the ValidationError from my validate() method is not raised. I was wondering if there is a way to get all of the ValidationErrors without creating custom validation methods for each field. -
In django 2.0, writing a script to delete models
I have tried every answer on this (Django script to access model objects without using manage.py shell) stack question, and I always get error "no module name 'project_name'". My project name is called snapbackend. I have an init.py setup. I know I can write django command, but that is somewhat overkill to run one function. I am using django 2.0, and I wanted to write a script to delete old models. import os os.environ["DJANGO_SETTINGS_MODULE"] = "snapbackend.settings.production" import django django.setup() import snapbackend from snapbackend.models import deleteCapsuleModels deleteCapsuleModels() -
how to show a manytomany django form
I am trying to do that a user can modify his/her profile. https://i.stack.imgur.com/ZPesn.png At the rigth (in the image attached in url) we can see that the user has coins and wallets (Bitcoin, Ethereum and coinbase) The goal is that in the left form, the user could change his/her data and add or remove coins and wallets. I need: How can I do that with ModelMultipleChoiceField? How can I show the user's data in the input when the form is loaded?. e.g: antonigalile will be un name input I would like that my widget looks like that: https://i.stack.imgur.com/Fz1tr.png Here my files: models.py from django.db import models from django.utils.timezone import now from django.contrib.auth.models import AbstractUser class Coin(models.Model): name = models.CharField(unique=True,max_length=50) url = models.CharField(max_length=200) transaction_fee = models.FloatField(default=0.0,blank=True) price = models.FloatField(default=0.0,blank=True) market_cap = models.IntegerField(default=0,blank=True) volume = models.IntegerField(default=0,blank=True) circulating = models.IntegerField(default=0,blank=True) change = models.FloatField(default=0.0,blank=True) def __str__(self): return self.name class Wallet(models.Model): name = models.CharField(unique=True,max_length=50) url = models.CharField(max_length=200) coins = models.ManyToManyField(Coin) def __str__(self): return self.name class Usuario(AbstractUser): name = models.CharField(max_length=12, help_text="The name must be between 2 and 12 characters") email = models.EmailField(max_length=60, unique=True, help_text="The email must be between 5 and 30 characters") password = models.CharField(max_length=78) change_password_code = models.CharField(blank=True,max_length=15) activated = models.BooleanField(default=False) activated_code = models.CharField(default="",max_length=15) ip = … -
Django-tables2 footer sum of computed column values
Is there a way to get the sum of values of a column which contains computed values? I tried rendering the footer following the documentation and a question here, but without results. -
How to pass data to database using WYSIWYG HTML Javascript Editor with Django
I've spent the morning reviewing several tutorials on youtube regarding how to create your own WYSIWYG editor. I tested the code and it works as expected in a test environment. The editor customizes the code as advertised. However, when I try to incorporate the code into a django app, it does not work. I've tried to put my django form.variable in many places, but ultimately when I am testing by putting in user data into the new WYSIWYG editor, the screen refreshes and I receive errors on the page. I am using an iframe in my HTML. Is there a straight forward solution to this or better to use one of the many WYSIWYG editors already out there? I am ultimately trying to save the data to a Postgresql database. I can't seem to get the data from the screen to the postgresql database. -
What will happen if the django database gets full ?
It may sound stupid knowing that the database can have as much as 128 TB of data but i want to know what will happen if it's full ? will it just stop working or it will create a new one ? -
Django: Uploading files with AJAX: Form says that the file input field is empty
I'm trying to add a very simple file upload modal form in my Django app. But, when I click the submit button, the form shows me an error message: "this field is required". Everything renders correctly: My main page loads correctly When I click in the "Agregar archivo adjunto" button ("add attachment"), the modal form shows correctly, and all the fields are rendered as I want them to. The issue comes when I click on the "Adjuntar archivo" ("attach file") button in my modal field: The form throws an error, as if I was trying to upload a "null" file! Any help will be really appreciated. By the way: I'm testing this using Chrome (no IE will be used!) Here is my code: models.py def lead_dir_path(instance, filename): """ Files will be saved to: MEDIA_ROOT/leads/<int:pk>/<filename> where <int:pk> is lead's primary key, and <filename> is just that. Filename will be set to an UUID value. """ ext = filename.split('.')[-1] filename = '%s.%s' % (uuid.uuid4(), ext) return 'leads/%s/%s' % (instance.lead.pk, filename) class ArchivosAdjuntosLead(models.Model): lead = models.ForeignKey(Lead, on_delete=models.CASCADE) descripcion = models.CharField(max_length=100) archivo = models.FileField(upload_to=lead_dir_path) views.py def agregar_adjunto_json(request, pk): """ Adds a file to lead with id=pk """ context = {} data = {} lead … -
Django-Sass-Processor Framework Installation
I would like to integrate Sass into my Django project via the django-sass-processor framework. However, after installation, I am receiving a PermissionError: [Errno 13] Permission denied: '/static/' when the framework attempts to create the SASS_PROCESSOR_ROOT directory. How should I approach handling this issue? Should I manually create the directory or is there a way I can grant the appropriate privileges? -
Django admin, Use ImportExportModelAdmin and MarkdownxModelAdmin (Multiple)
I have model Product. 1) There is markdownx field (from django-markdownx package) and I want use markdown editor in admin 2) I use import-export in admin for this model. I can make *import-export** works by using ImportExportModelAdmin: from import_export.admin import ImportExportModelAdmin class ProductAdmin(ImportExportModelAdmin): [some_code...] admin.site.register(Product, ProductAdmin) I can make markdownx works by using MarkdownxModelAdmin: from markdownx.admin import MarkdownxModelAdmin class ProductAdmin(MarkdownxModelAdmin): [some_code...] admin.site.register(Product, ProductAdmin) How to make them both works? -
Why my testing view response is none?
I have a post detail view as below. class PostDetailView(AjaxResponseMixin, UpdateView): model = UserPost context_object_name = 'post' template_name = 'feed/post_detail.html' form_class = CommentForm def get_initial(self): initial_data = super(PostDetailView, self).get_initial() obj = self.get_object() initial_data.update({ "content_type": obj.get_content_type, "object_id": obj.id }) return initial_data def get_context_data(self, **kwargs): # comment_form = CommentForm context = super(PostDetailView, self).get_context_data(**kwargs) kwargs['form_comment'] = context['form'] # comment_form try: total_views = r.incr('userpost:{}:views'.format(self.object.pk)) kwargs['total_views'] = total_views except (redis.exceptions.ConnectionError, redis.exceptions.BusyLoadingError): pass return super(PostDetailView, self).get_context_data(**kwargs) def get_success_url(self): try: total_views = r.incr('userpost:{}:views'.format(self.object.pk)) except (redis.exceptions.ConnectionError, redis.exceptions.BusyLoadingError): pass return reverse_lazy('feed:post_detail', kwargs={'pk': self.object.pk}) def form_valid(self, form): c_type = form.cleaned_data.get("content_type") obj_id = form.cleaned_data.get('object_id') content_data = form.cleaned_data.get("content") parent_obj = None try: parent_id = int(self.request.POST.get("parent_id")) except: parent_id = None if parent_id: parent_qs = Comment.objects.filter(pk=parent_id) if parent_qs.exists() and parent_qs.count() == 1: parent_obj = parent_qs.first() new_comment, created = Comment.objects.get_or_create( user=self.request.user, content_type=c_type, object_id=obj_id, content=content_data, parent=parent_obj, ) if created: ct = ContentType.objects.get_for_id(c_type.id) obj = ct.get_object_for_this_type(pk=obj_id) create_action(self.request.user, 'commented on', obj) return super(PostDetailView, self).form_valid(form) def form_invalid(self, form): print("invalid form") I am writing test case as below. class PostDetailViewTests(TestCase): @classmethod def setUpTestData(cls): user = User.objects.create_user(username='chitra', password='password123') cls.post = UserPost(author=user, post_body="Test post", ) cls.post.save() def setUp(self): login = self.client.login(username='chitra', password='password123') user = auth.get_user(self.client) assert user.is_authenticated def test_postdetail_view_page_status_code(self): """ Test that a PostDetailView page is rendering correctly """ response = self.client.get(reverse_lazy('feed:post_detail', …