Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to redirect to a dynamic url in django
I am working on a django project. in the project I have a dynamic url as follows app_name = 'test' urlpatterns = [ path('root', views.root, name='root'), path('output/<str:instance>', views.output_page, name='output_page'), ] There exists two pages in the application. In the root page there exists a form which when submitted should redirect to the output_page. But because the output_page is a dynamic url, I am not able to redirect. Here is my views file def root(request): if request.method == 'POST': name = request.POST.get('name') job = request.POST.get('job') return redirect("test:output_page") return render(request, 'test/root.html') def output_page(request, instance): record = Object.objects.all(Instance_id=instance) return render(request, 'test/output_page.html', {'record': record}) Here is the Model class Object(models.Model): Name = models.CharField(max_length=200, null=True, blank=True) Job = models.CharField(max_length=200, default="") Instance_id = models.CharField(max_length=200) When the redirect happens I want the url to be as follows http://127.0.0.1:8000/output/test-001 where test-001 is the instance_id in the model. The output_page should filter all the data in the model with instance_id test-001 -
Django {% translate %} does not work in project's base.html
I am internationalizing my app and need to translate nav links into their Italian counterparts. All the apps in my project share the same base.html file located in project_folder/templates/base.html. I also created a locale folder inside project_folder containing the .po file for base.html. Inside base.html I have the nav links I want to translate: {% load i18n %} <!doctype html> <html> <body> <nav> <a href="#">{% translate "Define" %}</a> <a href="#">{% translate "Profile" %}</a> ... </nav> </body> </html> Here is the corresponding portion of my .po file: #: project_folder/templates/base.html:32 msgid "Define" msgstr "Definisci" #: project_folder/templates/base.html:35 msgid "Profile" msgstr "Profilo" Despite this, when I switch the site to Italian, the links are all still in English. Other translations done similarly inside app folders in other parts of the website work perfectly. Also, in my settings.py I specified LOCALE_PATH = [ os.path.join(BASE_DIR, 'locale'), ] It seems that Django is not able to find the .po files at the project level, however, there is no error when I compile them and everything seems to be working until I render the nav. Can anybody help? -
Django Celery Tasks are not executed after an hour
I'm using celery to run some background tasks in django. Celery worker executes the tasks correctly for the first 45 minutes. After that tasks are not executed. I'm using Django==2.2.13 and Celery==4.4.7 And this is how i start the celery worker and beat. celery worker -A app_name --loglevel=info celery beat -A app_name --loglevel=info celery setting file is: CELERY_ACKS_LATE = True CELERYD_PREFETCH_MULTIPLIER = 1 CELERY_BROKER_URL = 'redis://localhost:6379' CELERY_RESULT_BACKEND = 'redis://localhost:6379' celery.py from celery import Celery from celery.schedules import crontab os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app_name.settings') app = Celery('app_name') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() app.conf.task_default_priority = 5 app.conf.beat_schedule = { 'parse_sources_manager_async': { 'task': 'parse_sources_manager_async', 'schedule': crontab(minute=0), } } Is there anyway to make it work , any help would be appreciated, thanks in advance. -
Django- user posting Errors
i am finding a problem in saving the user posts from my Django site. Whenever I try to run the submit form, it shows that the form has been submitted but I cant see the post being saved in the data base. def addPost(request): form = hacksform(request.POST or None, request.FILES or None) if request.method == 'POST': form = hacksform(request.POST or None, request.FILES or None) if form.is_valid(): try: newpost = form(commit= False) image = request.FILES['photo'] newpost.author = request.user newpost.post_image = image newpost.save() newpost.save_m2m() except: newposts = form(commit=False) newpost.author = request.user newposts.save() newposts.save_m2m() return HttpResponseRedirect('/tweaks/tweaks') return HttpResponseRedirect('/tweaks/tweaks') and here is my forms.py file class hacksform(forms.ModelForm): VIEW_CHOICES = ( ("Option", "Choose Option"), ("Public", "To Public"), ("Channels", "To Channels"), ) title = forms.CharField(widget=forms.TextInput(attrs={'class': 'user-title', 'placeholder': 'Title'}) ,required=True) content = forms.CharField(widget=forms.Textarea(attrs={'class': 'user-text', 'placeholder': 'Questions'}) ,required=False) tags = forms.CharField(widget=forms.TextInput(attrs={'class': 'input-tag', 'placeholder': 'Add Tag'}) ,required=False) audience_privacy = forms.CharField(widget=forms.Select(choices=VIEW_CHOICES,attrs={'id': 'selector'}) ,required=False) class Meta: model = hacks fields = [ 'title', 'author', 'tags', 'content', 'post_image', 'audience_privacy' ] any ideas why I cant post -
How to setup button on the home page for login Microsoft authentication in a django based project
I am using django-microsoft-auth in my Django project. I followed this guide. Now, I'm able to log in through Microsoft account(address: http://localhost:8000/admin ) but I don't know how to add a view that will say "Login using Microsoft" and how to link that view with the Microsoft authentication page. It will be great if someone can tell me how to do this. You can see this picture. Here Microsoft button is automatically added for login. How to set up a button like this on the home page for login? -
Django multiple annotations sum in one queryset
Models class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE, related_name='order_items') quantity = models.IntegerField(default=1) class OrderPlateRelation(models.Model): order = models.ForeignKey(Order, on_delete=models.PROTECT, related_name='order_model_relations') plate = models.ForeignKey(EncryptedModel, on_delete=models.PROTECT, related_name='order_model_relation') quantity = models.PositiveSmallIntegerField() class OrderItemPlateRelation(models.Model): order_plate_relation = models.ForeignKey( OrderPlateRelation, on_delete=models.CASCADE, related_name='order_plate_relation', ) order_item = models.ForeignKey(OrderItem, on_delete=models.CASCADE, related_name='plate_relation') quantity_of_order_item = models.PositiveSmallIntegerField() Rest Framework Order Detail (Example) : { "id":70, "order_items":[ { "id":1313, "quantity":5 }, { "id":1311, "quantity":5 }, { "id":1310, "quantity":5 } ], "assigned_orders":[ { "order":70, "plate":15929, "quantity":1, "relations":[ { "order_item":1313, "quantity_of_order_item":5 } ] }, { "order":70, "plate":15930, "quantity":1, "relations":[ { "order_item":1310, "quantity_of_order_item":5 }, { "order_item":1311, "quantity_of_order_item":5 } ] } ] } Queryset : qs = ( Order.objects.filter(order_status__in=[Order.ORDER_STATUSSES.New, Order.ORDER_STATUSSES.Processing]) .filter(order_items_productowner_company=self.request.user.company) .distinct() .annotate( item_quantity=Sum('order_items__quantity'), assign_quantity=Sum( F('order_model_relations__quantity') * F('order_model_relations_order_plate_relation_quantity_of_order_item') ), ) .order_by('id') ) I have a order model at top. I'm building queryset from order. I need to sum order items quantity based on provider. Below item quantity part is working fine. item_quantity=Sum('order_items__quantity'), I want to check order_items quantity and sum of assigned_orders quantity. Let me give you a quick example from my JSON : sum of order_items quantity ( "id":1313,"quantity":5 + "id":1311,"quantity":5 + "id":1310, "quantity":5 ) is 15. sum of assigned_order (quantity * sum[quantity_of_order_item]) ==> ("plate":15929,"quantity":1,("quantity_of_order_item":5) 1 * 5 = 5 ("plate":15930,"quantity":1,("quantity_of_order_item":5,"quantity_of_order_item":5) 1 * ( 5 + 5 ) … -
Django Rest when i replace ModelSerializer with HyperlinkedModelSerializer, Raise this error
In my django rest project when I replace ModelSerializer with HyperlinkedModelSerializer, this error Raise below; ' Could not resolve URL for hyperlinked relationship using view name "product-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. ' # Views.py class ProductView(viewsets.ModelViewSet): queryset = Product.objects.all() serializer_class = ProductSerializer class CatView(viewsets.ModelViewSet): queryset = SubCategory.objects.all() serializer_class = CatSerializer class BrandView(viewsets.ModelViewSet): queryset = Brand.objects.all() serializer_class = BrandSerializer # Serializer.py class BrandSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Brand fields = '__all__' class CatSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = SubCategory fields = '__all__' class ProductSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Product fields = '__all__' # urls.py app_name = 'api' router = routers.DefaultRouter() router.register('product', views.ProductView) router.register('category', views.CatView) router.register('brand', views.BrandView) -
Python Django send post request from vue app using axios to django app
I am trying to send a post request from a vue app to a django app. The project structure is something like: - MyProj (main project file) - myproj (django main folder with settings.py) - myapp (django app with urls.py) - vueapp (vue app that has no django related files in it) I am trying to use axios to post data from 'vueapp' to 'myapp' basically. In axios I am posting to "{% url 'frontend:add_to_basket' %}" which seems to be an error. Any suggestions to how to make the two apps communicate with each other? There may be a better method to do it, but here's mines (I added some code snippets) urls.py where i need to post data: app_name = "frontend" urlpatterns = [ path("add_to_basket/", views.add_to_basket, name="add_to_basket"), ] And the view to go with it: def add_to_basket(request): if request.method == "POST": quantity = request.POST['quantity'] return JsonResponse({"quantity":quantity}, status=201) return HttpResponse('') The script in the html/vue file: Assume bagCount takes an integer value correctly. function sendRequest(method, data) { var r = axios({ method: method, url: "{% url 'frontend:add_to_basket' %}", data: data, xsrfCookieName: 'csrftoken', xsrfHeaderName: 'X-CSRFToken', headers: { 'X-Requested-With': 'XMLHttpRequest' } }) return r } export default { name: "purchase-coffee", data(){ return{ … -
django comment form on post detailview
i am still learning django. trying to create a comment form in my blogdetail view.. i am following a tutorial from youtube.. https://www.youtube.com/watch?v=An4hW4TjKhE&t=40s this tutorial has form which takes users from django users .. but in my form i want user to enter his name ,email and content.. following this tutorial i made form model but i have no idea how to get data from my own html form by this.. i have reached to a stage where in admin i can add comments and display them in my html file but now i am getting an error.. name 'post' is not defined my files are.. forms.py from django import forms from.models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('content', 'email', 'name' ,) models.py class BlogPost(models.Model): title = models.CharField(max_length=500) writer = models.CharField(max_length=150,default='my dept') category =models.CharField(max_length=150) image = models.ImageField(upload_to='images') post = models.TextField(max_length=2000) Date = models.DateField( default=datetime.date.today) def __str__(self): return self.title class Comment(models.Model): post = models.ForeignKey(BlogPost , on_delete=models.CASCADE) name = models.CharField (max_length = 150) email = models.CharField (max_length = 150) content = models.TextField () def __str__(self): return self.email views.py def detailview(request, id=None): blg = get_object_or_404(BlogPost, id=id) comments = Comment.objects.filter( post=blg).order_by('-id') if request.method == 'POST': comment_form = CommentForm(request.POST or … -
json.decoder.JSONDecodeError: Expecting value: line 1 column 1 (char 0) while loading a json file
I am trying to load a json file as below but getting the above error. Any idea why am getting this error, thanks. import json with open(settings.NEWS_JSON_PATH, 'w+') as news: articles = json.load(news) the file is this path defined in my settings.py file: NEWS_JSON_PATH = os.path.join(BASE_DIR, 'news.json') -
Django Forms - How to combine Form (CreateView) into ListView Class
My application has User model, to whom I assign different programs. Each program contain different exercises, for each exercise, the user needs to fill up results according to his exercise. So basically, my HTML page for the exercise need to contain another form that provide the user inputs areas. My code contain: User Model, Program Model, Exercise Model, Data Model. Program Model: class Program(models.Model): patient = models.ForeignKey(User, on_delete=models.CASCADE, default=0) program_name = models.CharField(max_length=1000, default="") date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return str(self.id) + " - " + self.patient.username + " - " + self.program_name + " - " + str(self.date_posted) def get_absolute_url(self): return reverse('program-detail', kwargs={'pk': self.pk}) Exercise Model: class Exercise(models.Model): program = models.ForeignKey(Program, on_delete=models.CASCADE, default=0) date_posted = models.DateTimeField(default=timezone.now) name = models.CharField(max_length=1000, default="") description = models.TextField(default="") load_share = models.TextField(default="") breath_method = models.TextField(default="") recovery_method = models.TextField(default="") measure_method = models.TextField(default="") notes = models.TextField(default="") extra_info = models.TextField(default="") reps = models.PositiveSmallIntegerField(default=0) sets = models.PositiveSmallIntegerField(default=0) def __str__(self): return str(self.program_id) + " - " + str(self.pk) + " - " + " - " + self.name + " - " + str(self.date_posted) Data Model: class Data(models.Model): exercise = models.ForeignKey(Exercise, on_delete=models.CASCADE, default="0") set_number = models.PositiveSmallIntegerField(default=0) spo2 = models.PositiveSmallIntegerField(default=0) hr = models.PositiveSmallIntegerField(default=0) physical_level = models.PositiveSmallIntegerField(default=0) breath_level = models.PositiveSmallIntegerField(default=0) sys = models.PositiveSmallIntegerField(default=0) … -
Change the name of output of form-variables Django
I have a form for creating a new recipe using Django - the problem is, that it displays by variable names i.e n_persons, prep_time etc. but I would like to make it Number of persons, Preperation time. Is there a way to do so? {% extends "indkoeb/base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section"> <form method="OPSKRIFT"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">New</legend> {{form|cripsy}} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="submit">Save</button> </div> </form> </div> {% endblock content %} -
Django models save field prohibited
I'm new to Django, I'm tring to save an entry on the history model with the code below. This are my models class Actius(models.Model): id = models.ObjectIdField() name = models.CharField(max_length=255) ric = models.CharField(max_length=255) pais = models.CharField(max_length=255) index = models.CharField(max_length=255) sector = models.CharField(max_length=255) class History(models.Model): actiu = models.ForeignKey( Actius, on_delete=models.CASCADE ) time = models.DateTimeField() price = models.FloatField(max_length=255) What I'm tring to do actiu = Actius.objects.filter(ric='EUR_USD').get() print(actiu) # output: Actius object (None) entry = History( actiu = actiu, price = 12 ) entry.save() print( actiu.history_set.all() ) # output # ValueError: save() prohibited to prevent data loss due to unsaved related object 'actiu'. The actiu field i already created... Why says it's not saved? -
Changing website currency based on user selection Django
I want to implement multiple currency in my Django website. I have used the django-money app for currency conversion. The website allows the user to select currency using a dropdown. When the user selects a currency, I want the entire website (every page) to show the product prices converted in the selected currency. How can I do that? -
Django-auth-ldap problem while trying to login to a Django web-app
Specifications: The web-app runs on Apache 2.4.6 server which runs on a VM with CentOS 7. The LDAP server which I test this app on is ldap.forumsys.com (https://www.forumsys.com/tutorials/integration-how-to/ldap/online-ldap-test-server/). The error: When I try to login in the aforementioned Django app, the authenticate() function returns None. When I look at the Django-auth-ldap logs I see this error: Caught LDAPError while authenticating euler: SERVER_DOWN({'result': -1, 'desc': "Can't contact LDAP server", 'errno': 107, 'ctrls': [], 'info': 'Transport endpoint is not connected'},) What works: From my Centos 7 VM I am successfully able to use ldapsearch on the LDAP server (I can connect from my VM to the LDAP server). This makes me think that the problem is not within Centos itself. The LDAP authentication works when running on my Windows 10 computer with the basic Django development server. The code is the same and I can login without any problems. This makes me think that the problem is not within Django. My counclusion: I think that the problem must be in the communication between the Apache server and the LDAP server. It could perhaps be connected to the httpd configuration (I have not made any changes to any .conf in regards to LDAP, … -
How to solve cannot unpack non-iterable bool object error in Django?
if i put below condition in my view file id=request.POST['id'] #post data which i am sending from html file name=request.POST['name'] #post data which i am sending from html file if MyModel.objects.filter(id=id,name!=name).exists(): print('data available') else: print('data is not available') its showing below error cannot unpack non-iterable bool object if request.POST['name'] is available in my requested id(request.POST['id']),then i want to print print('data available'). Otherwise i want to print print('data is not available') How to Do that? -
How can I visualize data in realtime with Influxdb, django and d3js?
I have developped a little project with django + Influxdb I send data every 15 minutes to influxdb. I have succeeded on displaying that data through D3.js. However, I don't know how to visualize it in "real time". I need to find the way of sending to django the changes in a specific measurement in Influxdb. After that i will send through websockets that data to d3js chart. Any tip? Thanks in advance -
Do for Loop in Django models.py file affect performance?
i plan on using for loops to auto-generate a choices parameter for my field SIZE=[] # to be generated with a for loop to avoid me writing extra lines of code e.g (0, '32'),(1, '33') ... old_price = models.PositiveIntegerField() shoe_varient = models.IntegerField('SIZE', choices=SIZE) Do for loops in the models.py file cause any performance issues, because I assume that the models.py file is just for the building (structuring) of the database.. In other words does the model.py file get called after every request? -
django vs node.js.which is better?
(sorry for my bad english) I know django medium-high level and I know js medium-high level(with jquery and vue.js). Now I have been developing with django. But lately, I liked searching node.js more on the internet for some reason. At the same time, I thought it was better than django node.js. (speed performance, asynchronous etc). I wanted to get advice from experienced people first, that is, from you. Do you think this is the right decision? I should learn node.js after django? I would be glad if you could help. -
Sort weekdays from datetime objects
I want to get the weekdays for each week from a list of datetime objects. Example: For the list [2020-08-17 07:00:00, 2020-08-28 05:00:00, 2020-08-17 09:00:00, 2020-08-18 09:00:00, 2020-08-24 02:00:00, 2020-08-27 02:00:00] The result should be as : list_1 = ['Mon', 'Tue'] list_2 = ['Mon', 'Thu', 'Fri'] -
Can't get images in django
I have vue app and django app. I build them separately and I use vue's index.html as a template. When I go to the image directory. For example: http://localhost:8000/media/posts/images/image.png. Instead of getting the image, I get a static file. Here is my urls.py file. TemplateView responds to the root URL. I use index.html as a template. It comes from vue build. from django.conf import settings from django.conf.urls.static import static from django.contrib import admin from django.urls import path, re_path from django.views.generic import TemplateView urlpatterns = [ path('api/admin/', admin.site.urls), ## I use index.html as template. It comes from vue dist directory re_path('', TemplateView.as_view(template_name='index.html')) ] urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I included vue build files in static files directories. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') STATICFILES_DIRS = ['/home/sam/Documents/Projects/vue/flow/dist/static'] MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') And I use index.html from vue build as a template TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['/home/sam/Documents/Projects/vue/flow/dist'], ... }, ] I tried different ways to fix it. If I remove re_path('', TemplateView.as_view(template_name='index.html')) line from urlpatterns, the image problem disappears. However I miss static files. I tried to use path instead of re_path. Like this: path('', TemplateView.as_view(template_name='index.html')). In this case, I get both images and static files. But … -
How can I change the default value of db in django?
I would like to change the value of itemCnt stored as 0 in db to None if the value of serializer.data[item] comes in as None.So I tried to write and post code as follows, but the default value of db does not change. What should I do? Here's my code. views.py class makeVoteView (GenericAPIView) : serializer_class = makeVoteSerializer permission_classes = [IsAuthenticated] def post (self, request) : serializer = self.serializer_class(data=request.data) serializer.is_valid(raise_exception=True) serializer.save(organizer=request.user) user = User.objects.get(username=serializer.data['organizer']) Vote = vote.objects.get(pk=serializer.data['pk']) if serializer.data['item3'] == None : Vote.item3Cnt = None if serializer.data['item4'] == None : Vote.item4Cnt = None if serializer.data['item5'] == None : Vote.item5Cnt = None if user.identity == 'teacher' : Vote.is_consent = True return Response({'message': '투표 등록이 완료 되었습니다.'}, status=201) return Response({'message': '대기열 등록이 완료 되었습니다.'}, status=200) serializers.py class makeVoteSerializer (serializers.ModelSerializer) : organizer = serializers.CharField(source='organizer.username', read_only=True) class Meta : model = vote fields = ['pk', 'organizer', 'subject', 'item1', 'item2', 'item3', 'item4', 'item5'] -
Randomly Can't connect to MariaDB from Python & Django
I'm running windows server 2016 vm with Diango 3.1.1, Python 3.7.9 (mysqlclient 2.0.1) and MariaDB 10.5.4. After a few hours/minutes randomly django web pages do not connect for a few seconds with the error: OperationalError at / (2002, "Can't connect to MySQL server on '127.0.0.1' (10060)") django page error screenshoot Other python scripts connecting the database fail with the same error. File "c:\Python37\lib\site-packages\MySQLdb\__init__.py", line 130, in Connect return Connection(*args, **kwargs) File "c:\Python37\lib\site-packages\MySQLdb\connections.py", line 185, in __init__ super().__init__(*args, **kwargs2) MySQLdb._exceptions.OperationalError: (2002, "Can't connect to MySQL server on '127.0.0.1' (10060)") I have no errors in MariaDB logs or in event viewer. With "SELECT * FROM information_schema.processlist" I have less than 15 processes My.ini [mysqld] datadir=C:/Program Files/MariaDB 10.5/data port=3306 innodb_buffer_pool_size=1023M slow_query_log=1 long_query_time=5.0 bind-address = 0.0.0.0 max_allowed_packet=64M Can anybody help me solve this? Any reply will be appreciated. -
Migration problem in related models with Django
i'm getting some problems migrating my models with Django. I have 2 models in 2 differents apps: authentication model page import datetime from consumptions.models import Platform from django.contrib.auth.models import User from django.db import models from logs.mixins import LogsMixin class Client(LogsMixin, models.Model): """Model definition for Client.""" user = models.OneToOneField(User, on_delete=models.CASCADE) cif = models.CharField("CIF", null=False, default="", max_length=50) platforms = models.ManyToManyField(Platform, verbose_name=("Plataformas")) dateadded = models.DateTimeField("Fecha de inserción", default=datetime.datetime.now) class Meta: """Meta definition for Client.""" verbose_name = 'Cliente' verbose_name_plural = 'Clientes' def __str__(self): """Representación de cliente.""" cif = "Sin empresa" if self.cif: cif = self.cif string = "{} {} ({})".format(self.user.first_name, self.user.last_name, cif) return string And then I have consumption model page import datetime from authentication.models import Client from django.contrib.auth.models import User from django.db import models from django.utils.timezone import now from logs.mixins import LogsMixin from rules.models import Rule class Consumption(LogsMixin, models.Model): """Definición del modelo de Consumos""" STATES = [ ('not-prevalidated', 'No prevalidado'), ('prevalidated', 'Prevalidado'), ('pendant', 'Pendiente validación cliente'), ('accepted', 'Aceptado'), ] client = models.ForeignKey(Client, verbose_name=("Cliente"), null=True, default=None, on_delete=models.SET_DEFAULT) course = models.ForeignKey(Course, verbose_name=("Curso"), null=True, default=None, on_delete=models.SET_DEFAULT) class Platform(LogsMixin, models.Model): """Definición del modelo para plataforma""" name = models.CharField("Nombre de la plataforma", max_length=100, null=False, blank=False) url = models.CharField("URL de la plataforma", max_length=100, null=False, blank=False) As you can see, … -
local variable 'comment_form' referenced before assignment
hi i am trying to make a comment form in my post detailview .. but getting this error.. local variable 'comment_form' referenced before assignment views.py file def detailview(request, id=None): blg = get_object_or_404(BlogPost, id=id) comments = Comment.objects.filter( post=blg).order_by('-id') if request.method == 'POST': comment_form = CommentForm(request.POST or None ) if comment_form.is_valid(): content = request.POST.get('content') comment_form.save() else: comment_form = CommentForm() context = {'blg': blg, 'comments': comments, 'comment_form' : comment_form , } return render(request, 'blog/blogdetail.html', context) i think the problem is with the context.. forms.py from django import forms from.models import Comment class CommentForm(forms.ModelForm): class Meta: model = Comment fields = ('content',)