Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Spanning relationships
I have the following models: class User(AbstractUser): pass class Employer(models.Model): company_name = models.CharField(max_length=100, ...) ... class Employee(models.Model): employee_name = models.OneToOneField(User, unique=True) employer = models.ForeignKey(Employer) ... class Psa(models.Model): owner = models.ForeignKey(Employer) ... Each Employer owns several Psa's. Employees of a given Employer should be able to view all Employer owned Psa's. I'm able to write a query that get's the employer_id from the request: def get_queryset(self, *args, **kwargs): employee = Employee.objects.get(employee_name_id = self.request.user.id) employer = employee.employer With this id I can query Psa in the python shell to get the correct list of Psa's for the logged in user. What I don't understand is how to write the query set so that generic views (ListView, DetailView...) return a filtered Psa list. I know this must be incredibly obvious but after several day's of mucking about and reading everything I can find on SO / Django, I'm lost. -
TypeError reverse() got an unexpected keyword argument 'kwarg'
Working on making a blog in Django Python. Got this error: TypeError at /posts/3/edit/ reverse() got an unexpected keyword argument 'kwarg' Request Method: POST Request URL: http://127.0.0.1:8000/posts/3/edit/ Django Version: 1.11.4 Exception Type: TypeError Exception Value: reverse() got an unexpected keyword argument 'kwarg' Exception Location: C:\Users\winkl\Desktop\trydjango19\src\posts\models.py in get_absolute_url, line 22 Python Executable: C:\Users\winkl\Desktop\trydjango19\Scripts\python.exe Python Version: 3.6.1 C:\Users\winkl\Desktop\trydjango19\src\posts\views.py in post_update def post_update(request, id=None): instance = get_object_or_404(Post, id=id) form = PostForm(request.POST or None, instance=instance) if form.is_valid(): instance = form.save(commit=False) instance.save() # message success return HttpResponseRedirect(instance.get_absolute_url()) ... context = { "title": instance.title, "instance": instance, "form":form, } C:\Users\winkl\Desktop\trydjango19\src\posts\models.py in get_absolute_url def __unicode__(self): return self.title def __str__(self): return self.title def get_absolute_url(self): return reverse("posts:detail", kwarg={"id": self.id}) ... #return "/posts/%s/" %(self.id) C:\Users\winkl\Desktop\trydjango19\src\posts\urls.py urlpatterns = [ #url(r'^$', views.post_home), url(r'^$', views.post_list), url(r'^create/', views.post_create), #name='create' url(r'^(?P<id>\d+)/$', views.post_detail, name='detail'), url(r'^(?P<id>\d+)/edit/', views.post_update, name='update'), url(r'^delete/', views.post_delete), } -
Django REST Framework: Serialize and write related field
class Foo(models.Model): a = models.CharField(max_length=100, blank=False, null=False) class Bar(models.Model): b = models.ForeignKey(Foo, on_delete=models.CASCADE) And i want to create a serializer that validates a Foo object with a list of Bar's, something like this { "a": "1", "b": [ { "1", "2", "3"}, { "1", "6", "3"} ] } What is the best way to serialize them together using ModelSerializer? and how to WRITE them like this (POST inserting both Foo and his Bars) -
JSONResponse outoupt a dictionary element containing another dictionary to be formatted differently in django
The application is working fine but the UX designer wants a different output in the JSON response. Currently, the output is like this: { "detail": { "password_current": [ "Current password is incorrect." ] } } He insisted on having it like this: { "detail": { "password_current": "Current password is incorrect." } } The output, coming from JSONResponse is constructed like this: errors={"password_current":"Current pasword is incorrect"} reply['detail']=errors return JSONResponse(reply,status=200) I have several responses made up that way and i am hoping for a simpler/shorter solution. Any ideas? -
django template engine extends "base.html fails base.html in own file template in other
I have the following structure as far as project django blog <---root templates base.html __init__.py settings.py etc etc.py posts migrations templates post-detail.html post-list.html post-form.html in my post-detail.html I have {% extends"base.html" %} To which I receive the following error: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: /home/rickus/Documents/softwareProjects/webFullStack/djangoBlog/src/djangoblog/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/rickus/Documents/softwareProjects/webFullStack/djangoBlog/src/local/lib/python2.7/site-packages/django/contrib/admin/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/rickus/Documents/softwareProjects/webFullStack/djangoBlog/src/local/lib/python2.7/site-packages/django/contrib/auth/templates/base.html (Source does not exist) django.template.loaders.app_directories.Loader: /home/rickus/Documents/softwareProjects/webFullStack/djangoBlog/src/djangoblog/posts/templates/base.html (Source does not exist) Error during template rendering In template /home/rickus/Documents/softwareProjects/webFullStack/djangoBlog/src/djangoblog/posts/templates/post_form.html, error at line 1 my template engine is set up like this in my settings: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], #join templates folder to root (base) Directory of project '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', ], }, }, ] I am really not sure what is going on here. My understanding is that the template engine as it is set in the settings is to go to the root folder of my project, grab all the templates, and then go though all my apps and grab the templates too. Shouldn't this work? -
Fetching id's of all the distinct records in django
Suppose we have a table with multiple records. Each record contains an awb number.There are some duplicate awb number. I want to filter out all the distinct awb numbers with corresponding id's so that i can exclude all the distinct awb numbers on the basis of their id's from table to swipe out the redundant data. what i am trying is following and not leading me any where: a= x.objects.filter(customer_id = 6).values('awb')distinct() but this is only giving me awb and can't use this to reduce redundancy. if i pass .values('awb','id') then also i fail as it says all the records are unique with this combination. -
Sharing data between requests to the same view in django
I have a simple view in django class SimpleView(View): def get(self, *args, **kwargs): c = C() c.m() class C: def m(self): x = # get from an external server if not set I would like to share x across different requests to SimpleView For example, let's consider the following scenario: Someone#1 requests get to SimpleView. x is not set up, so it will be fetched from an external server. Someone#2 requests get to SimpleView. x is set up, so it won't be fetched from an external server. I know that that piece of code doesn't do it. I know what is a global variable. But, I don't know how to share data between different requests. I don't want to use a database to store it (because of the optimization)- the value x don't have to be persistent. Please note that it will be great if that method to sharing something be a thread-safe (it is not neccessary, I deal with it). How to do it? (django 1.6) -
open a WebSocket connection in django chat app
i want to add a chatting application to my Django website (hosted by web faction), so a follow this example : Django channels chat and use the Django channels along with WebSocket make a one-to-one chatting app. But i got this error: WebSocket connection to 'ws://gadgetron.store/Pchat/' failed: Unexpected response code: 404 =========== src/chatbot/settings.py CHANNEL_LAYERS = { "default": { "BACKEND": "asgiref.inmemory.ChannelLayer", "ROUTING": "chatbot.routing.routing",},} src/chatbot/routing.py from channels.routing import route, include from Pchat.routing import routing as chat_routing routing = [include(chat_routing, path=r"^/Pchat"),] src/Pchat/engine.py import json from django.dispatch import receiver from django.utils.translation import ugettext as _ from django.utils.module_loading import import_string from channels.sessions import channel_session from channels import Group from . import messages from . import conf @channel_session def on_connect(message): payload = message.content['text'] message.channel_session['user'] = payload['username'] message.reply_channel.send(messages.system(_('Welcome to the chat!'))) Group('chat').send(messages.system(_('User %(username)s joined chat') % payload)) Group('chat').add(message.reply_channel) @channel_session def on_disconnect(message): Group('chat').discard(message.reply_channel) Group('chat').send(messages.system(_('User %(user)s left chat') % message.channel_session)) @channel_session def on_message(message): payload = message.content['text'] message = messages.info(payload['text'], user) Group('chat').send(message) def get_engine(): return import_string(conf.CHAT_ENGINE) src/Pchat/routing.py from channels.routing import route from channels.sessions import channel_session from .message_router import get_router from .engine import get_engine router = get_router() engine = get_engine() routing = [ route("websocket.receive", channel_session(router.handle_receive)), route("websocket.disconnect", channel_session(router.handle_disconnect)), route("chat.connect", engine.on_connect), route("chat.message", engine.on_message), route("chat.command", engine.on_command), route("chat.disconnect", engine.on_disconnect),] static/js/PP_chat_index.js $(window).load(function() { $messages.mCustomScrollbar(); setTimeout(function() { … -
Django finding non-existent changes to a model after each migration
After running python manage.py migrate, Django will consistently return: Running migrations: No migrations to apply. Your models have changes that are not yet reflected in a migration, and so won't be applied. Run 'manage.py makemigrations' to make new migrations, and then re-run 'manage.py migrate' to apply them. Hmm that's funny, I don't remember making a change. python manage.py makemigrations --dry-run --verbosity=3 Generated by Django 1.11 on 2017-0x-xx xx:xx from __future__ import unicode_literals from django.db import migrations, models import django_cryptography.fields class Migration(migrations.Migration): dependencies = [ ('myApp', '0019_auto_xxxxxxx_xx'), ] operations = [ migrations.AlterField( model_name='myModel', name='encrypted_field', field=django_cryptography.fields.encrypt(models.CharField(verbose_name=models.CharField(verbose_name=models.CharField(max_length=50, verbose_name='Encrypted Field')))), ), migrations.AlterField( model_name='myModel', name='second_encrypted_field', field=django_cryptography.fields.encrypt(models.CharField(verbose_name=models.CharField(verbose_name=models.CharField(max_length=50, verbose_name='Second encrypted field')))), ), ] That would be fine, but the exact same AlterField() was run in 0018_auto. I've tested it out on a couple systems, even tried making these migrations for real and applying but, but the warning keeps coming back in 0020_auto. myModel.__str__ does reference one of those encrypted fields, which I think is what's causing the recursion in the migration. Still, I can't understand why that would make Django keep picking them up. Any idea what could be causing this? Is it a bug? Something having to do with the nature of django_cryptography? Something else? -
How to runserver on a command prompt, Django?
I have Django installed, so I do not know why this is coming up. If I just type in py it gives me my default version of python (3.6, Anaconda). What do I need to do in order to verify that my Django system works. In other words I need this to come up in my command prompt But Thiis is what I am receiving Thanks! -
Why does Case/When ungroup the results of my values() annotate() query?
I have a conditional query question. I've been reading https://docs.djangoproject.com/en/1.11/topics/db/aggregation/ and https://docs.djangoproject.com/en/1.11/ref/models/conditional-expressions/ and can't seem to figure this out. Let's say I have an Order model, and I want a payment breakdown grouped by user. Here's the Order model: class Order(models.Model): CASH = 'c' CARD = 'a' PAYMENT_TYPES = ( (CASH, 'Cash'), (CARD, 'Card'), ) user = models.ForeignKey(User, on_delete=models.PROTECT, null=True, blank=True) payment_type = models.CharField(max_length=1, choices=PAYMENT_TYPES) grand_total = models.DecimalField(max_digits=8, decimal_places=2) Here's a values() + annotate() query showing me the total per user: query = Order.objects.values( 'user' ).annotate( total=Sum('grand_total'), ) The result, so far so good: User Total -------------- User 1 300 User 2 250 However, when I add Case/When conditions to the query: query = Order.objects.values( 'user' ).annotate( cash=Case(When(payment_type=Order.CASH, then=Sum('grand_total')), default=Value(0)), card=Case(When(payment_type=Order.CARD, then=Sum('grand_total')), default=Value(0)), total=Sum('grand_total'), ) I get this result, which is not what I want: User Cash Card Total ---------------------------------- User 1 300 0 300 User 2 200 0 200 User 2 0 50 50 Of course, this is what I want: User Cash Card Total ---------------------------------- User 1 300 0 300 User 2 200 50 250 Why is the Case/When undoing the GROUP BY that values() is giving me? Note: The Order model doesn't have default ordering, but just … -
Django application on passenger shows empty home page
In my local environment, which is run by python manage.py runserver I can visit normally the application home in my http://localhost:8000 On passenger, I can work with some endpoints of my system in the remote domain, but I cannot access http://my.domain.com/ or http://my.domain.com. It shows a blank page, as in my local environment I can normally see the home. I then created another endpoint to show my home, to check static files and so, like: http://localhost:8000/h In passenger I can normally see http://my.domain.com/h as my home page, but I cant really make it work to see the home page in the root of the domain (as in any other website): http://my.domain.com In my url's I tried many, but no success. My django project is in public folder. And this is the folder structure I have for passenger. /path/to/project/public /path/to/project/passenger_wsgi.py /path/to/project/tmp/restart.txt How can I make this home work in http://my.domain.com? Welcome any help -
Django REST Framework - Best way to serialize related objects with Model Serializer and validate objects
Let's say that i have these two models: class Foo(models.Model): a = models.CharField(max_length=100, blank=False, null=False) class Bar(models.Model): b = models.ForeignKey(Foo, on_delete=models.CASCADE) And i want to create a serializer that validates a Foo object with a list of Bar's, something like this { "a": "1", "b": ["1", "2", "3"] } What is the best way to serialize them together using ModelSerializer? And also, how can i make the b list mandatory for every object? -
Django application inheritance from external package
I have a small package called my-tiny-framework with consist of one small django project with one app called main. I have another django project, which installs my-tiny-framework through pip and also has app called "main" and some other applications. Is there way to extend app from my-tiny-framework to override all their modules? For example i want to extend AppConfig from my-tiny-framework. Is there a elegant way to achieve this without registrating both applications (main from my-tiny-framework and main from my_project)? -
Datatable sort by date correctly
I'm using Django framework for my web site but to show info I use the plugin Datatable so one column show date info, the format that is used to show the date is like May. 6, 2017 so when I sort the date column the order as string and not date so the first date to show is like August 10, 2017 Is there a way to sort by date using that format? -
How to properly define a middleware class in Django v1.11?
I'm working on Django (v1.11) project and need to provide some middleware functionality to the site. This version of Django modify old MIDDLEWARE_CLASSES setting as described in docs: A new style of middleware was introduced for use with the new MIDDLEWARE setting. However, I can't understand how NEW middleware works. After reading the middleware's documentation I come to the following conclusion: class FooMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): return self.get_response(request) def process_template_response(self, request, response): # do something here return response I thought that it'll work, but unfortunately code above doesn't work and completely ignored by Django (without any error!). When change the code as follows everything works: from django.utils.deprecation import MiddlewareMixin class FooMiddleware(MiddlewareMixin): def process_response(self, request, response): # do something here return response But! The MiddlewareMixin is related to the deprecation utils and used for compatibility purposes: Django provides django.utils.deprecation.MiddlewareMixin to ease creating middleware classes that are compatible with both MIDDLEWARE and the old MIDDLEWARE_CLASSES. Question: How to properly define a middleware class in Django v1.11? -
Django Queryset Replace 'None' Values
Let say I have a query set that returns this: <QuerySet [{'key': None}, {'key': 'FIXED INCOME'}]> However, I want to replace the None with something else like N/A. What is the easiest way to do this? -
unbound method is_valid() must be called with UserLoginForm instance as first argument (got nothing instead)
Hello guys anyone with an idea help to solve this error, I am using Django framework to develop a simple application using Class based views. Here is my View Codes: class OpenLogin(FormView): template_name = 'signin.html' form_class = UserLoginForm def post(self, request, *args, **kwargs): form = self.form_class next_url = self.request.GET.get('next') if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') obj = authenticate(username=username, password=password) if obj is not None: if obj.is_active(): login(self.request, obj) if next_url is not None: return HttpResponseRedirect(next_url) else: return HttpResponseRedirect(reverse('index')) else: messages.error(self.request, 'Error! sorry account is not active') return HttpResponseRedirect(reverse('signin')) else: messages.error(self.request, 'Error!, sorry account is not found') return HttpResponseRedirect(reverse('signin')) else: messages.error(self.request, 'Sorry! an error occurred, try again') context = { 'title': 'Sign In', 'next_url': next_url, 'messages': messages.get_messages(self.request), 'user': self.request.user, 'form':form, } return context And Here is my form Class: class UserLoginForm(forms.Form): username = forms.CharField(max_length=User._meta.get_field('email').max_length) password = forms.CharField(min_length=6, max_length=16, widget=forms.PasswordInput()) def is_valid(self): valid = super(UserLoginForm, self).is_valid() if not valid: return valid try: user = User.objects.get( Q(username=self.cleaned_data['username']) | Q(email=self.cleaned_data['username']) ) except User.DoesNotExist: self._errors['no_user'] = 'User does not exist' return False if not check_password(self.cleaned_data['password'], user.password): self._errors['invalid_password'] = 'Password is invalid' return False return True After submitting the form I end up with the following error: unbound method is_valid() must be called with … -
How to update Celery Task ETA?
I am building simple waiting list app in Django 1.10.3 using Celery 4.1.0. I have following base tasks: @shared_task def start_user_counter(): logging.info('Task executed @ {}'.format(datetime.datetime.utcnow())) # This task is executed when user reaches the Top of the queue. # Send email, perform other stuff in here ... @shared_task def update_queue(): curr_time = datetime.datetime.utcnow() logging.info('Task called @ {}'.format(curr_time)) time_to_exec = curr_time + datetime.timedelta(seconds=10) # Here, perform checks if task already exists in Redis # if it does not exist - create a new one and store it to Redis # if it does exist - update task's ETA. task_id = start_user_counter.apply_async(eta=time_to_exec) logging.info('Task ID: {}'.format(task_id)) ... update_queue.delay() Each task represents one user on the waiting list. New user will be assigned ETA when he is suppose to be removed from the waiting list (he reached the top at the ETA). However, each user has also a possibility to speed up the time when he will reach the top of the waiting list. Question: How I can update ETA of already existing celery.Task so it execcutes earlier than it was first anticipated? -
Dajngo Template Render
I make an AJAX request by selecting options. But, (.html) file renders somewhere unavailable. All the pages must be rendered in one main (.html) file. But the third page causes a problem. I use DJANGO. This is my basic page. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Teacher</title> </head> <body> <p>Menu</p> <ul> <li><a href={% url 'diary' %}>Diary</a></li> <li><a href="teacher_schedule">Schedule</a></li> </ul> {% block teacher_diary %}{% endblock %} {% block teacher_subjects %}{% endblock %} </body> </html> This my second page {% extends 'teacher/teacher.html' %} {% load staticfiles %} {% block teacher_diary %} <script language="JavaScript" src="http://ajax.googleapis.com/ajax/libs/jquery/1.10.0/jquery.min.js"> </script> <script type="text/javascript"> $(document).ready(function(){ $('#grade_list').change(function(){ var element = document.getElementById("grade_list"); var value = element.options[element.selectedIndex]; $.ajax({ url: "get_subject/", type: "get", data: { 'grade_id': value.getAttribute("pk") }, dataType: "json" }); })}); </script> <select id="grade_list"> {% for grade in grades %} <option pk={{ grade.pk }}>{{ grade }}</option> {% endfor %} </select> {% endblock %} And the third page which should be rendered under the second page. {% extends 'teacher/teacher.html' %} {% block teacher_subjects %} <select> {% for subject in subjects %} <option>{{ subject }}</option> {% endfor %} </select> {% endblock %} And python code from django.shortcuts import render from electronic_diary.models import Subject # Create your views here. def render_teacher_diary(request): grades = {} … -
Django formset custom render error: ManagementForm data is missing or has been tampered with
I have a simple formset: TextAdFormset = formset_factory(TextAdForm, formset=BaseFormSet, max_num=3) if request.method == "POST": form = CampaignForm(request.POST) text_ad_formset = TextAdFormset(request.POST) if form.is_valid() and text_ad_formset.is_valid(): .... else: form = CampaignForm() text_ad_formset = TextAdFormset() which is being rendered customly in the template: <form action="" method="POST">{% csrf_token %} {{ text_ad_formset.management_form }} {% for text_ad_form in text_ad_formset.forms %} {{ text_ad_form.headline1 }} {% endfor %} </form> Error I get: ValidationError at / [u'ManagementForm data is missing or has been tampered with'] Debugging: My code WORKS PERFECTLY with one form. It doesn't work with 2/3 forms in the formset I inspected html and TOTAL FORMS are being correctly updated by {{ management_form}} Django version 1.11 Any ideas how I could debug this problem ? -
Django - Disable Editing for Existing Forms in Formset but Allow Editing in New Forms
How do I make form fields in a model formset disabled when the forms already exist and just need a couple columns updated, but make those same fields editable when a new form is added to the formset by the user? models.py: from django.db import models from django.utils import timezone class MyModel(models.Model): idno = models.CharField(max_length=20) date = models.DateTimeField(default=timezone.now) entity = models.CharField(max_length=50) logic = models.CharField(max_length=100) choices = ( ('1', 'Choice1'), ('2', 'Choice2'), ('3','Choice3'), ) choices = models.CharField( max_length=20, choices=choices, null=True, ) comment = models.CharField(max_length=500, null=True) def __str__(self): return self.idno forms.py: from .models import MyModel from django.forms import modelformset_factory, ModelForm class MyForm(ModelForm): class Meta: model = MyModel fields = '__all__' def __init__(self, *args, **kwargs): super(MyForm, self).__init__(*args, **kwargs) self.fields['idno'].disabled = True self.fields['date'].disabled = True self.fields['entity'].disabled = True self.fields['logic'].disabled = True MyFormSet = modelformset_factory(MyModel, extra=1, exclude=(), form=MyForm) views.py: from django.shortcuts import render from django.http import HttpResponseRedirect from .models import Alert from .forms import AlertFormSet from django.contrib import messages def index(request): newAlerts = MyModel.objects.filter(choices__isnull=True) modelformset = MyFormSet(request.POST or None, queryset=newAlerts) context = {'modelformset':modelformset} if request.method == 'POST': for form in modelformset: if form.is_valid(): if form.has_changed(): form.save() idno = form.cleaned_data['idno'] entity = form.cleaned_data['entity'] messages.success(request, 'idno %s for %s was saved' % (idno, entity)) return HttpResponseRedirect('/') return … -
Use text both as Safetext and in url in Django
Suppose I want to convert the string [[w'ord]] into the link <a href="example.com?q=w'ord">w'ord</a> Since input can be anything, I want to make it safe by applying conditional_escape (so, before making link I apply conditional_escape and string becomes [[w&#39;ord]]). But in this case ' becomes unapplicable for the link because of the ampersand. How can make the word safe for the html output and safe in the link? Thank you. -
django for loop not rendering
I have just started learning django. I am facing issues while rendering the html inside for loop. Please find for your reference the HTML Code and Python code that is passing context to the same index.html {% load staticfiles %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'bootstrap.min.css' %}" /> <link rel="stylesheet" href="{% static 'style.css' %}" /> <title>TreasureGram</title> </head> <body> <nav class="navbar navbar-default navbar-static-top text-center"> <a href="/"> <img src="{% static 'images/logo.png' %}" alt="TreasureGram"> </a></nav> <main class="container" role="main"> <div class="treasure panel panel-default"> <% for treasure in treasures %> <div class="panel-heading"> <h2 class="panel-title">{{ treasure.name }}</h2> </div> <div class="panel-body"> {{ treasure.material }} <p>{{ treasure.value }}</p> </div> <% endfor %> </div> </main> </body> </html> views.py from django.shortcuts import render from django.http import HttpResponse # Create your views here. def index(request): context = {'treasures': treasures} ##A context is a dictionary that maps template variable names to Python objects. return render(request, 'index.html', context) ##We can pass context as a third variable to our render() function ##We can access the values in context by their keys class Treasure: def __init__(self, name, value, material, location): self.name = name self.value = value self.material = material self.location = location treasures = [Treasure('Gold Nugget', 500.00, 'gold', "Curly's Creek, NM"), Treasure("Fool's … -
Understanding Django ForeignKey relationships in inline formsets
I am building a simple app around firewall policy change requests. I am having a hard time understanding how I should setup my models and forms so that a rule request can be made all in one view. Here is a simplified version of my models and forms to get to the root of the issue. I am using a few foreign keys from RuleRequest to Address as this is my understanding of how to do a One-to-Many relationship in that a RuleRequest can have many source and destination Address's but an Address will only have one RuleRequest. # Models class Address(CreatedUpdatedModel): ipv4_address = IPAddressField(null=True) class RuleRequest(CreatedUpdatedModel): sources = models.ForeignKey(Address, related_name='rule_requests_source', null=True) destinations = models.ForeignKey(Address, related_name='rule_requests_destination', null=True) # Forms class AddressForm(BootstrapMixin, forms.ModelForm): class Meta: model = Address fields = [ 'ipv4_address' ] class RuleRequestForm(BootstrapMixin, forms.ModelForm): sources = inlineformset_factory(RuleRequest, Address, AddressForm, fk_name='rule_requests_source') destinations = inlineformset_factory(RuleRequest, Address, AddressForm, fk_name='rule_requests_destination') class Meta: model = RuleRequest fields = [ 'sources', 'destinations', ] As of now, I get: ValueError: 'firewall.Address' has no field named 'rule_requests_source'.