Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
bootstrap dropdown not working with ajax
So I am creating my blog with Django and I am developing the notification system. I want when the user click the drop to mark all notifications as seen its working and every thing is working fine but when I add the Ajax the dropdown stop working but the Ajax works fine I tried changing the script position in HTML but nothing. Using bootstrap 3.3.7 locally jquery the ajax : <script> $(document).ready(function() { $("#n_d").click(function(event){ $.ajax({ type:"POST", url:"{% url 'seen' %}", success: function(){ document.getElementById("mcount").innerHTML = 0 } }); return false; }); }); </script> the dropdown (it's inside a navbar) {% if user.is_authenticated %} <li class="dropdown"> {% notifications request as notifications %} <a href="#" class="dropdown-toggle" id="n_d" onclick="return x=1" data-toggle="dropdown" role="button" aria-haspopup="true" aria-expanded="false"><i aria-hidden="true" class="fa fa-inbox "> <span class="label label-info" id="mcount">{% noticount request %}</span></i></a> <ul class="dropdown-menu"> {% load blog_tags %} {% for notification in notifications %} <li> <div class="col-md-3 col-sm-3 col-xs-3"><div class="notify-img"><img src="https://www.awn.com/sites/default/files/styles/userthumbnail_tiny/public/avatar92.jpg?itok=i7013HnC" alt=""></div></div> <div class="col-md-9 col-sm-9 col-xs-9 pd-l0"><a href="{% url 'detail' notification.post_pk %}">{{ notification.FromUser }}&nbsp;{{ notification.content }}</a></div> </li> {% endfor %} </ul> </li> {% endif %} the weird tags are Django stuff. -
Django widget template override does not search in the project template directory. How to fix?
I am attempting to override a built in widget template in Django 1.11. I seem to be doing everything that the docs say to do in this regard, but for the widget templates, Django is not looking in my project at all, and I get a TemplateDoesNotExist error. Here's what I have for the override: class MyFileWidget(widgets.FileInput): template_name = 'myapp/my_file_widget.html' The template is definitely there. If I pass the template to a render call, it finds it fine. Problem is an issue of paths. When calling render from a view, it checks the following: projectroot/templates/myapp/my_file_widget.html djangoroot/forms/templates/myapp/my_file_widget.html When it finds the template in my project, it renders it. This is NOT happening when I provide the template path in the class above. In that case, it does not check in my project templates, where the file actually exists, and begins checking in the django path, where it does not. Hence the error message. So I have no clue why this the loader would check my project templates on render calls, but then fail to do so when looking for the "template_name" of the widget override. Any ideas? -
Django periodic task in period of time
I want to make complex tasks that let me control when the task will be started, when it will be finished, when it can repeated Example: I want to create task, it's description call 10 of clients and this task will be assigned to X user and the quantity of this task will be 10 but I want this task will start from 1/1/2018 and it will be finished in 30/12/2018 and the repeat of this task will be weekly Hint: meaning of the repeat, each week I will get the real quantity of the user that's done divided by the quantity of the task and make the quantity of the user is zero in the next week and so on. In details, The X user will start work on Saturday with the target of calling 10 clients by the end of the week, at the end of the week I will calculate the number of clients he called him and I will start again from scratch in the next week with the new task and so on. what is the best way to do that in Django? is there any way to do that with Celery? if can I … -
db_index in django as raw sql query
Can any one specify the real sql query executing for a db_index = True in django, I have a model field which I need to alter with db_index as True, but my rds server crashes since a lot of db process runs in parallel, url = models.CharField(db_index=True,max_length=100, blank=True) What will be the raw psql query for this alteration -
Django - get current user permissions in a view?
Im trying to get the current logged on users permissions My current attempt below returns an error from django.contrib.auth.models import Permission from django.contrib.auth.models import User permissions = Permission.objects.filter(user=User.id) Error int() argument must be a string, a bytes-like object or a number, not 'DeferredAttribute' does anyone know how I can do this? is there a simpler way? Thanks -
Django: how to get list related ForeignKey records?
I am using Django v1.11. Here are 2 models: class Task(models.Model): title = models.CharField() class TaskUser(models.Model): task = models.ForeignKey(Task, related_name='task_user') user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='+') So, I want to get list of tasks and print in one column list of users that are related to this task. How to do that? The problem is tried a lot: select_related, prefetch_related('task_user') and so on.. but nothing works. In some cases there are no sql error, but it prints task.User.None tasks = Task.objects.all() View must be: <table> <tr> <td>Title</td> <td>Users</td> </tr> {% for task in tasks %} <tr> <td>{{ task.title }}</td> <td> {% for user in task.users %} {{ user.id }} {% endfor %} </td> </tr> {% endfor %} </table> -
How do I create a python app after learning the basic
How can I create an app window, Linux or Android with the basic python I've learned. How can I also learn Django with the basic python I've learned -
Removing unnecessary filters from URL django-filter
I have implemented a pretty standard use of Django-filter, and I noticed that when I submit my query, the URL populates not just with the filters I entered, but with blank values for every filter I did not as well. For example, when I fill out just the STATUS_CODE filter, and then search on my site, I get http://localhost:8888/request-log/?status_code=200&route=&time_sent_0=&time_sent_1=&python_error_msg=&s3_upload_failed=&s3_error_msg= Ideally, I would like the URL to only show fields that aren't blank. So, it would go to http://localhost:8888/request-log/?status_code=200 What is the best way to do this? -
Insert data to sqlite3 - python - django
I'm new to django framework. I parsed data from WebAPI server to dict: key is product buys and value is list that contains info about product. Code: def get_best_products(self): dict_of_items = {} for x in range (0, self.max_range): itemId = self.fresh_data.item[x].itemId itemTitle = self.fresh_data.item[x].itemTitle photoUrl = self._get_main_item_photo(x) itemPrice = self._get_item_price(x) dict_of_items[self.fresh_data.item[x].bidsCount] = [itemId, itemTitle, itemPrice, photoUrl] return self._sort_parsed_item_data(dict_of_items) def _sort_parsed_item_data(self, data): return OrderedDict(sorted(data.items(), reverse=True, key=lambda t: t[0])) So i have dict of sorted items by product buys with info as value. What is best way to put this data to database? Should i build a model? And if yes how to do it? any tips? On internet i can find examples of models that allows to edit data... or "how to build mail registration". I want to make a model that shows all the data in a table from all the auctions but i dont want to add more. I want to have only 100 records and they will be updated when a buys change. (and maybe later when i build table that table i will try to do... lets say you click on "itemID" it will take you to edit manager, where you can change what you want about … -
Gallery Slider Images Too Big
This is my first post on stackoverflow. So I am sorry for some untypical stuff in this post. I have programmed a Django Website with a gallery slider, but I have no idea why the images are way too big. Look Here: https://imgur.com/a/YNxu7 I have spent a lot of hours to fix it but, but without sucess. {% block content %} <!-- <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script --> <div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> <!-- Pictures --> <div class="item active"> <img src="/static/img/portfolio/1.jpg" class="img-responsive" alt="Cover1"> <div class="carousel-caption"> <h3>Picture 1</h3> <p>Some details to it</p> </div> </div> <div class="item"> <img src="/static/img/portfolio/2.jpg" class="img-responsive" alt="Cover2"> <div class="carousel-caption"> <h3>Picture 2</h3> <p>Also some details</p> </div> </div> </div> </div> <!-- Left and right controls --> <a class="left carousel-control" href="#myCarousel" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#myCarousel" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> <span class="sr-only">Next</span> </a> </div> {% endblock %} -
Is there a standard way to mock Django models?
I have a model called Pdb: class Pdb(models.Model): id = models.TextField(primary_key=True) title = models.TextField() It is in a one-to-many relationship with the model Residue: class Residue(models.Model): id = models.TextField(primary_key=True) name = models.TextField() pdb = models.ForeignKey(Pdb) Unit tesing Pdb is fine: def test_can_create_pdb(self): pdb = Pdb(pk="1XXY", title="The PDB Title") pdb.save() self.assertEqual(Pdb.objects.all().count(), 1) retrieved_pdb = Pdb.objects.first() self.assertEqual(retrieved_pdb, pdb) When I unit test Residue I just want to use a mock Pdb object: def test_can_create_residue(self): pdb = Mock(Pdb) residue = Residue(pk="1RRRA1", name="VAL", pdb=mock_pdb) residue.save() But this fails because it needs some attribute called _state: AttributeError: Mock object has no attribute '_state' So I keep adding mock attributes to make it look like a real model, but eventually I get: django.db.utils.ConnectionDoesNotExist: The connection db doesn't exist I don't know how to mock the actual call to the database. Is there a standard way to do this? I really don't want to have to actually create a Pdb record in the test database because then the test won't be isolated. Is there an established best practices way to do this? Most of the SF and google results I get for this relate to mocking particular methods of a model. Any help would be appreciated. -
Django View function. Can't get a value from Dictionary, only full dictionary
I want to get a value from a dictionary which I get from request session words = request.session['words'] In the Python console I get my excepted result: >>> words {0: "value_0", 1: "value_1", 2: "value_2", 3: "value_3", 4: "value_4"} >>> words[0] 'value_0' I have a variable called wordcount = 0 and get the result exactly as expected, whatever else. >>> words[wordcount] 'value_0' But, If I try to get a value in my Django view function, it doesn't work Here are my two view functions: def first_view(request): words = {} wordcount = 0 request.session['wordcount'] = wordcount for i in range(5): words[i] = "value_" + str(i) request.session['words'] = words def second_view(request): if request.method == "POST": message = "checkpoint_1" words = request.session['words'] wordcount = request.session['wordcount'] if request.POST.get("input"): input = request.POST.get("input").upper() message = words[wordcount] data = {'message': message} return JsonResponse(data) The second view is called by an Ajax-Request $(button).on('click', function(event) { event.preventDefault(); var input = $('#input').val(); $.ajax({ method: "POST", url: "/second_view/", data: { "input": input }, dataType: "json", context: this, success: function (data) { output.innerHTML = data.message; } }); }); My exception is, that the Response data.message is 'value_1', but I get the 'checkpoint_1' message. If I replace the following part: if request.POST.get("input"): input … -
How to have different serializers for read_only & write_only with the same name in DRF?
After you create a Django object in a CreateAPI of DRF, you get a status 201 created and the object is returned with the same serializer you used to create the Django object with. Wanted: on create: Serializer.comments = Textfield(write_only=True) and on created (201 status) Serializer.comments = a list of commments I know it's possible by overriding the CreateAPIView.create function. However, I'd like to know if it's possible by using write_only=True and read_only=True attributes to serializer fields. For now I think it's not possible because they both have the same name. I'd have liked to do something like this: class CreateEventSerializer(serializers.ModelSerializer): comments_readonly = serializers.SerializerMethodField(read_only=True, label='comments') class Meta: model = Event fields = ('id', 'comments', 'comments_readon) def __init__(self, *args, **kwargs): super(CreateEventSerializer, self).__init__(*args, **kwargs) self.fields['comments'].write_only = True def get_comments_readonly(self, obj): comments = obj.comments.replace('\r', '\n') return [x for x in comments.split('\n') if x != ''] But this way, the JSON that is returned still contains the key "comments_readonly" instead of the expected key "comments". Using latest DRF, 3.7.1 In other words: Is it possible to create a serializer field that behaves differently based on read and write? -
No JSON object could be decoded - Need to upload file to Django
I'm working on an existing Django app and need to be able to upload a file. I'm sending it a multi-part form so I can send a file and some fields, but the server responds back No JSON object could be decoded How can I allow my view to accept a multi-part form? My route function definition is simply: @api_view(['POST']) def upload(request, pk) print "hello" It doesn't get to hello, so somewhere in the magical box of Django this JSON error is occuring. Can anyone give me a clue where to look? I've checked our urls.py file and see nothing that would make this decision or interrupt a request and our init.py file is empty. runserver isn't even a file... I guess it's just more django magic. (Python: 2.7, Django: 1.10.6) -
Django POST request does not organize data as expected
So I have a form that I'm posting to a Django app. The field names are such as: field[section][name][attr] where section, name, etc. can have any number of values. When I attempt to access the data in the POST request these are the exact keys in the QueryDict, so to access the data I have to do something like request.POST.get('field[section][name][attr]'). Why doesn't Django create the hierarchy so I can do something like fields = request.POST.getlist('field') and then go deeper from there with something like for section, value in fields: for field_name, attributes in value: It seems I have to use regex's to process the form data. Am I missing something? -
How to pass Django filter args as arguments to other function
I want to make a class function that returns the result of a filter, but I want to be able to use it as if the function was a django filter too: This is what I've tried: def section_set_with_compound(self, *args, **kwargs): print args print kwargs return self.section_set.filter(Q(args) |Q(course__is_compound=True)) But im getting an error as if args and kwags are empty: I want to be able to do: myobject.section_set_with_compound(param1=1,param2__param3__=x,param4__icontains="ha..") How can I accomplish this? -
My form fields are no longer coming though on the update page?
I have a model 'Partner' with a one-to-many relationship to 'Product'. When I added the 'Product' formset I broke something to do with the relationships - the html still shows up eg <h3>Products</h3>, and the submit button remains but there are no longer any of the form boxes. So it looks like the form is being loaded but something isn't being passed anymore maybe. Any help would be greatly appreciated. Here is my code below. my forms.py <div class="container"> <div class='col-sm-6'> <h1>Preview</h1> <hr/> <div class='content-preview'> <h3 id='preview-name'></h3> <p id='preview-mission'></p> <p id='preview-vision'></p> <p id='preview-website-link'></p> <p id='preview-fb-link'></p> <p id='preview-twitter-link'></p> <p id='preview-ig-link'></p> </div> </div> <div class='col-sm-6'> <h1>Form</h1> <hr/> <form method='POST' action='' enctype='multipart/form-data'>{% csrf_token %} {{ partnerForm|crispy }} {{ formset.management_form }} <br> <h3>Products</h3> {% for form in formset %} {{ form|crispy }} {% endfor %} <input type='submit' class='btn btn-default' value='Create Partner' /> </form> </div> </div> my form.html class PartnerForm(forms.ModelForm): mission = forms.CharField(widget=PagedownWidget(show_preview=False)) vision = forms.CharField(widget=PagedownWidget(show_preview=False)) # publish = forms.DateField(widget=forms.SelectDateWidget) class Meta: model = Partner fields = [ "name", "logo", "banner_image", "mission", "vision", "website_link", "store_link", "fb_link", "twitter_link", "ig_link", ] class ProductForm(forms.ModelForm): image = forms.ImageField(label='Image') class Meta: model = Product fields = [ "name", "link", "description", "price", "image", ] my views.py from django.contrib import messages from … -
Gunicorn can't create .sock file using .BASH script
We have two ways to start gunicorn: Use command 'systemctl start gunicorn' and config file 'gunicorn.service', then it create .sock file as it should be. I can see myproject.sock file using use command 'ls /webapps/myproject'. [Unit] Description=gunicorn daemon After=network.target [Service] User=myproject Group=nginx WorkingDirectory=/webapps/myproject ExecStart=/usr/bin/gunicorn —access-logfile - —workers 3 —bind unix:/webapps/myproject/myproject.sock myproject.wsgi:application [Install] WantedBy=multi-user.target Create and use .BASH script 'gunicorn_start.bash', becouse it`s good way with 'virtualenv', but then we start gunicorn at this script, .sock file not create. I not see myproject.sock file using command 'ls /webapps/myproject'. Can't configure nginx without gunicorn myproject.sock. How to fix this? - Tell me, please. #!/bin/bash NAME="tdkennel" # Name of the application DJANGODIR=/webapps/myproject/ # Django project directory SOCKFILE=/webapps/myproject/myproject.sock # we will communicte using this unix socket USER=myproject # the user to run as GROUP=webapps # the group to run as NUM_WORKERS=3 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=myproject.settings # which settings file should Django use DJANGO_WSGI_MODULE=myproject.wsgi # WSGI module name echo "Starting $NAME as myproject" # Activate the virtual environment cd $DJANGODIR export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn # Programs meant to … -
How to calculate events per hour by route and daterange
How can I calculate stops per hour by route and date model: MyModel(models.Model): route = models.Integer(... on_route_time = models.TimeField(... dropoff_stops = models.Integer(... pickup_stops = models.Integer(... date = models.DateTime(... My query: def stops_per_hour(date): query_set = MyModel.objects.filter(date=date).values( 'route', 'dropoff_stops','pickup_stops','on_route_time').annotate( total=(Sum('actual_stops') + Sum('pickup_stops'))).order_by('route') which gives me: <<QuerySet [{'route': 226, 'dropoff_stops': 84, 'pickup_stops': 0, 'on_route_time': datetime.time(5, 23), 'total': 84},{'route': 242, 'dropoff_stops': 33, 'pickup_stops': 0, 'on_route_time': datetime.time(3, 24), 'total': 33}]>> I'm stuggling with how calculating stops/hour for each route and passing this to the view (e.g. route 226 stops/hour = 15.18. Suggestions? Thanks. -
Filtering select field options in django-xadmin
I am using django-xadmin for one of my project. I need help in a case. Suppose, i have two models like this - class Foo(models.Model): CHOICES = ( ('a', 'Option A'), ('b', 'Option B') ) status = models.CharField(max_length=10, choices=CHOICES) class Bar(models.Model): foo = models.ForeignKey(Foo) remarks = models.CharField(max_length=200) In xadmin, when i try to add Bar via default form provided by xadmin, in the select Field Foo, all Foos (both with Option A and Option B) become available to select. I want to filter the options and only provide, say, Foos of Option A. How can i do that ? Is there any method in xadmin, i should call or customize to achieve it ? -
Trying to use Docker with Django but server not starting
I'm trying to start a Django app using Docker on Windows 10. I'm following the Quickstart Tutorial here: https://docs.docker.com/compose/django/#connect-the-database When it gets to the docker-compose up part, to actually start the app, it gets stuck. This is the docker-compose.yml: version: '3' services: db: image: postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db This is the Dockerfile: FROM python:3.5 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code ADD requirements.txt /code/ RUN pip install -r requirements.txt ADD . /code/ when I use docker-compose up it gets stuck in: web_1 | Performing system checks... web_1 | web_1 | System check identified no issues (0 silenced). -
How can I reverse django admin url with url parameters to prepopulate some fields?
I have Transaction app and Transaction model. Transaction model has foreign key to User model. I noticed that I can prepopulate some fields with data through GET parameters. For example to choose user for my transaction in admin form I can use this url: transactions/transaction/add/?user=1 It work fine, but I want to user reverse function to generate that kind of urls. Tried this: from django.urls import reverse reverse('admin:transactions_transaction_add', kwargs={'user': 1}) But got this error: Reverse for 'transactions_transaction_add' with arguments '()' and keyword arguments '{'user': 1}' not found. 1 pattern(s) tried: ['admin/transactions/transaction/add/$'] I made this work to use concatenate generated link: change_url = reverse( "admin:transactions_transaction_add", ) + "?user=" + str(obj.pk) But would be very kind to know if the more clear solution for this. Note that 'transactions/transaction/add/?user=1' works just fine if use it from browser, error appears for reverse function. Thanks! -
Does a foreign key object have a unique id value?
I am creating a job board site, where all jobs are displayed in a list and each one is a link that leads to a page displaying more information about the job. I have the following models: from django.db import models from django.contrib.auth.models import User from django.db.models.signals import post_save from django.dispatch import receiver # Create your models here. class Employer(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) def __str__(self): return self.user.first_name @receiver(post_save, sender=User) def create_employer(sender, instance, created, **kwargs): if created: Employer.objects.create(user=instance) @receiver(post_save, sender=User) def save_employer(sender, instance, **kwargs): instance.employer.save() class Job(models.Model): poster = models.ForeignKey(Employer, on_delete=models.CASCADE) job_title = models.CharField(max_length=50) establishment_name = models.CharField(max_length = 50) address = models.CharField(max_length = 50) state = models.CharField(max_length = 20) zip_code = models.CharField(max_length = 10) def __str__(self): return self.job_title + " - " + self.establishment_name \ + ", " + self.poster.user.first_name + " " +self.poster.user.last_name Views.py: def index(request): jobs = Job.objects.all return render(request, 'core/index.html', {'jobs' :jobs }) On index.html, the available jobs are listed as so: <table> <tbody> {% for job in jobs %} <tr> <td><a href="#">{{ job.job_title}} - {{ job.establishment_name }}</a></td> </tr> {% endfor %} </tbody> </table> I want these to be clickable links, that will bring the user to another page giving them more details about the job. I … -
TypeError at /notes/index/ context must be a dict rather than RequestContext
hello guys i have a error with django i dont know where exactly the error is please have a look at my code and help me solving this is my views.py from notes app from django.shortcuts import render from django.http import HttpResponse from django.template import loader,RequestContext # Create your views here. def index(request): template=loader.get_template("index.html") rc=RequestContext(request,{'username':'hello'}) return HttpResponse(template.render(rc)) this is my settings.py configuration from appsuite project folder BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '&1hv71rr0e7b!m)7sv(p7of0p7q0%-mb9o*^r*amw$d1o3%=s_' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ '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', ] ROOT_URLCONF = 'appsuite.urls' WSGI_APPLICATION = 'appsuite.wsgi.application' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'notes/templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] # Database # https://docs.djangoproject.com/en/1.11/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, … -
UnboundedLocalError in Django
I'm getting UnboundedLocalError in django. Exception-value:local variable 'comment_form' refrenced before assignment. I used ModelForms from forms to create a comment form.So this is the views.py file of the comment form. def post_detail(request,year,month,day,post): '''post=get_object_or_404(Post,slug=post,status='published',publish__year=year, publish__month=month,publish__day=day)''' try: post=Post.published.get(slug=post) except Post.DoesNotExist: raise Http404("Post Doesnot Exist") #list of active comments for the post comments=post.comments.filter(active=True) if request.method=='POST': #a comment was posted comment_form=CommentForm(data=request.POST) if comment_form.is_valid(): #create comment object but dont save to database yet new_comment=comment_form.save(commit=False) #assign the current post to the comment new_comment.post=post #save the comment to database new_comment.save() else: print (form.error) comment_form=CommentForm() return render(request,'blog/post/detail.html',{'post':post,'comments':comments,'comment_form':comment_form}) '''return render(request,'blog/post/detail.html',{'post':post})''' template detail.html {% extends "blog/base.html" %} {% block title %}{{ post.title }}{% endblock %} {% block content %} <h1>{{ post.title }}</h1> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|linebreaks }} (% with comments.count as total_comments %} <h2> {{total_comments}}comment{{total_comments|pluralize}} </h2> {% endwith %} {% for comment in comments %} <div class="comment"> <p class="info"> Comment {{forloop.counter }} by {{comment.name}} {{comment.created}} </p> {{comment.body|linebreaks}} </div> {%empty%} <p>There are nocomments yet.</p> {% endfor %} {% if new_comment %} <h2>Your comment has been added.</h2> {% else %} <h2>Add a new comment.</h2> <form action="." method="post"> {{comment_form.as_p }} {% csrf_token %} <p><input type="submit" value="Add comment"></p> </form> {% endif %} {% endblock %} …