Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django- distinct doesn't work on order by
I have 2 models as follows: class Chat(models.Model): name = models.CharField(max_length=20) class ChatMessage(models.Model): chat = models.ForeingKey(Chat, related_name="messages") text = models.TextField() created = models.DateTimeField(auto_now_add=True) I want to get all chats order by last message created datetime. Some chats may not have messages, so I want to be at the end of the list. I tested following ways: 1- chats = Chat.objects.all().order_by(F('messages__created').desc(nulls_last=True)).distinct() 2- chats = Chat.objects.all().order_by('-messages__created').distinct() 3- chats = Chat.objects.all().annotate(last_message=Max("messages__created").order_by("-last_message") ways 1 and 2 return duplicate values. way 3 return non-duplicate date but chats with no message are on the top of the list. I want to be at the end of the list. -
Django search returns an empty value
def book(request): books = Library.objects.all() form = ChoiceFilterForm(data=request.GET or None) if form.is_valid(): filter_choice = form.cleaned_data['filter_choice'] books = books.filter(category=filter_choice) if filter_choice == 'null': books = Library.objects.all() query = request.GET.get('search') if query and query != '': result = Library.objects.filter(Q(title__icontains=query)).distinct() else: result = Library.objects.all() context = {'books': books, 'form': form, 'result': result, 'query': query} return render(request, 'book.html', context) I am new to django and I want to make a search bar. Program doesn't return an error message but the search bar shows nothing. What is my mistake here? -
how to implement CI/CD for Django project on AWS Lightsail from Bitbucket
I am trying to implement a Bitbucket CI/CD pipeline to deploy my Django project which is already deployed on AWS lightsail. after two hours of searching, I found a lot of information but none of them are exactly like my case. I have a few questions: 1- how to write a .yml file for my project that is already deployed on lightsail? 2- how to choose between codedeploy, jenkins, and other proposed tools for deploying and testing? 3- lots of articles are talking about EC2 but I'm using lightsail, is there the same configuration? a doc or tutorial for writing docker file for django project and yml file would be perfect. -
TypeError: 'NoneType' object is not iterable While Decleare Context Processor in Django Project
I want to pass a context value without rendering a page, that's why I implemented context processor. But when I return a context value from that function it showing me this error. here is my code for payment.py: def payment_url(request): todays_date = date.today() now = datetime.datetime.now() mcnt_TxnNo = "Txn" + str(todays_date.year) + str('{:02d}'.format( todays_date.month)) + str(todays_date.day) + str(now.hour) + str(now.minute) + str('{:02d}'.format(now.second)) order_no = "ON" + str(todays_date.year) + str('{:02d}'.format( todays_date.month)) + str(todays_date.day) + str(now.hour) + str(now.minute) + str('{:02d}'.format(now.second)) secret_key = b"***" print(mcnt_TxnNo) if request.method == 'POST': name = request.POST["clientName"] phone = request.POST["phone"] address = request.POST["address"] email = request.POST["clientEmail"] product_name = request.POST["proName"] print("product Name", product_name) paid = request.POST["paid"] print(name) string = "***" print(string) byte_string = bytes(string, 'utf-8') hash_code = hmac.new(secret_key.upper(), byte_string, hashlib.sha256) hash_text = hash_code.hexdigest() print(hash_text) jsonObj = { // json object } json_string = json.dumps(jsonObj) print(json_string) url = "**" headers = {'Content-type': 'application/json', 'Accept': 'text/plain'} r = requests.post(url, data=json_string, headers=headers) print(r.json()) j = r.json()['status'] k = r.json()['data'] if j == "200": payment_id = k['payment_id'] redirect_url = k['redirect_url'] payment_link = str(redirect_url) + "?" + str(payment_id) print(payment_link) return {'payment_link': payment_link} else: return {} And my setting.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', … -
Cripsy forms prepend is not showing up anywhere in the DOM
I am using this forms.py file and I want to prepend an icon to my field with Django Crispy Forms, but when I run this nothing appears on the screen. I have done everything that I could and nothing I research is helping. It is not even appearing anywhere in the DOM. In my html template inside a form element I am doing {{ form|materializecss }} and I have brought in the crispy forms tags {% load crispy_forms_tags %} {% crispy UpdateProfileForm %} as well. Whats wrong with this code? Why isn't it putting an icon before my profile_picture file input field? from crispy_forms.bootstrap import PrependedText from crispy_forms.helper import FormHelper from crispy_forms.layout import Layout from django import forms from django.forms.models import ModelForm from django.forms.widgets import TextInput class UpdateProfileForm(ModelForm): class Meta: model = UserInformation fields = [ 'profile_picture', ] def __init__(self, *args, **kwargs): super(UpdateProfileForm, self).__init__(*args, **kwargs) # this is for crispy forms self.helper = FormHelper() self.helper.layout = Layout( PrependedText('profile_picture', '<i class="material-icons">photo</i>'), ) -
Django - how to combine multiple filter parameters together, where the number of parameters is variable
I'm trying to implement a search function on Django. If my query is: "a b c", then I want to to search : select * from table where col LIKE '%a%' and col LIKE '%b%' and col LIKE '%c%' I see I can do that with table.objects.filter(col__icontains('a')) But how do I make this work for a,b & c. I can't hard-code the number of parameters. There might be a,b,c,d or any number of search terms.? -
How to create Django database custom user fields creation problem. Use User.objects.create_user()
I create a custom user information field on django. But on admin database hobby and bio field not create. myuser = User.objects.create_user(username, email,password) myuser.hobby = friendid myuser.first_name = "sami" myuser.last_name = "khan" myuser.bio = "khanann" myuser.save() And my model.py class User(AbstractUser): hobby = models.CharField(max_length=113) bio = models.TextField() admin.py @admin.register(User) class CoreAdmin(admin.ModelAdmin): list_display = ("id", "first_name", "last_name") i also make migrate my database. -
Rest API Requests drop on Django framework
There are some web services developed in python and Django framework in Windows server Also, Waitress serves Django In addition, Nginx has chosen as a web server, but Django is not served on Nginx there are some problems when users are more than 80 per seconds First of all: Requests not queued and receive sadly and periodic (It seems they are buffering) Second: Many requests dropped Failed to establish a new connection: [WinError 10061] No connection could be made because the target machine actively refused it -
Using the URLconf defined in projectname.urls, Django tried these URL patterns, The current path, appname/tablename/add/, didn't match any of these
When I deploying a Django project, I find this error: The error after deploying project This error didn't appear in localhost and everything is fine in the localhost. I do many solutions in static and media files but still doesn't work. Hint: This error come only with tables that contain the image field. project/app/urls.py from django.urls import path from .views import * from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', IndexView.as_view(), name='index'), path('aboutus/', AboutUsView.as_view(), name='aboutus'), path('blogs/<int:pk>', BlogsView.as_view(), name='blogs'), path('blogdetail/<int:pk>', BlogDetailView.as_view(), name='blogdetail'), path('blogdetail/', BlogDetailView.as_view(), name='comment'), path('blogsearch/', SearchBarView.as_view(), name='search'), path('contactus/', ContactUsView.as_view(), name='contactus'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) setting.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Example of table that contain image field: enter code here class Blog(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200, unique=True) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='media/images', default='images/defualt_blog.png', blank=True) short_content = models.TextField(max_length=200) content = RichTextField() category = models.ForeignKey('Category', on_delete=models.CASCADE) status = models.BooleanField(default=False) recipe = models.ForeignKey('Recipes', on_delete=models.SET_NULL, null=True, blank=True) date_created = models.DateTimeField(auto_now_add=True) class Meta: ordering = ['-date_created'] verbose_name_plural = 'المدونة' def __str__(self): return self.title The files structures: Project/ --- db.sqlite --- manage.py --- app/ --- migration/ --- admin.py --- apps.py --- model.py --- urls.py --- views.py --- Projectname/ … -
Django - How to get parameters from PUT request?
I set the URL like this: path('voucher/<str:voucher>', views.update_voucher.as_view()) Here is my code: class update_voucher(generics.GenericAPIView): @swagger_auto_schema(......) @logging_code def put(request, voucher): voucher_id = voucher request_data = json.loads(request.body) My request: http://0.0.0.0:6001/voucher/125 Body: {"custimer_id": 123} When running it, I got this error: TypeError at /voucher/125 put() got multiple values for argument 'voucher' Request Method: PUT Request URL: http://0.0.0.0:6001/voucher/125 Django Version: 3.1.4 Exception Type: TypeError Exception Value: put() got multiple values for argument 'voucher' Exception Location: /code/leadtime/logger.py, line 9, in func_wrapper Python Executable: /usr/local/bin/python Python Version: 3.9.0 Python Path: ['/code', '/usr/local/lib/python39.zip', '/usr/local/lib/python3.9', '/usr/local/lib/python3.9/lib-dynload', '/usr/local/lib/python3.9/site-packages'] Server time: Sun, 31 Jan 2021 05:27:46 +0000 Since, I am the beginner, it would be nice if you can give me both solution and explanation. Thanks -
WagtailAdminPageForm and URL not saving in admin or passing to page
I have a quick script that parses a JSON response from an API and adds it to a WagtailAdminPageForm, like so: """Flexible page.""" from django.db import models import requests from django import forms from wagtail.admin.edit_handlers import FieldPanel from wagtail.core.models import Page from wagtail.core.fields import RichTextField from wagtail.images.edit_handlers import ImageChooserPanel from wagtail.admin.forms import WagtailAdminPageForm def get_mp3_choices(): response = requests.get('https://api.somexamplepage.com') response.raise_for_status() jsonResponse = response.json() jsonResponse['results'][0]['audio'] mp3_list = [] return [ (key['audio'], key['title']) for key in jsonResponse['results'] ] class FlexPageForm(WagtailAdminPageForm): audioUrl = forms.ChoiceField(choices=get_mp3_choices) class Meta: label = 'Select Audio for Player' class FlexPage(Page): """Flexibile page class.""" template = "flex/flex_page.html" # @todo add streamfields # content = StreamField() base_form_class = FlexPageForm subtitle = models.CharField(max_length=100, null=True, blank=True) Flexbody = RichTextField(blank=True) bannerImage = models.ForeignKey( "wagtailimages.Image", null=True, blank=True, on_delete=models.SET_NULL, related_name="+" ) content_panels = Page.content_panels + [ FieldPanel("subtitle"), FieldPanel('Flexbody', classname="full"), ImageChooserPanel('bannerImage'), ] class Meta: # noqa verbose_name = "Flex Page" verbose_name_plural = "Flex Pages" The code works well and I'm able to see the returned list of MP3's within my admin panel. The problem, the selected MP3 is not being preserved when I save the page and, when I look in the sqlite table, I'm not seeing any record of the audioUrl. The following fields do show. page_ptr_id … -
why i'm getting this error 'dict' object has no attribute '_meta'
code in views.py file def settings(request): if not request.user.is_authenticated: return redirect('login') context = {} if request.POST: form = AccountUpdateForm(request.POST, instance=request.user) if form.is_valid(): form.save() else: form = AccountUpdateForm( instance={ 'email': request.user.email, 'username': request.user.username, 'light_theme': request.user.light_theme } ) context['account_form'] = form return render(request, 'account/account.html', context) code in forms.py file variable light_theme is BollenFiled I made it to make it eye-friendly to night-time user and select light-theme if they want class AccountUpdateForm(forms.ModelForm): class Meta: model = Account fields = ('username', 'email', 'light_theme') def clean_username(self): if self.is_valid(): email = self.cleaned_data['email'] try: account = Account.objects.exclude(pk=self.instance.pk).get(email=email) except Account.DoesNotExists: return email raise forms.ValidationError('email "%s" is already in use.' % email) def clean_email(self): if self.is_valid(): username = self.cleaned_data['username'] try: account = Account.objects.exclude(pk=self.instance.pk).get(username=username) except Account.DoesNotExists: return username raise forms.ValidationError('Username "%s" is already in use.' % username) code in account.html {% extends 'base.html' %} {% block content %} <h2 style="color:blue;">Account settings</h2> <form method="post"> {% for filed in account_form %} <p> {{ filed.label_tag }} {{ filed }} {% if filed.help_text %} <small style="color:blue;">{{ filed.help_text }}</small> {% endif %} </p> {% end for %} {% for filed in account_form %} {% for error in filed.error %} <p style="color:red;">{{ error }}</p> {% endfor %} {% endfor %} {% if account_form.non_filed_error %} <div style="color:red;"> … -
Render Django login form using django.contrib.auth.urls
I am following this document for implementing the authentication mechanism. Having trouble with rendering the form at begging using this code. It only renders when the form was first submitted, form object was created. How to render form from the auth.urls? #This is not working, it duplicates the base_generic.html, and form input fields are not rendered. {% if user.is_authenticated %} # {% else %} {% include 'registration/login.html'%} {% endif %} https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Authentication {% extends "base_generic.html" %} {% block content %} {% if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {% if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access.</p> {% else %} <p>Please login to see this page.</p> {% endif %} {% endif %} <form method="post" action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{ form.username.label_tag }}</td> <td>{{ form.username }}</td> </tr> <tr> <td>{{ form.password.label_tag }}</td> <td>{{ form.password }}</td> </tr> </table> <input type="submit" value="login" /> <input type="hidden" name="next" value="{{ next }}" /> </form> {# Assumes you setup the password_reset view in your URLconf #} <p><a href="{% url 'password_reset' %}">Lost password?</a></p> {% endblock %} -
Django: Adding monthly goal for products model, and daily production
I'm sorry if my question seems weird, I'll try to explain: I'm building an app for my family's company, there are some products, and every month I need to set a goal for each product for each user. I also need each user to be able to submit how much they've sold of each product every day I'm confused about the approach I should use to relate all of these What I've done is created models for the Products, for the goals and for 'production' (how much they've sold that day) First, I put each product as field in the 'Production' model, but that wouldn't allow me to change anything using the admin panel So, how can use the Products models in the Production models as "fields". ex: class ProductsModel(models.Model):#This is the form each worker is supposed to fill every day, Worker is set accordingly to logged in user Worker = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, on_delete=models.SET_NULL) ProductsModel1 = models.FloatField()#How much they've sold of this product ProductsModel2 = models.FloatField()#How much they've sold of this product I'd like to do this for as many Products as there are And for the goals, this is what would be ideal: class GoalsModel(models.Model):#This is me or the … -
Which version of Django to start learning as a beginner in 2021?
I've decided to learn Django. But as a beginner, it seems overwhelming seeing the different versions of it. Which version should I choose to learn first so that I have a solid understanding actually how it works? 3.xx or 2.xx or 1.xx? How much different are these three versions of Django? -
vue+django+graphql:has been blocked by CORS policy
the question is 'has been blocked by CORS policy: Response to preflight request doesn't pass access control check: Redirect is not allowed for a preflight request.' I use Django+Graphql and I can get the data through postman。 enter image description here In order to solve the cross domain problem of Django, I have done the following work 1.install django-cors-headers pip install django-cors-headers 2.Add “corsheaders” to the list of installed apps in the settings.py file 3.Add “corsheaders.middleware.CorsMiddleware” to the middleware list in the settings.py file 4.Add CORS_ALLOW_METHODS and CORS_ALLOW_HEADERS But in the front end of Vue, cross domain problems are encountered enter image description here Here is my configuration django/setting.py from pathlib import Path # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '08ux)8987i4d#7^@4a-e3y601*rwhl)zdpl=5#te4f8#!eh(_5' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # app 'company', # graphql 'graphene_django', # cors 'corsheaders', ] 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', … -
How to make element active in sidebar which is in django include tag through javascript?
I have made sidebar in sidebar.html and had include it in main.html as well as dashboard.html through django include tag to reduce data reduntancy-> {% include 'employee/sidebar.html' %} {% block content %} {% endblock %} Now how do I make different elements (in sidebar) active according to the different pages? Like for example, When I am on dashboard.html , dashboard should be active in sidebar. -
How does social-auth-app-django work with jinja2?
I'm using: python 3.7 Django 2.2.13 social-auth-app-django 3.1.0 I'm considering moving from django templates to jinja2. Most of it makes sense, but it's not clear how the social-auth part would work. In my settings for the DjangoTemplates backend, I've got: 'social_django.context_processors.backends', 'social_django.context_processors.login_redirect', but the django docs say, "Using context processors with Jinja2 templates is discouraged." So, are these context managers not needed with jinja? -
How to create/update ManytoManyField-related Models
I have been trying lotta solutions (mostly depreciated) on multiple sites but can't manage to make it working in my script : I have two models Product and MyClient : class Product(models.Model): tdpcode = models.IntegerField(null=True) name = models.CharField(max_length=50, null=False) prange = models.CharField( max_length=8, choices=PRODUIT_RANGE, default='TDP') desc = models.TextField(blank=True) unitweight = models.IntegerField(null=True) pcperctn = models.IntegerField(null=True) img = models.ImageField(null=True, blank=True, upload_to="images/") pc = models.FloatField(null=True) palletization = models.ForeignKey( Palletization, default=DEFAULT_PALLETIZATION_ID, on_delete=models.CASCADE, null=True) countryban = models.ManyToManyField(Country, blank=True) status = models.CharField( max_length=10, choices=PRODUIT_STATUS, default='active') date = models.DateField(auto_now_add=True) updatedate = models.DateField(auto_now=True) def __str__(self): return self.name and class MyClient(models.Model): class Meta: ordering = ['clientname'] clientname = models.CharField(max_length=50, null=False) channel = models.CharField( max_length=18, choices=CLIENT_TYPE, default='Distributor') logoimg = models.ImageField(null=True, blank=True, upload_to="client/") incoterm = models.CharField( max_length=3, choices=INCOTERM, default='EXW') country = models.ForeignKey( Country, default=DEFAULT_COUNTRY_ID, on_delete=models.CASCADE, null=True) clientbuy = models.ManyToManyField( Product, blank=True, related_name='myclient') date = models.DateField(auto_now_add=True) updatedate = models.DateField(auto_now=True) When I create/update a new client : I can select the products from MultipleSelectField, on submit, it is working fine. However, I would like to do the same when I create/update a new item, I would like to be able to tick which client will potentially buy it among my full list of client MyClient.objects.all() Please help to indicate where is my issue? … -
Django generic view fields for reverse relationship
I may just be having issues reading the documentation but I can't figure out if this is impossible or I just don't know how to make it work. I'm trying to use a generic UpdateView, and include a reverse relationship in fields to show all of the cars a user has. View: class User_Detail_View(LoginRequiredMixin, UpdateView): model = User template_name = "User/User_Detail.html' fields = ['email', 'cars_set'] User.models: class Cars(models.Model): User = models.ForeignKey('User', on_delete=models.Set_NULL, null=True) Car_Name = models.CharField(max_length=256, unique=True) class User(models.Model): email = models.EmailField(_('email_ address'), unique=True) I'm getting a django.core.exceptions.FieldError: Unknown field(s) (cars_set) specified for User. I can access this reverse relationship via user.cars_set.all() in the shell, so I know the relationship works. I can also show normal fields on the page if I remove the offending reverse field. Any ideas if this is possible or not? Being able to use the generic view would be quite handy. -
Django Model Constraints
I have the following models from django.db import models class league(models.Model): name = models.CharField(max_length=64) def __str__(self): return f"{self.name}" class player(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=128) age = models.IntegerField() position = models.CharField(max_length=1) nteam = models.CharField(max_length=128) def __str__(self): return f"{self.id} {self.name} {self.age} {self.position} {self.nteam}" class team(models.Model): name = models.CharField(max_length=64) league = models.ForeignKey(league, null=True, blank=True, on_delete=models.CASCADE, related_name="teams") roster = models.ManyToManyField(player, blank=True, related_name="rosters") def __str__(self): return f"{self.name} {self.league}" My goal would be to have many different leagues, each league containing multiple teams. I want a player only to be added to one team in a league. Right now I created a league, add several teams, then added players to each team. As of now I can take a player and add to all the teams in the same league if I want. How would you add a constraint so that once a player has been added to a team, they can no longer be added to another team in the same league? -
Best way to use Django with Scrapy
I started using Django a few months ago since I switched from PHP to Python, and I started working on a small project and I would like to know the best way to let Django communicate with Scrapy. It's possible to make a Rest Api between Django App and Scrapy App? What is the best way? -
Django unable to render my template because it is unable to find my url. This only happens with url patterns from one of my apps
Django is unable to load my template because "NoReverseMatch at /books/outlines/20 " This issue lies within a link in the template: <a href="{% url 'test'%}" class="type">New Blank Outline</a> Here is my outlines/urls.py from django.urls import path from .views import Dashboard from . import views as outline_views urlpatterns = [ path('<int:pk>/', outlines_views.outline, name='url-outline') path('blank/<int:storyPk>', outline_views.newBlankOutline, name='url-blankOutline'), path('test/', outline_views.testView, name = 'test') ] urlpatterns += staticfiles_urlpatterns() Here is the testView: def testView(request): return render(request, 'outlines/test.html') Here is the outline view: def outline(request, pk): context = { 'storyPk': pk } return render(request, 'outlines/outline.html', context) The django error tells me: NoReverseMatch at /books/outlines/20 Reverse for 'test' not found. 'test' is not a valid view function or pattern name. The weird thing is, if I change the url name in the template to a url name from another app's urls.py file, it renders the template no problem. Any idea why it can't find the url? -
Run Django in root and phpMyAdmin in apach2
I want to serve my Django app from mysite.com and PHPMyAdmin from mysite.cm/phpmyadmin. So I have tried some methods to achieve so with modwsgi. It's / directory seems to take precedence over all directories. How can I set up my apache config to get expected output? I don't want to run my project in a subdirectory, instead, PHPMyAdmin should be in a subdirectory. Here is my apache config. ... <Directory /home/tareq/djproject/config> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess djapp python-path=/home/tareq/djproject python-home=/home/tareq/djproject/dj_env WSGIProcessGroup djapp WSGIScriptAlias / /home/tareq/djproject/config/wsgi.py Alias /phphmyadmin /var/www/html/phpmyadmin <Directory /var/www/html/phpmyadmin> Options Indexes FollowSymLinks MultiViews AllowOverride all Order Deny,Allow Allow from all </Directory> </VirtualHost> I tried placing WSGIScriptAlias top and bottom, no change. But everything works just fine if I use WSGIScriptAlias anything other than /. This settings throws error 404 by django app when I visit mysite.com/phpmyadmin -
clearing and seeding database from endpoint in django
I'm trying to set up a rest API that can be cleared and then have the data in my postgres db re-seeded via an endpoint. I'm doing this with Django with json data in a fixtures file, executing a series of functions in my views. This has worked great so far, but now I'm trying to add data with foreign key fields. models.py: class Profile(models.Model): name = models.CharField(max_length = 100) profile_name = models.CharField(max_length = 100) email = models.CharField(max_length = 100) def __str__(self): return self.name class Post(models.Model): title = models.CharField(max_length = 250) body = models.TextField(max_length = 4000) profile = models.ForeignKey(Profile, on_delete = models.CASCADE) def __str__(self): return self.title class Comment(models.Model): title = models.CharField(max_length = 200) body = models.TextField(max_length = 1000) profile = models.ForeignKey(Profile, on_delete = models.CASCADE) post = models.ForeignKey(Post, on_delete = models.CASCADE) def __str__(self): return self.title in views.py def seed(request): Profile.objects.all().delete() reset(Profile) for profile in all_profiles: add_profile(profile) Post.objects.all().delete() reset(Post) for post in all_posts: add_post(post) Comment.objects.all().delete() reset(Comment) for comment in all_comments: add_comment(comment) return HttpResponse('database cleared and seeded') def add_profile(new_profile): profile_instance = Profile.objects.create(**new_profile) profile_instance.save() def add_post(new_post): post_instance = Post.objects.create(**new_post) post_instance.save() def add_comment(new_comment): comment_instance = Comment.objects.create(**new_comment) comment_instance.save() def reset(table): sequence_sql = connection.ops.sequence_reset_sql(no_style(), [table]) with connection.cursor() as cursor: for sql in sequence_sql: cursor.execute(sql) some example seed …