Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I create a functional api using django rest framework?
I am trying to use mailgun's api on a landing page made through unbounce.com, however I discovered that I can't make requests client side. I do have django set up, so, I'd like to use that to make api calls to mailgun instead. So, my question is how do I create using django-rest-framework, an API that would make the api calls for me and return the response. I have used drf before, but mostly serializing models, and this time I'd like to make a function-based api I expect to make a call to mailgun and pass a parameter called email so that I can use something like domain.com/api/mailgun/email="email@email.com" -
Keep getting duplicate key errors when saving database entires with Django
In the project I am currently working on, I have a Django model with a VARCHAR field that is the primary key. It was multiple purposes and it designed quite generically. This model is used within an app to store data saved, and a secondary model is create simultaneously to link the generic object with a less generic model, to easily find the related models. When saving the generic model, the VARCHAR primary key is generated based off certain parameters sent when saving (such as store it belongs to, and the time period it was saved, and the the product it is attached to). The issue is on more than one occasion, when a user saving data and creating a new generic modal and link model, Django is returning duplicate key errors. The key generated is fairly distinct and at least one version of the data is being created. Examples of the model structure (some fields omitted for levity) class GenericModel(models.Model): string_id = models.CharField(max_length=255, db_index=True) updated = models.DateTimeField() created = models.DateTimeField(auto_now_add=True) class LinkModel(models.Model): generic_model = models.ForeignKey(form_models.GenericModel, on_delete=models.CASCADE, related_name='link_models') Example of saving process: string_id = f`{store.id}{period.id}{product.id}` generic_model = GenericModel.objects.filter(string_id=string_id).first() if generic_model: generic_model.updated = time.now() generic_model.save() else: generic_model = GenericModel.objects.create(string_id=string_id) link_record = … -
Graphene Django File field get absolute path
I have an image field in my Django model and I am trying to get absolute path of the image field output from Graphene. none class Meta: model = Account``` i do not get an absolute filefield path -
Email not sending using gmail
I am creating an e-commerce website by following a tutorial online and ive reached the point where I created a form and then I am supposed to send emails to anyone who completed the form, however, the emails are not sending. Settings.py EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'email@gmail.com' EMAIL_HOST_PASSWORD = 'password123' EMAIL_PORT = '587' EMAIL_USE_TLS = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' DEFAULT_FROM_EMAIL = 'testing@testing.com' viwes.py from django.shortcuts import render from django.core.mail import send_mail from django.conf import settings from .forms import contactForm # Create your views here. def contact(request): form = contactForm(request.POST or None) if form.is_valid(): name = form.cleaned_data['name'] comment = form.cleaned_data['comment'] subject = 'Message from MYSITE.com' message = '%s %s' %(comment, name) emailFrom = form.cleaned_data['email'] emailTo = [settings.EMAIL_HOST_USER] send_mail(subject, message, emailFrom, emailTo, fail_silently =True) context = locals() template = 'contact.html' return render(request,template,context) I don't get an error but I'm not receiving emails -
Django fetch dropdown data
How to fetch data from the database which just got stored in the DB. I have tried several attempts but got closer but still not a clean data which I would like to retrieve for the script to execute. MODEL: class CODE (models.Model): name = models.CharField(max_length=4, default=None) def __str__(self): return self.name class SiteData (models.Model): site = models.ForeignKey(Code, on_delete=models.CASCADE, null=True) VIEW: def sitedata(request, *args, **kwargs): form = SiteData_Form(request.POST or None) template_name = 'sitedata.html' if request.method == 'POST': form = SiteData_Form(request.POST or None) if form.is_valid(): code_pk_list = request.POST.getlist('dc', None) selected_location = CODE.objects.filter(pk__in=code_pk_list) context = [{ 'location': selected_location, 'data1': request.POST['data1'], }] Location and data1 are dropdown selections.. I get the <QuerySet [<CODE: SITE1>]> How to get the only SITE1 thanks for the help In debug, i get ID not the text name. Location: `10` Data1: `1` -
serve existing excel files using django and pure javascript
Im trying to serve an existing excel file using django download it using javascript. I tried the following code in django view: Generate_Report is the io.Bytes() read from xlsxwriter. response=HttpResponse(Generate_Report.output,content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition']='attachment;filename=Report.xlsx' return response In html I wrote this xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { var downloadLink = window.document.createElement('a'); var contentTypeHeader = xhttp.getResponseHeader("Content-Type"); downloadLink.href = window.URL.createObjectURL(new Blob([xhttp.response], {type: 'application/vnd.openxmlformats-officedocument.spreadsheetml.sheet'})); downloadLink.download = "Report.xlsx"; document.body.appendChild(downloadLink); downloadLink.click(); document.body.removeChild(downloadLink); } }; I want to serve an existing excel file as downloaded format. -
How to check for specific backend error keys when using async/await?
I want to display a custom message in Vue (with Django as the backend) when creating an account if the entered email already exists in the database. Currently the server returns a 400 with the following response: {"email":["There is another user with this email"]} How can I access this error object to check if it contains an "email" key? I've found this approach creating a wrapper: https://dev.to/sadarshannaiynar/capture-error-and-data-in-async-await-without-try-catch-1no2 but I feel like there must be a better/simpler way of handling this Last thing I tried: const { error, data } = await usersAPI.create(userData) where "create" is: create (data) { return Vue.axios.post(url, data, config) } then console.error(error) (but it doesn't print anything) -
How can I determine the separator when I got many inputs
I'd like to inform the value of two variables separated by an delimiter. Even thoug I can inform mutiple inputs, they will not be separateded. I get >>>>> 12 for example. I'd like >>>>> 1 2 x, y = input().split(' ') Actual result >>>>12 Expected >>>>> 1 2 -
Django - Html Audio Failed to load resource: the server responded with a status of 403 (Forbidden)
Audio file uploaded and referenced with the correct path, but does not play in html5 audio. models.py class AudioTrack(models.Model): track = models.FileField(upload_to=upload_image_path) index.html <audio controls> <source src="{{ instance.track.url }}"> <code>audio</code> element. </audio> The audio file get's stored together with the images in the media directory. I can download the file from the media directory. When I try to open the audio file path in a new tab I get a 403 Forbidden nginx/1.14.0 (Ubuntu) Ive also added the media context processor to the settings, but still the same. The HTML5 Audio player works with audio files from other websites. Thank you for any help -
Loading assets folder in Django
I recently started a basic django project, i want to load an already made default template. This template has an assets folder with all the CSS, JS files etc This folder, is later called in the templates, so for example i can have: <script src="./assets/somejsfile.js" type="text/javascript"></script> The problem with this is that none of the files in the assets are being retrieved. I know that the problem depends on where i put the assets folder, but i don't know how to solve that. I tried to add it to different parts of my project's structure but it doesn't work, since i only get a lot of errors like this: http://127.0.0.1:8000/assets/somecss.css net::ERR_ABORTED 404 (Not Found) Here is my settings.py: STATIC_URL = '/static/' In this static folder, there is a basic css file i tested before trying this. And here is the structure of my project: //MYSITE FOLDER migrations ASSETS templates -> INDEX.HTML (where the assets folder is called) views, forms etc -
Django Social Auth - Referring to usersocialauth for foreign key in model
I'm using the social_django package for the first time. The project only requires authentication for the application through Facebook so I implemented the SOCIAL_AUTH_FACEBOOK method into my app, which retrieves basic info like username, first name, last name, email address. I also get the user's Facebook profile picture through SOCIAL_AUTH_FACEBOOK_EXTRA_DATA. I want to figure out how to refer to the usersocialauth model as a parent key in my model. Right now, it's associating everything to auth_user model, which doesn't allow me to access the Facebook profile picture in the template. Here is what I am doing at the moment: models.py from social_django import models as oauth_models class Review(models.Model): ... author = models.ForeignKey(oauth_models.USER_MODEL, on_delete=models.CASCADE) I am able to access the basic fields in the template through <p>{{ review.author.name }}</p>, but to see the profile picture, I have to do something like this: {% for author in backends.associated %} <img src="{{ author.extra_data.picture.data.url }}" alt=""> {% endfor %} I would like to simplify this and just refer to the usersocialauth model so I can access all the data from one place in the template. -
Django - No 'Access-Control-Allow-Origin' header is present on the requested resource when making a POST
Whenever I make a request.post inside my custom authentication class, the response takes a while and then throws me this error (502) Access to XMLHttpRequest at 'http://54.185.235.97:8000/rest-auth/login/' from origin 'http://ec2-54-185-235-97.us-west-2.compute.amazonaws.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. Here is the code (This code send an email to the user to reset the password if he/she exceed the numbers of login attempts) headers = {'Access-Control-Allow-Origin': '*'} requests.post( "http://ec2-54-185-235-97.us-west-2.compute.amazonaws.com:8000/rest-auth/password/reset/", data={'email': user.email}, headers=headers ) user.is_blocked = True user.save() attemptsObject.delete() raise exceptions.AuthenticationFailed(('User Blocked')) This code works fine in my development workspace, but somehow gets trouble inside my AWS instance, is it something to do with my Nginx configuration? or do I need to create a Custom CORS middleware class? Nginx: upstream django_app { server unix:/var/www/backend/run/gunicorn.sock fail_timeout=10s; } server { listen 8000; server_name localhost; access_log /var/www/backend/logs/nginx-access.log; error_log /var/www/backend/logs/nginx-error.log warn; location / { proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://django_app; } location ~* \.(eot|ttf|woff|woff2)$ { add_header Access-Control-Allow-Origin *; } } -
NoReverseMatch at / Reverse for 'dashboard' not found. 'dashboard' is not a valid view function or pattern name
Hi i am beginner in django, I have started the course of it last week and got stuck into this error from last two days. Seeking for the help to get out from that mess i have made. I am not able to open the dashboard of my site don't know what has happened. I have been searching for this from last two days. Still doesn't got anything. Thanks in advance. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 2.2.3 Python Version: 3.7.3 Installed Applications: ['pages.apps.PagesConfig', 'listings.apps.ListingsConfig', 'realtors.apps.RealtorsConfig', 'accounts.apps.AccountsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize'] Installed 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'] Template error: In template C:\Users\kamal jeet singh\wproject\kt\webproject\Template\partials\_nav.html, error at line 50 Reverse for 'dashboard' not found. 'dashboard' is not a valid view function or pattern name. 40 : 41 : <ul class="navbar-nav ml-auto"> 42 : {% if user.is_authenticated %} 43 : <li 44 : {% if 'dashboard' in request.path %} 45 : class="nav-item active mr-3" 46 : {% else %} 47 : class="nav-item mr-3" 48 : {% endif %} 49 : > 50 : <a class="nav-link" href=" {% url 'dashboard' %} "> 51 : Welcome {{ user.username }}, "Dashboard" </a> 52 : </li> 53 … -
Interactive WebAgg plot using Django Channels not rendering entire figure
I am trying to embed an interactive matplotlib plot using the WebAgg backend into a Django application. Whenever fig.canvas.draw() is called only parts of the figure are rendered in the browser. Versions: Python - 3.6.7 Django - 2.2.4 Channels - 2.2.0 Matplotlib - 3.1.1 I am using Django Channels for the figure's websocket. The figure has 3 points connected by two lines, the user can click and drag the points, after the user releases the mouse button the figure redraws the lines. The figure should draw the entire canvas on every 'motion_notify_event' and on 'button_release_event' before disconnecting the callback ids, but only seems to be drawing certain artists and doesn't even draw the x or y axis. I have been able to get this plot working in a Tornado web application. I've tried tracing the fig.canvas.draw call to see if the artists list is empty, but it wasn't. I think somehow the browser end of the figure is only rendering the differences. example.html: {% load staticfiles %} <html> <head> <script type="text/javascript" src='https://cdnjs.cloudflare.com/ajax/libs/reconnecting-websocket/1.0.0/reconnecting-websocket.min.js'></script> <link rel="stylesheet" href="{% static 'css/page.css' %}"> <link rel="stylesheet" href="{% static 'css/boilerplate.css' %}"> <link rel="stylesheet" href="{% static 'css/fbm.css' %}"> <link rel="stylesheet" href="{% static 'jquery-ui-1.12.1/jquery-ui.min.css' %}"> <script src="{% static 'jquery-ui-1.12.1/external/jquery/jquery.js' … -
No module named 'psycopg2.extensions' despite having 'psycopg2-binary'
I am trying to develop a Django project leveraging psycopg2 but when i deploy in a Docker container on python:3.7.4-slim I was running into the 'no pg_config' issue, so I determined the best way to proceed after some digging is to go with psycopg2-binary since since that seems to be the recommended way to go forward. Only problem now is that when I try to run the command python manage.py <...> from local I'm getting the error: ModuleNotFoundError: No module named 'psycopg2.extensions' I'm not sure how to proceed, since psycopg2 works fine locally but we are going to end up containerizing this resource and having it sit in a k8s cluster so I was fairly certain the binary library was the right way to go. Has anyone figured out a solution to pull in psycopg2.extensions without sacrificing the integrity of using the binary distribution? Happy to provide more context as-needed. Thanks! -
Django AudioFile OS Error: No such file or directory
I am trying to implement the audio field into my django project, but when I try to upload a file I get this OS Error. Traceback: File "/usr/lib/python2.7/dist-packages/django/core/handlers/exception.py" in inner 41. response = get_response(request) File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in _legacy_get_response 249. response = self._get_response(request) File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "/usr/lib/python2.7/dist-packages/django/core/handlers/base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/usr/lib/python2.7/dist-packages/django/contrib/admin/options.py" in wrapper 551. return self.admin_site.admin_view(view)(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/views/decorators/cache.py" in _wrapped_view_func 57. response = view_func(request, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/contrib/admin/sites.py" in inner 224. return view(request, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/contrib/admin/options.py" in change_view 1511. return self.changeform_view(request, object_id, form_url, extra_context) File "/usr/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapper 67. return bound_func(*args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/utils/decorators.py" in _wrapped_view 149. response = view_func(request, *args, **kwargs) File "/usr/lib/python2.7/dist-packages/django/utils/decorators.py" in bound_func 63. return func.__get__(self, type(self))(*args2, **kwargs2) File "/usr/lib/python2.7/dist-packages/django/contrib/admin/options.py" in changeform_view 1408. return self._changeform_view(request, object_id, form_url, extra_context) File "/usr/lib/python2.7/dist-packages/django/contrib/admin/options.py" in _changeform_view 1448. self.save_model(request, new_object, form, not add) File "/usr/lib/python2.7/dist-packages/django/contrib/admin/options.py" in save_model 979. obj.save() File "/usr/lib/python2.7/dist-packages/django/db/models/base.py" in save 808. force_update=force_update, update_fields=update_fields) File "/usr/lib/python2.7/dist-packages/django/db/models/base.py" in save_base 848. update_fields=update_fields, raw=raw, using=using, File "/usr/lib/python2.7/dist-packages/django/dispatch/dispatcher.py" in send 193. for receiver in self._live_receivers(sender) File "/usr/local/lib/python2.7/dist-packages/audiofield/fields.py" in _rename_audio 222. os.rename(filename, dst_fullpath) Exception Type: OSError at /admin/products/product/20/change/ Exception Value: [Errno … -
Django ORM + Postgres + Enum Fields
(Django 2.2 + Latest Postgres) I am using Django Models with Enum Fields in this manner: from enum import Enum from django_enum_choices.fields import EnumChoiceField class DocumentType(Enum): SPREADSHEET = 'spreadsheet' PRESENTATION = 'presentation' In my Model class.... document_Type = EnumChoiceField(DocumentType, null=False) I migrate the model to Postgres, but I noticed there isn't any enum on the database side field definition. I could easily break the constraints of the enum by entering data directly into the DB via a query in an external tool like DataGrip. Isn't there any component that'll constrain the database as well to the enum i declared in my model? -
python: logging: can we added multiple filters to the logger and which one is considered
I am trying to understand how multiple Filters (one defined in config and other in the code) in Python logging work. I am working on a Django project and below is my logger config in settings.py My goal is to switch on and switch off the logger whenever i want. So using filters i am trying to switch off the logger by returning False (0) 1) Switch off the logger in the starting class StartFilter(object): def filter(self, record): """ Determine if the specified record is to be logged. Is the specified record to be logged? Returns 0 for no, nonzero for yes. If deemed appropriate, the record may be modified in-place. """ return 0 LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '%(levelname)s %(funcName)s() %(pathname)s[:%(lineno)s] %(name)s \n%(message)s' } }, 'handlers': { 'console': { 'level': 'DEBUG', 'formatter': 'verbose', 'class': 'logging.StreamHandler', }, }, 'filters': { 'myfilter': { '()': StartFilter, } }, 'loggers': { 'log_testing': { 'handlers': ['console'], 'level': 'DEBUG', 'propagate': False, 'filters': ['myfilter'] }, } } I have added the filter to the logger. 'filters': ['myfilter'] 2) Switch on and off the logger in the views.py file where i want the logging to be seen # to switch … -
Initial value not showing up in DecimalField
I have a form with a DecimalField and I have set the initial value like so: class RawProductForm(forms.Form): title = forms.CharField(label="") description = forms.CharField(required=False) price = forms.DecimalField(initial=199.99) However, the initial value is not showing up when I render the page: What could be the issue? -
Form variables inside templates
As far as I know in Django, if I want to pass the form variable inside the templates I use the {{ form }} tag. But in the code that I am following they put the variable as {{ answer_form }}. How is this all working, and would replacing the latter with form work? views.py class CreateAnswerView(LoginRequiredMixin, CreateView): form_class = AnswerForm template_name = 'qanda/create_answer.html' def get_initial(self): return { 'user': self.request.user.id, 'question': self.get_question().id, } def get_context_data(self, **kwargs): return super().get_context_data(question=self.get_question(), **kwargs) def get_success_url(self, form): return self.object.question.get_absloute_url() def form_valid(self, form): action = self.request.POST.get('action') if action =='SAVE': #save and redirect as usual return super().form_valid(form) elif action == 'PREVIEW': ctx = self.get_context_data(preview=form.cleaned_data['answer']) return self.render_to_response(context=ctx) return HttpResponseBadRequest() def get_question(self): return Question.objects.get(pk=self.kwargs['pk']) Part of the HTML(post_answer.html) <div class="col-sm-12" > <h3 >Post your answer</h3 > <form method="post" action="{% url "qanda:answer_question" pk=question.id %}" > {{ answer_form | crispy }} {% csrf_token %} <button class="btn btn-primary" type="submit" name="action" value="PREVIEW" >Preview </button > <button class="btn btn-primary" type="submit" name="action" value="SAVE" >Answer </button > </form > </div > -
How to fix "Django form validation unit test returns False value"
I have to customize a form, and had to add 4 drop-down to the existing form. Before adding the drop downs, my unit test cases form validation function returned “True” value. But after adding the drop-downs the function is returning “False”. I am not sure what exactly is the problem, can any one help me what is the exact issue. I use below function for unit testing... Form validation unit test function test.py: def test_form_is_valid(self): form = self.form_class(data=self.data, **self.get_form_kwargs()) self.assertTrue(form.is_valid()) My customize drop-down is below... <div class="col-md-6"> <div class="form-group"> <label class="control-label" for="id_management_fund_income">Management Fund Account *</label> <select name="management_fund_income" title="" required="" class="form-control" id="id_management_fund_income"> <option value="">---------</option> {% for mf in managementaccountlist %} <option value="{{ mf.pk }}" {% if mf.pk == setting_data.management_fund_income_id %}selected="selected" {% endif %}>{{ mf.code }}-{{ mf.name }}</option> {% endfor %} </select> </div> </div> My whole template(template.py) file is below... {% load bootstrap3 %} {% load tags %} <div class="ibox"> <div class="ibox-title"> <h5>Maintenance Invoicing Settings</h5> <div class="ibox-tools"> <a class="collapse-link"> <i class="fa fa-chevron-up"></i> </a> </div> </div> <div class="ibox-content"> <div class="row"> <div class="col-md-8"> <div class="row"> <div class="col-md-6"> {% bootstrap_field form.management_fee addon_before="$" %} </div> <div class="col-md-6"> {% bootstrap_field form.sinking_fund_contribution addon_before="$" %} </div> <div class="col-md-6"> <div class="form-group"> <label class="control-label" for="id_management_fund_income">Management Fund Account *</label> <select name="management_fund_income" title="" … -
Django: 'SafeText' object has no attribute 'as_widget'
In my django template form this works {{ form.content_previeiw.as_hidden }} But this gives error {{ form.content_previeiw.as_hidden|add_class:"post_content_previeiw" }} Error: 'SafeText' object has no attribute 'as_widget' What am I doing wrong? And how to solve it? -
how to construct condition in ValidationError
I have a model named Comments which has content=models.CharField(max_length=100) in forms I want to use "def clean_content" to raise validation error if user types characters exceeding max_length. So how to use if condition operator. def clean_content(self): content = self.cleaned_data.get("content") if ????????? < 100: return content else: raise forms.ValidationError(('You exceeded max number of character')) -
Using .ttf font file in Pillow within a django app hosted on Heroku
I am setting up my first web application via the Django framework. This application takes data supplied by an html form and generates an image using Pillow. this image features text drawn on top of it, and I would like to use a particular .ttf file when generating the text. The font is used just fine when I run the app locally (via manage.py runserver), however, when running on Heroku an "OSError" occurs as it "cannot open resource". Location of font file in directories. scales is the Django root folder. scales1 is a package I wrote containing image generation logic. The scales_app folder contains the view for which the image is generated. scales/AGENCYB.ttf scales/scales1/AGENCYB.ttf scales/static/fonts/AGENCYB.ttf scales/scales_app/AGENCYB.ttf The Heroku app builds just fine and can be visited via web browser. https://guit-proj-1.herokuapp.com/scales/SelectBoard Clicking the "Gen Board" button will elicit the traceback below. Note that the application was fully functional when the default font for pillow was used. However, the font did not look acceptable for my application. I have tried placing the font file in all places where it might be relevant including the root directory of the Django app, the python package where the image generation logic is stored, and in … -
Validating a modelformset with a restricted queryset
I'm trying to validate a modelformset with a queryset filtered on one field having a specific value, where any added forms need to have that specific value set. I'm a relative beginner with Django and hoping there will be a 'standard' answer to my requirement, which I feel can't be that unusual. I have three models (for the purposes of this question) - Project, Stage and Check. The constraint is that there may only be at most one Check for each combination of Project and Stage. At the model level this is met by: class Meta: constraints = [models.UniqueConstraint(fields=['project', 'stage'], name="project-stage"),] where project and stage are ForeignKey fields in the Check model, and this works. I have a view with a modelformset that shows all Checks for a given Project. The view queryset is models.Check.objects.filter(project__id=pk) where pk is an integer from the url (eg project/1/). In the ModelForms, the project field is excluded because it's fixed and the user doesn't need to see it in each form. Thus it's not available in the form data, cleaned or otherwise, and I have to insert it myself. I'm inserting the correct value for project_id in the view: if request.method == 'POST': formset …