Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Certbot: Invalid response http://www.example.org/.well-known/acme-challenge
I'm working through https://serversforhackers.com/video/letsencrypt-for-free-easy-ssl-certificates and https://certbot.eff.org/docs/intro.html , trying to add an ssl certificate to my site (django 1.8 on nginx on ubuntu 16.04). I have been able to do this before a few months ago using the standalone option (Certbot cannot reach nginx webroot running django), but this time I want to get the certbot-auto script working so I can run it on a chron job. I tried: deploy@server:/opt/certbot$ sudo ./certbot-auto certonly --webroot -w /var/www/html -d example.org -d www.example.org Saving debug log to /var/log/letsencrypt/letsencrypt.log Cert is due for renewal, auto-renewing... Renewing an existing certificate Performing the following challenges: http-01 challenge for example.org http-01 challenge for www.example.org Using the webroot path /var/www/html for all unmatched domains. Waiting for verification... Cleaning up challenges Failed authorization procedure. www.example.org (http-01): urn:acme:erruthorized :: The client lacks sufficient authorization :: Invalid response http://www.example.org/.well-known/acme-challenge/6j3QzM4LGMRWaLYZXYTR98: " If I paste http://www.example.org/.well-known/acme-challenge/6j3QzM4LGMRWaLYZXYTR98: " into the browser I get a 404 like in the screenshot. Is it possible to set django to allow the challenge to 'pass through ' the routing without generating a django error? -
Django optional choices
Currently, I have the following field in my model event_duration = models.PositiveIntegerField(blank=False, null=False, choices=EVENT_DURATION_OPTIONAL_CHOICES, validators=[ MaxValueValidator(270), MinValueValidator(1) ], ) and in my forms.py I have def __init__(self, *args, **kwargs): super(EventForm, self).__init__(*args, **kwargs) self.helper['event_duration'].wrap(DropDownTextInput) and my DropDownTextInput: class DropDownTextInput(Field): """ Layout object for rendering dropdowntextinput:: DropDownTextInput('field_name') """ template = "widgets/dropDownTextFieldRendered.html" def render(self, form, form_style, context, template_pack=TEMPLATE_PACK, **kwargs): return super(DropDownTextInput, self).render( form, form_style, context, template_pack=template_pack, extra_context={'inline_class': 'inline'} ) I want it to allow people to select from the the choices I provide, but if I they really wanted to enter their own integer, they could also do so. It currently renders exactly like I wanted (which is the same as in here), but if the user enters a value which is not in the choices list, the form becomes invalid and returns a message Select a valid choice. 99 is not one of the available choices. -
Django CMS get all models defined in the admin
I am building a FAQ plugin that will display a list of questions and answers on my Django CMS site. I have the following model: class Faq(models.Model): question = models.CharField( 'question', blank=False, default="", help_text=u'Please type in the question', max_length=256, ) answer = HTMLField(configuration='CKEDITOR_SETTINGS_BASIC', null=True, help_text=u'Please provide an answer. if you paste HTML make sure to cmd+shift+v for plain paste') def __unicode__(self): # Python 3: def __str__(self): return self.question Which I defined in the admin: class FaqAdmin(admin.ModelAdmin): model = Faq extra = 3 admin.site.register(Faq, FaqAdmin) And added a few instances as content. For now in the plugin defines 10 questions: class FaqPluginModel(CMSPlugin): faq1 = models.ForeignKey(Faq, related_name='faq1+') faq2 = models.ForeignKey(Faq, related_name='faq2+') faq3 = models.ForeignKey(Faq, related_name='faq3+') faq4 = models.ForeignKey(Faq, related_name='faq4+') faq5 = models.ForeignKey(Faq, related_name='faq5+') faq6 = models.ForeignKey(Faq, related_name='faq6+') faq7 = models.ForeignKey(Faq, related_name='faq7+') faq8 = models.ForeignKey(Faq, related_name='faq8+') faq9 = models.ForeignKey(Faq, related_name='faq9+') faq10 = models.ForeignKey(Faq, related_name='faq10+') def __unicode__(self): return self.faq1.question However this approach is not scalable. I am looking for a way to fetch all the models from the admin and render them in the template's html. Something along the lines of: <div class="col-xs-12 col-sm-6"> <div class="box"> --->> {% for every faq model render this: %} <<-- <div class="question"> <div class="question-title"> What are your supported … -
Creating Process Dictionary
My Goal: I need to create a function that retrieves the PID and Name of each process and returns them in a dictionary. I will be uploading this to Django and really need two different dictionaries. 1 with every running process name and PID and another with all installed names and PIDs. So far I can get it to print the dictionary well but not return correctly. Maybe I am calling it wrong. I am newer to this. import psutil def pid_name(): for proc in psutil.process_iter(): try: pinfo = proc.as_dict(attrs=['pid', 'name']) except psutil.NoSuchProcess: pass else: return pinfo If you were to sub "return" for print the dict will print fine. How to I call that dict from here? Is it even returning correctly?? -
OneToOneField in Django admin not editable
I've stripped my code all the way down and am left with these simple models: models.py class Member(models.Model): property = models.OneToOneField(Property, on_delete=models.CASCADE, blank=True, null=True) class Property(models.Model): .... And this very basic admin for Members: admin.py class MemberAdmin(admin.ModelAdmin): pass admin.site.register(Member, MemberAdmin) While logged into the admin as a superuser, as expected on the Member admin page I see a dropdown to choose a Property model. When there is already a Property model selected, the usual pencil icon to edit the selected Property model is faded out, so I cannot click on it. How can I activate this icon so that I can get the usual pop-up to edit the related Property from this Member page? I can't figure out what I am missing. Thank you! -
Django makemigrations and migrate unbearably slow / freeze
I am using Django 1.8.6 for a small project. It has about 5 small models. When I run makemigrations and migrate locally on my Mac, it takes about 3-4 seconds to finish and apply migrations to the SQLite DB. However, when I try doing the same thing on the production server, each of the commands freezes. Here is the point at which it freezes: Operations to perform: Synchronize unmigrated apps: staticfiles, sekizai, sortedm2m, mptt, absolute, aldryn_reversion, aldryn_common, messages, treebeard, emailit, aldryn_apphooks_config, aldryn_translation_tools, parler, aldryn_boilerplates, djangocms_admin_style Apply all migrations: djangocms_video, page_extensions, aldryn_forms, filer, email_notifications, aldryn_newsblog, djangocms_picture, aldryn_people, menus, djangocms_text_ckeditor, djangocms_link, sessions, djangocms_column, djangocms_googlemap, auth, djangocms_snippet, captcha, aldryn_bootstrap3, easy_thumbnails, admin, djangocms_file, cms, taggit, reversion, contenttypes, sites, social_icon, aldryn_categories, djangocms_style Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... Why is this happening? How can I fix it? If it helps, I am using an EC2 AWS instance with CentOS as the production server. -
(Re)Checking Dependencies with PIP
Is it possible to re-check the dependencies of packages installed with pip? That is, suppose we have a working environment. Then, one of the packages changes (gets upgraded, etc). Is there a command one can run to make to make sure that the dependency tree is still sound and does not have conflicts? -
Excluding URLs from Django redirects
Im redirecting all my files on the root of my site to the English subdirectory url(r'^(?P<zero>([a-z-]*)).(htm|php|html)$', redirect, {'to': '/en/{0}.html', 'permanent': True}), I want to exclude a specific page. If I were using apache I could easily do this with an alias or a mod rewrite before it hits the Django application. However Im using Nginx and the redirect gets process regardless of the alias. Is there a rule I can use above so a specific page on my root won't get redirected? -
How to get the next n records in a django queryset?
Is there a way to get the next n records in django queryset? For example, how would I get the next 5 records after getting the first five records? My use case is that I have a see more button on my page and I want to load the next 5 records whenever the see more button is clicked (via ajax) I would like to do something like this #function that handles ajax def load_next_five(initial_five) next_five = initial_five.??? return JsonResponse({'next_five': list(next_five)}) def main_view(request): initial_five = Car.objects.filter(year__gte=2000) ... How would I go about the load_next_five function? -
Cassandra: occasional permission errors
I use cqlengine with django. In some occasions Cassnadra throws an error indicating that user has no permissions do to something. Sometimes this is select, sometimes this is update or sometimes it is something else. I have no code to share, because there is no specific line that does this. I am very sure that user has all the permissions, and sometimes it works. So if user did not have the permissions it should always throw no permission error. So what might be the reasons behind this and how to find the problem? -
One drop down the botton correctly but not the other
What is the difference between {% load i18n %} <a class="material-icons" href="#" data-activates="dropdown1">create<i class="material-icons">arrow_drop_down</i></a> <ul id="dropdown1" class="dropdown-content"> <li> <a href="{# url "requests:accept" pk=object.pk #}" class="green-text" data-turbolinks="false"> <i class="material-icons left">check_circle</i>{% trans "Accept" %} </a> </li> <li> <a href="{# url "requests:reject" pk=object.pk #}" class="red-text text-darken-2" data-turbolinks="false"> <i class="material-icons left">remove_circle</i>{% trans "Reject" %} </a> </li> </ul> and {% load i18n %} <a class="dropdown-button btn" href="#" data-activates="dropdown1" style="padding:0 1rem;"><i class="material-icons">arrow_drop_down</i></a> <ul id="dropdown1" class="dropdown-content"> <li> <a href="{# url "requests:accept" pk=object.pk #}" class="green-text" data-turbolinks="false"> <i class="material-icons left">check_circle</i>{% trans "Accept" %} </a> </li> <li> <a href="{# url "requests:reject" pk=object.pk #}" class="red-text text-darken-2" data-turbolinks="false"> <i class="material-icons left">remove_circle</i>{% trans "Reject" %} </a> </li> </ul> The second block allows me to drop down the button with 'Accept' in green and 'Reject' in red, but not the first block. How could I fix it? Thanks in advance! P.S. Please tell me if the question is unclear. -
django how to delete query object from template
how can I perform an object delete from queryset when I click some button in template for django view here is my code ... HTML views.py def CamerasList(request): model = Cameras # This function can hadle both the retrieval of the view, as well as the submission of the form on the view. if request.method == 'POST': form = CamerasForm(request.POST, request.FILES) if form.is_valid(): form.delete_cam_id = request.POST.get('delete_cam_id') deletelement = Cameras.objects.get(pk=form.delete_cam_id) deletelement.delete() var = {} var = user_group_validation(request) theuser = request.user theuserid = Users.objects.get(user_id=theuser.id).pk theorgid = Users.objects.get(pk=theuserid).organization_id.pk if var['grupo'] == 'superuser': object_list = Cameras.objects.all() organization = Organizations.objects.all() url = request.session['url'] if var['grupo'] == 'admin' or var['grupo'] == 'user': object_list = Cameras.objects.filter(organization_id=request.session['userInc']) organization = Organizations.objects.filter(id=request.session['userInc']) url = request.session['url'] template = get_template(app+u'/cameras_list.html') return HttpResponse(template.render(locals())) -
Google Maps not showing all the markers on the Map
I am trying to plot some coordinates which are transferred from Django backend to front end using Templates. However whenever I see results,all coordinates are not placed,like if I have set of 8 coordinates , I see 6 markers only. Can anybody tell me where is the problem? Code: <script> {{ coordinatelist }}; var sentiment={{ sentimentlst|safe}}; var results= parseInt("{{ Hits }}"); var map; function initMap() { // Constructor creates a new map - only center and zoom are required. map = new google.maps.Map(document.getElementById('map'), { center: {lat: 33, lng:-26}, zoom:2 }); var i=parseInt("0"); {% for item in coordinatelist %} var he = new google.maps.LatLng({{ item.1}},{{ item.0}}); console.log(sentiment[i]) if(sentiment[i]==="positive") { var marker = new google.maps.Marker({ position: he, icon: 'http://maps.google.com/mapfiles/ms/icons/green-dot.png', title: "Mymarker" }); } else if (sentiment[i]==="neutral") { var marker=new google.maps.Marker({ position: he, icon:'http://maps.google.com/mapfiles/ms/icons/blue-dot.png', title:"Mymarker"}); } else { var marker=new google.maps.Marker({ position: he, icon:'http://maps.google.com/mapfiles/ms/icons/red-dot.png', title:"Mymarker"}); } marker.setMap(map); i=i+1; {% endfor %} } </script> -
Django project restructure: Can't import app
I'm trying to restructure my project to match the recommendation in the latest Two Scoops of Django book (for Django 1.11). After completing the restructure, my app can't be imported. secureDash_project ├── README.rst ├── config │ ├── __init__.py │ ├── __pycache__ │ ├── db.sqlite3 │ ├── settings │ │ ├── __init__.py │ │ ├── __pycache__ │ │ └── settings.py │ ├── urls.py │ └── wsgi.py ├── db.sqlite3 ├── manage.py ├── requirements.txt └── secureDash ├── __init__.py ├── __pycache__ ├── dash │ ├── __init__.py │ ├── __pycache__ │ ├── admin.py │ ├── apps.py │ ├── forms.py │ ├── migrations │ │ └── __init__.py │ ├── models.py │ ├── tests.py │ ├── urls.py │ └── views.py └── templates └── dash settings.py excerpt: ... import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname( os.path.dirname(os.path.abspath(__file__)))) ENV_PATH = os.path.abspath(os.path.dirname(__file__)) # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'secureDash.dash.apps.DashConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 'django_static_jquery', # 'bootstrap3', ] ... When running python3 manage.py runserver --settings=config.settings.settings I get: Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x1076b0d08> Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/django/utils/autoreload.py", line 226, in … -
Django: WSGI, slow when running apps.populate, only runs occasionally
I have a django app running on Apache2 and WSGI. I have the wsgi python module below, and added a print statement after application = get_wsgi_application(). When watching the logs this process takes about 1 second. What is confusing, is when this gets triggered. I have a page that sends a simple text output. I hit refresh a bunch of times, and this print gets written to the log once. If I wait a few seconds, it gets written on the next page request. If I refresh successively, it does not until I wait for a period again. My call and response is about 10 milliseconds, but when this is executed (as verified by the print in the log) it takes about a second. This is adding a tremendous amount of unnecessary load to my server and slowing things down. I have it narrowed down to the apps.populate(settings.INSTALLED_APPS) that is called in the django.setup() method. Is there a way I can prevent this from running so often or make it run faster? Thanks for any guidance, or advice you can offer to figure this out or prevent it. wsgi.py: import datetime import os import sys from django.core.wsgi import get_wsgi_application root_path … -
Handle 2 django forms in separate modals but same template
I have a "landing page" in a django template which contains 2 modals with 2 different django forms inside (contact form & signup form) and i'm not sure of how to handle them independently via ajax, i mean the user can fill either form or the 2 of them without rendering the template again(refreshing). I only got to manage 1 of them at first, because after a successfull submission of any of the forms, both forms stop working. For example: if i fill out the contact form and is valid or invalid how do i return both forms in the view? (The success or error message for the contact form and the signup form empty in case the user wants to fill that one too and viceversa) Here's my code. Forms.py class SignUpForm(forms.ModelForm): class Meta: model = Subscriber fields = ['client_name', 'email_address'] widgets = { 'client_name': forms.TextInput(attrs={'class': 'form-control', 'type': 'text'}), 'email_address': forms.EmailInput(attrs={'class': 'form-control', 'type': 'email'}), } class ContactForm(forms.Form): client_name = forms.CharField(required=True,max_length=40,widget=forms.TextInput(attrs={'class': 'form-control', 'type': 'text'})) email_address = forms.EmailField(required=True,widget=forms.TextInput(attrs={'class': 'form-control', 'type': 'email', 'required': 'required'})) message = forms.CharField(required=True,widget=forms.Textarea(attrs={'class': 'form-control', 'type': 'text'})) def sendEmail(self, datas): message = "Hello, " + datas['username']+" "+ datas['email_from'] + " contacted you. here's the message: " + datas['message'] msg … -
Stick the pencil on the right
I'd like to center 'Status' with the pencil on the picture : Here is the html code : {{ headers }} {% load i18n admin_static material_admin %} {% if results %} <div class="results"> <table id="result_list" class="table bordered highlight"> <thead> <tr> {% for header in result_headers %} {% if 'action_checkbox' in cl.list_display and forloop.counter == 1 %} <th class="action-checkbox"> {{ header.text }}<label for="action-toggle">&nbsp;</label> </th> {% else %} <th scope="col" {{ header.class_attrib }}> {% if header.sortable %} {% if header.sort_priority == 0 %} <a href="{{ header.url_primary }}" data-turbolinks="false">{{ header.text|capfirst }}</a> {% elif header.ascending %} <a href="{{ header.url_primary }}" title="{% trans "Toggle sorting" %}" data-turbolinks="false"><i class="material-icons">arrow_upward</i>{{ header.text|capfirst }}</a> {% else %} <a href="{{ header.url_remove }}" title="{% trans "Remove from sorting" %}" data-turbolinks="false"><i class="material-icons">arrow_downward</i>{{ header.text|capfirst }}</a> {% endif %} {% else %} <span>{{ header.text|capfirst }}</span> {% endif %} </th>{% endif %}{% endfor %} <th style="text-align:right;" style='postion: relative; right: 500px'>{% trans "Status" %}</th> {% if row_actions_template %} <th style="text-align:right;">{% trans "Actions" %}</th> {% endif %} </tr> </thead> <tbody> {% for row in results %} <tr class="{% cycle 'row1' 'row2' %}"> {% for item in row.cols %} {{ item }} {% endfor %} <td class="material-icons">create</td> {% if row_actions_template %} <td class="row-actions">{% include row_actions_template with object=row.object %}</td> … -
Django edit UserAdmin removes change password form from Admin Site
I have a model that looks like this: class Device(models.Model): user = models.ForeignKey(User, related_name='device', db_index=True, null=True, blank=True) If I do this in the admin, it removes the "change password" form from the admin site: class UserAdmin(admin.ModelAdmin): inlines = [DeviceInline] admin.site.unregister(User) admin.site.register(User, UserAdmin) Why? The DeviceInline is just a regular inline. -
Django range input instead of text
I am using django forms as you can see in the view.py file and the result is to have a text box.I can submit values numbers and then use this numbers to run script.py etc. I want to do the same with a range input instead of text so that every time the value on the slider change. My views.py def get_name(request): form = NameForm() if request.method == 'POST': a = request.POST['your_name'] # do somethink with the value entered in the form print(a) a = int(a) while a>0: print(a) a = a -1 return render(request, 'personal/code2.html', {'form': form}) My code2.html {% extends "personal/header.html" %} {% block content %} <form action="" method="POST"> {% csrf_token %} {{form}} </form> {% endblock %} And my forms.py from django import forms class NameForm(forms.Form): your_name = forms.DurationField(label='% Brightness ') -
Fields added to Django's AbstractUser aren't showing up in the migration
I'm creating a custom User model based on AbstractUser: from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): certs_only: models.BooleanField() When I run manage.py makemigrations, the migrations are created, but the certs_only field isn't there. All other fields from AbstractUser are there, eg password, last_login, etc. I see this migration in 0001_initial.py. This field also doesn't show up in the admin site, since it doesn't actually exist. I've tried ./manage.py makemigrations common, as some suggested ('common' is my app name), but this made no difference. I've also tried adding fields of different types, but this seems to happen regardless. What could be causing this? -
Python syntax error
I can not quite seem to find what is wrong with this code. from django.db import models from django.utils import timezone from django.contrib.auth.models import user # Create your models here. class post(models.Model): STATUS_CHOICES = ( ('draft','Draft'), ('published','Published'), ) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250,unique_for_date='publish') author = models.ForeignKey(User,related_name='blog_posts') body= models.TextField() publish = models.DateTimeField(default=timezone.now) created= models.DatetimeField(auto_now_add=True) updated= models.DateTimeField(auto_now=True) status = models.CharField(max_length=10, choices=STATUS_CHOICES, default='draft') class Meta: ordering = ('-publish',) def__str__(self): return self.title upon running I get the error message line 34 "def__str__(self):" invalid syntax. The colon seems to be the issue but im not sure why. -
Filtering objects in django admin
I want to manage objects in django admin, though I would like to be able only to edit objects with a specific value of some attribute. Precisely I have now in admin.py: class UnitAdmin(admin.ModelAdmin): list_display = ('type', 'name', 'result_file') list_filter = ['type'] admin.site.register(Unit, UnitAdmin) And I would like to manage only units with type='SomeSpecificType'. I saw something with overriding SimpleListFilter class, though I can't see how this applies here. -
using string variable with REGEXP select pymysql query in python3
i have a chat bot django web application that take the user input and tries to find the matching input in the DB then retrieve the corresponding output. This is a part of chatbot.py code: # -*- coding: utf-8 -*- import re,string,sys import codecs import types import nltk import csv import pymysql from nltk import pos_tag from nltk.tokenize import regexp_tokenize from nltk.tokenize import word_tokenize from nltk.stem.isri import ISRIStemmer from chatbotx1.arabic_const import * from chatbotx1.normalize import * from chatbotx1.stemming import * from nltk.tag.stanford import StanfordPOSTagger from chatbotx1.ar_ghalat import * from chat.models import chat, user_info # initialize the connection to the female_database conn = pymysql.connect("***","***","***","***") cursor = conn.cursor() conn.text_factory = str def run_conversation_male(): last_B =' '.join(chat.objects.values_list('chatbot_response', flat=True).latest('id')) H = ' '.join(chat.objects.values_list('user_iput', flat=True).latest('id')) New_H= ' '.join(PreProcess_text(H)) cursor.execute('SELECT respoce FROM Male_Conversation_Engine WHERE request REGEXP?',[New_H]) reply = cursor.fetchone() if reply: B8=reply[0] new_data(H,B8) ID = chat.objects.values_list('id', flat=True).latest('id') chat.objects.filter(id=ID).update(chatbot_response=B8) Before i was using sqlite3, but now after using Mysql i got this error message: TypeError: not all arguments converted during string formatting I have tried this solution: openconnect = pymysql.connect(host='xxxx',port=3306,user='xxx',passwd='xxx',db='xxxx',charset='utf8') and i got this error message: pymysql.err.ProgrammingError: (1064, "You have an error in your SQL syntax;) (PS: I am using Python3.5,Mysql, pymysql,Django10, and the text is in … -
auth_views.password_reset keeps rendering the root url template, not the password reset one
urls.py url(r'^password-reset/$', auth_views.password_reset, {'template_name': 'password_reset/password_reset.html', 'email_template_name': 'password_reset/password_reset_email.html', 'subject_template_name': 'password_reset/password_reset_subject.txt'}, name="password_reset"), When I visit localhost:8000/my_app/password-reset/ I get my landingpage.html template instead. The dev server output definitely shows a single GET to /my_app/password-reset/, and I've checked all the project's apps' urls.py; the password-reset url isn't duplicated anywhere else. I've even commented out that app's TEMPLATES directory in my settings file to try to force a TemplateDoesNotExist, and it does nothing - the password-reset view seems to be ignoring the template_name parameter that I pass in the url config file. I'm stumped. What could cause this? -
django formset posts an extra (and blank) row
I have a problem with a django formset that I can't really explain to myself. Here is the involved code. forms.py: class ScoreForm(forms.ModelForm): class Meta: model = models.Score fields = ( 'period', 'home_team_score', 'away_team_score', ) ScoreFormSet = forms.inlineformset_factory( models.Fixture, models.Score, form=ScoreForm, extra=5 ) models.py: class Score(models.Model): fixture = models.ForeignKey(Fixture, related_name="score") user = models.ForeignKey(settings.AUTH_USER_MODEL, related_name="score") inserted_at = models.DateTimeField(auto_now_add=True, blank=True, null=True) period = models.IntegerField(blank=True, null=True) home_team_score = models.IntegerField(blank=True, null=True) away_team_score = models.IntegerField(blank=True, null=True) class Meta: db_table = 'score' views.py: class InsertScoreView(CreateView): form_class = forms.ScoreForm model = Score template_name = 'gamestream/insert_score.html' success_url = "/gamestream/score_list/" def get_context_data(self, **kwargs): fixture = Fixture.objects.get(id=self.kwargs['fixture_id']) data = super(InsertScoreView, self).get_context_data(**kwargs) if self.request.POST: data['scores'] = forms.ScoreFormSet(self.request.POST) data['fixture'] = fixture else: data['scores'] = forms.ScoreFormSet() data['fixture'] = fixture return data def form_valid(self, form, **kwargs): user = self.request.user fixture = Fixture.objects.get(id=self.kwargs['fixture_id']) context = self.get_context_data() formset = forms.ScoreFormSet(self.request.POST) if formset.is_valid(): scores = formset.save(commit=False) for score in scores: score.fixture = fixture score.user = user score.save() return super(InsertScoreView, self).form_valid(form) and the template: <div class="container"> <h3>Please insert scores for the following match:</h3> <h4>{{ fixture.starting_time }} -- {{ fixture.league.league_name }} -- {{ fixture.home_team }} vs {{ fixture.away_team }}</h4> <form action="." method="POST"> {% csrf_token %} {{ scores.management_form }} {% for form in scores %} <p>{{ form }}</p> {% endfor …