Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to sort sentence according only first letter [duplicate]
If two words are starting with the same character then the same order of the words should be maintained from the original sentence. It is follow only first character or word This is my code st='this is an impossible task' sts=st.split() sts.sort() print(sts) Output ['an', 'impossible', 'is', 'task', 'this'] I want to this output how to get this output an is impossible this task -
Django not setting csrftoken cookie
I am writing a Django app that uses Django-hosts for the subdomains. I have the main app running (currently on localhost) and I have set CSRF_COOKIE_DOMAIN = ".localhost". However when I run localhost:8000/admin/, there is no csrftoken cookie set, same as when I run api.localhost:8000/<slug>. When I remove the setting, both subdomain endpoints get a different csrftoken which doesn't work when I make an AJAX request using the localhost endpoint to api.localhost endpoint. Is there a setting I am missing? I have tried removing the setting, and using *.localhost to no avail -
Django forms data retrieving and updating problem
I've four fields in my models.py file. class Item(models.Model): product_name = models.CharField(max_length=100) quantity = models.IntegerField() size_choice = ( ('S', 'Short'), ('M','Medium'), ('L','Long') ) size = models.CharField(max_length=30, choices=size_choice) date = models.DateField() And this is my forms.py file: class ItemForm(ModelForm): class Meta: model = Item widgets = {'date':DateInput()} fields = ['product_name','quantity'] As I'm taking two fields only so it will display only two fields in my additem.html file: <form action="" method="post"> {% csrf_token %} {{ form }} <button type="submit">Add</button> </form> </div> In my itemlist.html file I can retrieve 'product_name' and 'quantity' from database as it is being saved from additem.html file. But in this itemlist.html file I've created two more inputs for 'size' and 'date'. So from here i want to update data into database(all four coulmns). Updating two fileds is fine but how will i update 'size' and 'field' from itemlist.html file. {% for neww in all %} <tr> <td>{{ neww.product_name }}</td> <td>{{ neww.quantity }}</td> <td><input type="text" value="{{ neww.size }}"</td> /* This */ <td><input type="text" value="{{ neww.date }}"</td> /* and this i want to update from here */ <td><a href="{% url 'update_item' neww.id %}">Edit</a> My update.html file: <form action="" method="POST"> {% csrf_token %} {{ form }} <input type="submit" value="Update"> </form> My … -
Use Django Admin Widgets on any given page
This is not a duplicate! Alle the older questions either do not work, or are simply outdated. According to the Django documentation https://docs.djangoproject.com/en/3.2/topics/forms/media/ The Django Admin application defines a number of customized widgets for calendars, filtered selections, and so on. These widgets define asset requirements, and the Django Admin uses the custom widgets in place of the Django defaults. The Admin templates will only include those files that are required to render the widgets on any given page. If you like the widgets that the Django Admin application uses, feel free to use them in your own application! They’re all stored in django.contrib.admin.widgets. Here is my forms.py: from django import forms from django.contrib.admin.widgets import AdminDateWidget, AdminTimeWidget from .models import Category, Event class AntragForm(forms.Form): user = forms.CharField() day = forms.DateField(widget=AdminDateWidget(), label="Datum", required=True) category = forms.ModelChoiceField( queryset=Category.objects.all() ) start_time = forms.TimeField(widget=AdminTimeWidget(), label="Start", required=False) end_time = forms.TimeField(widget=AdminTimeWidget(), label="Ende", required=False) whole_day = forms.BooleanField(label="Ganztag", required=False) private = forms.BooleanField(label="Privat", required=False) whole_week = forms.BooleanField(label="Ganze Woche", required=False) summary = forms.CharField(label="Grund", required=False) description = forms.CharField(widget=forms.Textarea, label="Beschreibung", required=False) and here's the part of the template: <div class="row"> <div class="col"> {{ form.day|as_crispy_field}} </div> </div> I also tried without crispy-fields, but it doesn't render either, so that's not the problem. It simply … -
Customizing Django login template
I'm new to Django and I want to use my custom login page instead of the ugly looking django login template. How could I make it work? I think I need to edit the urls.py file and override the login template but I don't know how to do it. Thanks -
Django Inline formsets always invalid
I am struck with inline formsets in Django. Each time I submit the formset it is considered invalid and hence the data doesn't get saved. I am a newbie in full-stack development and am learning Django. I am following Dennis Ivy's playlist on youtube and coding along with him. It is kind of an E-commerce portal where people can order stuff. Here is a link to the video where he implements inline formsets Video. It was working fine when I accepted orders through normal form i.e. one order at a time. I have done exactly as he did in his video. I also tried consulting my friends who are learning with me and also asked my mentor about it but no one could figure out what is wrong here. I browsed through the documentation but that too didn't help. Please help me out in fixing this. Github Repo link views.py from django.forms import inlineformset_factory def createOrder(request, pkCrteOrder): OrderFormSet = inlineformset_factory(customer, order, fields=('product','status'), extra=7) CustomerOrderOwner = customer.objects.get(id=pkCrteOrder) formSet = OrderFormSet(queryset = order.objects.none(), instance=CustomerOrderOwner) if(request.method == 'POST'): print("post request detected") formSet = OrderFormSet(request.POST, instance=CustomerOrderOwner) if formSet.is_valid(): formSet.save() return(redirect('/')) else: print("formset was invalid") context = {'formSet': formSet} return(render(request, 'accounts/orderForm.html', context)) Brief explaination: From … -
Edited form not getting saved in django
I've fixed almost everything, the form opens and I can make the edits but as soon as I make the edits and click on save, this shows up: I don't understand what's wrong. I did the same thing for my edit profile page and it worked perfectly there so I don't understand why it's not working here. views.py: class EditComplaint(UserPassesTestMixin, UpdateView): model = Complaint fields = ('reportnumber', 'eventdate', 'event_type', 'device_problem', 'manufacturer', 'product_code', 'brand_name', 'exemption', 'patient_problem', 'event_text', 'document') template_name = 'newcomplaint.html' def form_valid(self, request): complaint = request.user.complaint form = ComplaintForm(instance=complaint) if request.method == 'POST': form = ComplaintForm(request.POST, request.FILES, instance=complaint) if form.is_valid(): form.save() context = {'form': form} return render(request, 'newcomplaint.html', context) def test_func(self): complain = self.get_object() if self.request.user == complain.user: return True raise Http404(_('This complain does not exist')) What seems to be wrong? I think I need to change something in my views because everything else seems to work well so I'm not including anything else. But i don't understand what needs to be changed -
How to add a custom download path to downloaded files in django admin?
I have written some snippet to download datas from a model from default django admin. It works and csv file with name "some.csv" is downloaded to root project foler in my local machine. But what i want is customise the dir to new specific folder for eg ( C:\downloads). Also I am hosting it to heroku and I want the clients to see the downloads in their download folder. How to do that in both production and my local?? My model: class Booking(models.Model): name = models.CharField(max_length=100,blank=True) email = models.EmailField(blank=True) phone = models.CharField(max_length=50, blank=True) model = models.CharField(max_length=100, choices=Model,blank=True) # message = RichTextField(blank=True, null=True) location = models.CharField(max_length=50, blank=True) sent_at = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class Meta: ordering = ('sent_at',) My admin.py: def download_csv(modeladmin, request, queryset): f = open('some.csv', 'w') abc = csv.writer(f) abc.writerow(["name", "email", "phone", "model"]) for s in queryset: abc.writerow([s.name, s.email, s.phone, s.model]) class BookingAdmin(admin.ModelAdmin): def delete(self, obj): return format_html('<a class="btn-btn" href="/admin/core/booking/{}/delete/">Delete</a>', obj.id) def edit(self, obj): return format_html('<a class="btn-btn" href="/admin/core/booking/{}/edit/">Change</a>', obj.id) list_display = ('name', 'email', 'phone', 'model','edit','delete') list_display_links = ('name',) icon_name = 'folder_open' actions = [download_csv] admin.site.register(Booking,BookingAdmin) -
how to implement test case for logout in Django?
I am trying to test the logout bypassing the username and password, but it is getting failed. Can anyone help from django.contrib.auth import logout from django.test import TestCase class BasicTest(Testcase): def test_logout(self): request = { 'data' : { 'username': 'admin', 'password': 'admin' } } logout(request) Error: request.session.flush() AttributeError: 'Session' object has no attribute 'flush' Thanks! -
View is getting rendered in the Network Preview tab Django
I have created the logon form in Django which working properly. However in the Network tab I am able to view the Form and for other views like GET request the form is getting rendered with prepopulated data. Am I missing something or doing something wrong. Below is the screenshot and login form code. {% extends "base.html" %} {% load crispy_forms_tags %} {% block content %} <div class="content-section col-md-6"> <form method="POST" autocomplete="off"> {% csrf_token %} <fieldset class="form-group"> <legend class="border-bottom mb-4">Log In</legend> {{ form|crispy }} </fieldset> <div class="form-group"> <button class="btn btn-outline-info" type="Submit">Login</button> </div> </form> <div class="border-top pt-3"> <small class="text-muted"> </small> </div> </div> {% endblock content %} logon_form_in_network_tab -
What is the best and stable ODM for mongodb and django?
I want to connect django to mongodb but what is the best ODM for this issue? Djongo or mongoengine ? -
CSS is only applying on few html files and not rest
So i am building a personal website and am using Materialize for web designing. At first it was good and my pages look good, but then I added some new pages and i found that the css is not applied in these new pages, can anybody help me in solving this. Actually both are same pages(categories.html) but the path are different. header.html (main html file, have not changed the name yet) <<!DOCTYPE html> <html> <head> <meta charset="utf-8"> <!--Import Google Icon Font--> <link href="https://fonts.googleapis.com/icon?family=Material+Icons" rel="stylesheet"> <!--Import materialize.css--> <link type="text/css" rel="stylesheet" href="static/main/materialize.css" media="screen,projection"/> </head> <body> {% load static %} {% include "main/includes/navbar.html" %} {% include "main/includes/messages.html" %} <main> <div style="background-image: url('https://www.google.com/url?sa=i&url=https%3A%2F%2Fwallpapersafari.com%2Fw%2FcU6JWo&psig=AOvVaw1eBAulQvnXOrIK1yQueVX5&ust=1623841457736000&source=images&cd=vfe&ved=0CAIQjRxqFwoTCPje9_--mfECFQAAAAAdAAAAABAD')"> <div class = "container"> <br> {% block content %} {% endblock %} </div> </div> </main> {% include "main/includes/footer.html" %} <script type="text/javascript" src="static/main/materialize.js"></script> </body> </html> views.py from django.shortcuts import render, redirect from django.http import HttpResponse from .models import Item, ItemSeries, ItemCategory from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import login, logout, authenticate from django.contrib import messages from .forms import NewUserForm def single_slug(request, single_slug): categories = [c.category_slug for c in ItemCategory.objects.all()] if single_slug in categories: matching_series = ItemSeries.objects.filter(item_category__category_slug=single_slug) series_urls = {} for m in matching_series.all(): part_one = Item.objects.filter(item_series__item_series=m.item_series).earliest("item_update") series_urls[m] = part_one.item_slug return render(request, "main/category.html", … -
Saving HTML form data all at once
I want to save HTML data using request.POST method all at once instead of column by column. But it is giving me error because of crsf token. I am using templates so I can't use Django Forms views.py @require_http_methods(["POST"]) def save_add_user(request): error="" message="" data=request.POST first_name=data.get('first_name') last_name=data.get('last_name') username=data.get('username') email=data.get('email') password=data.get('password') phone=data.get('phone') address=data.get('address') user_type=data.get('usertype') try: user=CustomUser.objects.create_user(username=username, email=email,password=password,user_type=user_type) #user=CustomUser.objects.create(**data) #gives me error unexpected argument 'csrfmiddlewaretoken' #user=CustomUser.objects.create_user(**data) #gives me error username not defined user.save() CustomUserDetails.objects.create(user=user, phone=phone,address=address,first_name=first_name,last_name=last_name) message='User Added Succesfully' except: error='Failed to add user' return render(request,'internal/add_user.html',{'messages':message,'error':error,}) -
Forum button only works when I am authenticated but returns NoReverseMatch at /forum/ Reverse for '' not found. '' when i'm not logged in
I'm having a lot of trouble with this. I don't understand why the same "Forum" button works when I'm logged in and redirects me to the forum page. However, it returns this when I'm not authenticated: NoReverseMatch at /forum/ Reverse for '' not found. '' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/forum/ Django Version: 3.1.11 Exception Type: NoReverseMatch Exception Value: Reverse for '' not found. '' is not a valid view function or pattern name. Here is my layout.html which home.html extends from: <body> <nav class="nav d-flex flex-row justify-content-between nav-fill navbar-expand-lg navbar-dark bg-dark sticky-top container-fluid" style=""> <div class="first"> <a class="navbar-brand mr-4 ml-4" href="#"><b>My Site</b></a> <a class="nav-item nav-link text-light" href="{% url 'home' %}">Home</a> <a class="nav-item nav-link text-light" href="{% url 'forum:index' %}">Forum</a> {% if user.is_authenticated %} <a class="nav-item nav-link text-light" href="{% url 'users_list' %}">Find New Buddies</a> </div> {% block searchform %}{% endblock searchform %} <div class="second"> <a class="nav-item nav-link text-light" href="{% url 'post-create' %}">Create Post</a> <a class="nav-item nav-link text-light" href="{% url 'my_profile' %}">Profile</a> <a class="nav-link dropdown-toggle text-light" href="#" id="navbarDropdownMenuLink" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Messaging</a> <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <a class="dropdown-item" href="{% url 'postman:inbox' %}">Inbox{% if unread_count %} <strong>({{ unread_count }})</strong> {% endif %}</a> <a class="dropdown-item" href="{% … -
Is there any module in python for web development?
I want to do web development in python and in a very simple language. Kindly suggest me some modules for web development in python. -
django 404 when loading admin but not local pages when deployed to heroku
I have just deployed my Django application to Heroku, All my locally saved apps load fine but not the django admin page # mysite/urls.py from django.contrib import admin from django.urls import path, include from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('', include('home.urls')), path('api/', include('api.urls')), path('admin/', admin.site.urls), # ... ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When I go to the home page it loads and the same for all other URLs, except for the admin page at https://myapp.herokuapp.com/admin and you get the following error. -
Django query to fetch top performers for each month
I need to fetch the top performer for each month, here is the below MySql query which gives me the correct output. select id,Name,totalPoints, createdDateTime from userdetail where app=4 and totalPoints in ( select max(totalPoints) FROM userdetail where app=4 group by month(createdDateTime), year(createdDateTime)) order by totalPoints desc I am new to Django ORM. I am not able to write an equivalent Django query which does the task. I have been struggling with this logic for 2 days. Any help would be highly appreciated. -
Can't seem to understand where I'm going wrong
I am working on a django project that accepts complains from users: models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber views.py: def History(request): complaint_data = Complaint.objects.filter(user=request.user) context = { 'complaint':complaint_data } return render(request, 'myHistory.html', context) class EditComplaint(UserPassesTestMixin, UpdateView): model = Complaint fields = ('reportnumber', 'eventdate', 'event_type', 'device_problem', 'manufacturer', 'product_code', 'brand_name', 'exemption', 'patient_problem', 'event_text', 'document') template = 'newcomplaint.html' def form_valid(self, request): complaint = request.user.complaint form = ComplaintForm(instance=complaint) if request.method == 'POST': form = ComplaintForm(request.POST, request.FILES, instance=complaint) if form.is_valid(): form.save() context = {'form': form} return render(request, 'newcomplaint.html', context) def test_func(self): complain = self.get_object() if self.request.user == complain.user: return True raise Http404(_('This complain does not exist')) template for my-history: <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">My Complaints</h1> <p class="all-comp-txt">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do … -
In my Django Models How can I create an Auto field which stores an id with format 'AAA BBB CCCC' (I also want to make this field as primary key)
In my Django Models, I want to create a custom field called 'facility_id' which will be storing in my database table column a unique facility_id for every registered facility using a format 'AAA BBB CCCC', where AAA,BBB, and CCCC are just mere random numbers. I intend to format this field because it will be used by people in a form, so I want it to look better and formatted, otherwise I would have simply used the default AutoField shown below. (Am too new in django & python, so pardon my simple question) Below is my autofield which I want to format, kindly help: class Facilities(models.Model): ... facility_id = models.AutoField(primary_key=True) # I want store this in form 'AAA BBB CCCC' ... -
What seems to be wrong with my code in django?
urls.py: urlpatterns = [ .... path('My-History/', accounts.views.History, name='MyHistory'), path('Complaint/<int:id>/edit', accounts.views.EditComplaint.as_view(), name='Complaint') ] views.py: def History(request): complaint_data = Complaint.objects.filter(user=request.user) context = { 'complaint':complaint_data } return render(request, 'myHistory.html', context) class EditComplaint(UserPassesTestMixin, UpdateView): model = Complaint fields = ('info', 'reportnumber', 'eventdate', 'event_type', 'device_problem', 'manufacturer', 'product_code', 'brand_name', 'exemption', 'patient_problem', 'event_text', 'document') def form_valid(self, request): complaint = request.user.complaint form = ComplaintForm(instance=complaint) if request.method == 'POST': form = ComplaintForm(request.POST, request.FILES, instance=complaint) if form.is_valid(): form.save() context = {'form': form} return render(request, 'newcomplaint.html', context) def test_func(self): complain = self.get_object() if self.request.user == complain.user: return True raise Http404(_('This complain does not exist')) models.py: class Complaint(models.Model): user = models.ForeignKey(User, on_delete= models.CASCADE, null = True, blank=True) id = models.AutoField(blank=False, primary_key=True) reportnumber = models.CharField(max_length=500 ,null = True, blank= False) eventdate = models.DateField(null=True, blank=False) event_type = models.CharField(max_length=300, null=True, blank=True) device_problem = models.CharField(max_length=300, null=True, blank=True) manufacturer = models.CharField(max_length=300, null=True, blank=True) product_code = models.CharField(max_length=300, null=True, blank=True) brand_name = models.CharField(max_length = 300, null=True, blank=True) exemption = models.CharField(max_length=300, null=True, blank=True) patient_problem = models.CharField(max_length=500, null=True, blank=True) event_text = models.TextField(null=True, blank= True) document = models.FileField(upload_to='static/documents', blank=True, null=True) def __str__(self): return self.reportnumber template for my-history: <div class="col-lg middle middle-complaint-con"> <i class="fas fa-folder-open fa-4x comp-folder-icon"></i> <h1 class="all-comp">My Complaints</h1> <p class="all-comp-txt">Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor … -
Serializing Django simple history items the same way as the main model
I am trying to work with Django rest framework in conjunction with Django simple history. This answer has gotten me pretty far with understanding how to serialize the history items of a model. This works well for simple cases, but my model has a calculated field ("store" in the example below). The problem is that the the serialization of the history field doesn't seem to capture these. How to I serialize the history in the same way as the main model? Is it possible to do this in the to_representation method of the HistoricalRecordField? class MyModel(models.Model): ... history = HistoricalRecords() @property def store(self): return {} class HistoricalRecordField(serializers.ListField): child = serializers.DictField() def to_representation(self, data): return super().to_representation(data.values()) class MySerializer(serializers.ModelSerializer): ... store = serializers.DictField(child=serializers.CharField(), read_only=True) history = HistoricalRecordField(read_only=True) class Meta: model = MyModel -
You're accessing the development server over HTTPS, but it only supports
enter image description here enter image description here -
AttributeError: 'WSGIRequest' object has no attribute 'app'
I'm building a dashboard with these commands on a local machine and then copy it to the remote server: cd ~/repos/fork/saleor-dashboard git checkout 2.11.1 npm14 --verbose install export API_URI="https://api.mydomain.com/graphql/" export GTM_ID="GTM-K9ZZ3R8" npm14 run build ls build/dashboard/ scp -i ~/Documents/webserver-key-pair.pem -r build/dashboard ec2-user@3.1.16.71:/srv/www/mydomain/ The dashboard is available online. But when I log in with a valid user/pass, the Saleor API throws these errors, visible by sudo journalctl -xe: File "/home/ec2-user/repos/fork/saleor/saleor/graphql/utils/__init__.py", line 128, in get_user_or_app_from_context return context.app or context.user graphql.error.located_error.GraphQLLocatedError: 'WSGIRequest' object has no attribute 'app' ERROR saleor.graphql.errors.unhandled A query failed unexpectedly [PID:8388:Thread-108] ... File "/home/ec2-user/repos/fork/saleor/saleor/graphql/utils/__init__.py", line 128, in get_user_or_app_from_context return context.app or context.user AttributeError: 'WSGIRequest' object has no attribute 'app' ... File "/home/ec2-user/repos/fork/saleor/saleor/graphql/utils/__init__.py", line 128, in get_user_or_app_from_context return context.app or context.user AttributeError: 'WSGIRequest' object has no attribute 'app' What could be the cause? Thanks! =) -
Nginx problem when i enabled the file by linking to the sites-enabled dir
my gorgeous friends on the internet. I was doing something about Nginx for deploying my app made by Django, Postgresql, Gunicorn, Nginx, and DigitalOcean. First of all, The project name in the Github gist is btre_project, but my app's project name is pfc_calc. Considering the name dif, I created project folder by coping and pasting the line on the gist. sudo nano /etc/nginx/sites-available/pfc_calc And, copy the code and paste it into the file I just made. server { listen 80; server_name 104.248.152.6; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/djangoadmin/pyapps/pfc_calc; } location /media/ { root /home/djangoadmin/pyapps/pfc_calc; } location / { include proxy_params; proxy_pass http://unix:/run/gunicorn.sock; } } BUT, here is where I made a mistake and got an error I was so foolish that I forgot to change btre_project to pfc_calc sudo ln -s /etc/nginx/sites-available/btre_project /etc/nginx/sites-enabled Because I noticed that mistake, I typed this line again. sudo ln -s /etc/nginx/sites-available/pfc_calc /etc/nginx/sites-enabled I thought it would be ok and my mistake was under the bridge, but it wouldn't. When I typed this line sudo nginx -t this error below showed up. nginx: [emerg] open() "/etc/nginx/sites-enabled/btre_project" failed (2: No such file or directory) in /etc/nginx/nginx.conf:62 nginx: configuration … -
How to improve tests for models with multiple foreign keys (Django)
I have a MVP for my testing suite, but my current style will be a beast to maintain. I am running into trouble efficiently writing tests for my model which has two Foreign Keys. I include my model.py file and my test.py file below: models.py class Category(models.Model): name = models.CharField(max_length=100) class Product(models.Model): name = models.CharField(max_length=100) class ProductCategoryValue(models.Model): value = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name="categories") product = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="products") class Meta: unique_together = [['category', 'product']] (The idea behind this model structure is that there can be a list of products and a list of categories, with the ProductCategoryValue to serve as the glue between the two lists. The list of categories may change later on in the project and I would like to easily modify the values of each product text with respect to that category. I am open to suggestions to improve this model structure as well!) test.py #... def setUp(self): p = Product(name="Touchscreen") p.save() Product.objects.create(name="Dancer") c = Category(name="Use Case", selection_type="bullets") c.save() Category.objects.create(name="Video Conferencincg", selection_type="text") Category.objects.create(name="Multisite", selection_type="Boolean") ProductCategoryValue.objects.create(value="foobar", product=p, category=c) Is this the canonical way of writing tests for models which have multiple foreign keys? I'm hoping that there is a more efficient way so that my testing …