Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Testing in django
I have a problem with testing. It's first time of writing test for me. and I got a problem. I just created a test folder inside my app users. and test_urls.py for testing the urls. when I type python manage.py test users It says: Creating test database for alias 'default'... Got an error creating the test database: database "database_name" already exists Type 'yes' if you would like to try deleting the test database 'database_name', or 'no' to cancel: What does It mean? What does happen if I type yes? Do I lose all my data in database? -
Creating a "soft" or "dummy" ForeignKey id in Django
I have a model, such as the one below: class MammalianLine (models.Model): name = models.CharField("name", max_length = 255, blank=False) parental_line = models.ForeignKey('self', on_delete=models.PROTECT, verbose_name = 'parental line', blank=True, null=True) It contains a ForeignKey that is not required because a MammalianLine instance may not have a parental_line. As we all know, users are lazy :) and they often forget, or can't be bothered, to enter a value for parental_line, even if one does indeed exist. Therefore, I would like to convert parental_line to a required (blank=False) field, but by doing so I need to cover the possibility that a MammalianLine instance may not have a parental_line. For these cases, I thought that a user could enter a "dummy" id for parental_line (I use raw_id_fields = ['parental_line']), such as 0, in the admin view, which would then set the underlying database value to NULL. What would be the best way to accomplish this? I thought I could use a signal, but maybe somebody has a better idea. I do not want to use db_constraint = False on parental_line. -
views didn't return an HttpResponse object. It returned None instead
I'm implementing some search mechanisam on my app, trying to get query from input, look for it in database(sqllite) and render it to template. Problem is that I'm getting ".views didn't return an HttpResponse object. It returned None instead" error. Logic is like: 1) making a function which will check given query def search_query(request,search,query): checking = check_in(query) #check if query is in DB if checking == False: #if not, get data from search api and save it search_querys = requests.get(search) json_search = search_querys.json() for each in json_search['data']: user_id = each['id'] name = each['name'] picture = each['picture']['data']['url'] Profiles.objects.create(user_id=user_id, name=name, picture=picture) return render(request, 'FB_search/home.html') else: # <--assuming that here's the problem. For testing purpose, I'm writing query for which I know that they are in DB and I'd like to return in tamplet context = { 'profiles': Profiles.objects.filter(Q(user_id__startswith=query) | Q(name__startswith=query)) } return render(request, 'FB_search/home.html', context) 2) calling function above in my endpoint like: def api_search(request): if request.method == "GET": query = request.GET.get('q') search = 'some API with {query} inside it' search_query(request,search,query) When I try to call the "search query" funtion I'm getting mentioned error. Any suggestion? Thank you. -
One single git repository for 2 different heroku apps with different PROCFILES, is it possible?
I want to create 2 different heroku apps.Both are using same github repository. Each app is having different processes to run i.e they need 2 different PROCFILES. Can we use same github code for runnning 2 different apps ? I created 2 different apps on Heroku. In Github code, created 2 different Procfiles also. In environment variables of each heroku app, I explicitly specifed 'PROCFILE' as environment variable with path of PROCFILE for each app. For one app i kept name of PROCFILE as it is and for other I created one different folder 'Backend' and in that folder added PROCFILE. Example of my folder structure: Project_folder\ -PROCFILE --> For one app -my_code_folder\ -abc.py -xyz.py -Backend\ -PROCFILE --> For second app -
Custom diagram for Django display - Circle with dots connecting to each other
I am making a web app using Django. I want to create a chart (as shown in image), displaying a circle with names on the edges and lines connecting the names, according to a set of values supplied. Is there any pre-existing library I can use? How would you recommend I attempt to make this? -
How to override ArrayField default error messages in template?
I am trying to change the default error message Django generates for ArrayField (Specifically too many items entered error message) If a user enters too many items to my ArrayField the following message generates in the template: List contains 4 items, it should contain no more than 3. I want to change this message to You can't have more than 3 topics. I have tried adding the following error_messages to my forms.py TopicForm Meta class but had no success error_messages = { 'topic': { 'invalid': ("You can't have more than 3 topics."), }, Here is my models.py file from django.contrib.postgres.fields import ArrayField from django.db import models class Topic(models.Model) topic = ArrayField(models.CharField(max_length=20), size=3, blank=True, null=True) and my forms.py from django import forms from .models import Topic class TopicForm(forms.ModelForm): class Meta: model = Topic fields = ['topic'] Would apperciate some input on this! Thank you! -
Sorting and Filtering on the client side. How should approach this?
GraphQL API from backend provides tabulated information of about 10000+ items (normalized data) (ie contact info: name, title, company, phone number, email...) Upon receiving this data in the front end. I want to sort by fields and search and filter by keywords. The approach I am thinking is, once the data is received via graphQL API to the component I can trigger onclick event to call a function to sort etc. within the component. Is this a naive approach? Would there be better method to handle this? -
Django - conditional image resizing & creating thumbnail on the fly in save method using PIL
I needed resize images and create thumbnails in my django 2.1.7 app. I decided to to do it via PIL in overwritten SAVE method. I have 2 version of my code now, one is fully working and one which doesn't. Problem is that I really don't understand what is going on, because I would say both version should working. So can anybody explain me where is problem in code below: #models.py #I am getting error OSError: cannot identify image file <_io.BytesIO object at 0x105a10200> from django.db import models import os import PIL from PIL import Image from io import BytesIO from django.core.files.uploadedfile import InMemoryUploadedFile class Photo(models.Model): image = models.ImageField(upload_to=change_image_name, null=True, blank=True, help_text = "") thumb = models.ImageField(upload_to=change_thumb_name, null=True, blank=True, help_text = "") gallery = models.ForeignKey(PhotoGallery, on_delete=models.CASCADE, related_name='image') def save(self, *args, **kwargs): maxsize = (1920, 1080) # max_size for image th_maxsize = (1000,1000) #ma_size for thubnail width,height = get_image_dimensions(self.image) with Image.open(BytesIO(self.image.read())) as thumb: if width > 1000: print ('image for thumb wider then 1000, doing resize') new_thumb = thumb.thumbnail(th_maxsize, PIL.Image.ANTIALIAS) output_1000 = BytesIO() thumb.save(output_1000, format='JPEG', quality=90) output_1000.seek(0) new_size = len(output_1000.getvalue()) self.thumb = InMemoryUploadedFile(file=output_1000, field_name='ImageField', name="%s.jpg" % self.image.name.split('.')[0], content_type='image/jpeg', size=new_size, charset=None) else: print ('saving thumbnail, no resize') output_thumb = BytesIO() thumb.save(output_thumb, format='JPEG', … -
How can I run a pubmed query in a Django app deployed on Elastic Beanstalk?
I wrote a Django app to query pubmed database using the Entrez tool provided by the Biopython package. Everything runs smoothly local. After deploying on AWS Elastic Beanstalk I get a "Permission denied". I am assuming that the problem might be that Entrez is writing to a cache directory which Elastic Beanstalk is refusing. Therefore, I tried to define the cache directory in Entrez.esearch(db='pubmed', ... cache='tmp/') - without success. I also tried to change permissions to 'tmp': container_commands: 02chmod: command: "chmod 777 /tmp" This is the function in python to perform the query: def PCMsearch(self, query, duration): Entrez.email = '***' handle = Entrez.esearch(db='pubmed', sort='relevance', retmax='5', retmode='xml', reldate = 365*duration, term=query directory='/tmp', cache='/tmp', ) self.results = Entrez.read(handle) return self.results Any help is highly appreciated! This is the response in Firefox: Request Method: GET Request URL: http://necessary.news/pubmed/ Django Version: 2.1 Python Version: 3.6.7 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'users.apps.UsersConfig', 'keywords', 'pubmed', ] 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'] Traceback: File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/exception.py" in inner 34. response = get_response(request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 126. response = self.process_exception_by_middleware(e, request) File "/opt/python/run/venv/local/lib/python3.6/site-packages/django/core/handlers/base.py" in _get_response 124. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/opt/python/current/app/pubmed/views.py" in search_pubmed 8. results = query.search_pubmed() File "/opt/python/current/app/pubmed/models.py" … -
How to determine to message to particular set of listeners?
How to determine to message to particular set of listeners? For example, I have Luke,Jason and Bruce in ChatRoom A. Lisa in Chatroom B.And each member has a message list screen which only display the last message of group chat room. I have a socket connection placed on every chatroom to listen incoming messages. Group messages from particular chatroom will have an room identifier along with message. The question is that how websocket to determine to send out messages only to those people who has subscribed to this chatroom? This websocket conncetion will receive msgs from diffrent room but it needs only to send msgs out to those who belongs to that particular group chat room. Do I need add some identifier in somewhere when I establish connection from client side so that serverside could know if it needs to send msgs to me? -
How to create 2 forms in one page(django)?
I want to have 2 different forms in my page. But when I try save value of forms, they are saved only in form_fridge. I think, it exists, because I use one csrf_token for 2 forms. Can you help me? <form method="POST" enctype="multipart/form-data" id = "formTv"> {% csrf_token %} {{ form_tv.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> <form method="POST" enctype="multipart/form-data" id = "formFridge"> {% csrf_token %} {{ form_fridge.as_p }} <button type="submit" class="save btn btn-default">Save</button> </form> views.py def add_new(request): form_fridge = FridgeForm(request.POST, request.FILES, use_required_attribute=False) form_tv = TvForm(request.POST, request.FILES, use_required_attribute=False) if form_fridge.is_valid() and request.method == 'POST': form_fridge.save() return redirect('new') elif form_tv.is_valid() and request.method == 'POST': form_tv.save() return redirect('new') return render(request, 'appliances/add_new.html', {'form_tv': form_tv, 'form_fridge': form_fridge}) -
How to refresh chart in django without refreshing whole page
I am new to Django , i Have used chart.js to populate a chart in HTML . I want to refresh the chart without loading the HTML itself. HTML Chart look like below View corresponding to the URL for above HTML is below Views.py # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render from django.views.generic import TemplateView # Create your views here. def dashboard(request): pass_tc=500 failed_tc=99 inprogress_tc=50 context = {'data':[pass_tc, failed_tc, inprogress_tc]} template='dashboard.html' return render(request,template,context) In HTML , i have used updateChart() functionality of Chart.js, but it refresh the chart only once Refresh <script> var ctx = document.getElementById('myChart').getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'bar', // The data for our dataset data: { labels: ['Pass', 'Fail', 'Inprogress'], datasets: [{ label: 'Results', //backgroundColor: 'rgb(255, 99, 132)', //borderColor: 'rgb(255, 99, 132)', backgroundColor:[ 'green','Brown','orange'], data: [10, 10,15] }] }, // Configuration options go here options: {}, }); function updateChart(){ jQuery.get("/dashboard/", function(data, status) { alert("Data: " + data + "\nStatus: " + status); chart.data.datasets[0].data={{ data}}; chart.update(); } ) }; </script> Suppose if i change the value of chart in views.py pass_tc=300 failed_tc=19 inprogress_tc=20 and click on refresh button , the … -
Difference between two date fields from Django form
How to find the difference between two date fields from django forms forms.py class task_form(forms.ModelForm): start_date = forms.DateField(widget = forms.widgets.DateInput(attrs={'type': 'date'}), label = 'Start date', required = False) due_date = forms.DateField(widget = forms.widgets.DateInput(attrs={'type': 'date'}), label = 'End date',required = False) duration = forms.IntegerField(required = False, label = 'Duration', disabled = True) views.py def edit_view(request): if request.method == "POST": form = task_form(request.POST) if task_edit_form.is_valid(): temp = form.save(commit= False) temp.bfs_task_duration = temp.start_date - temp.due_date temp.save() But this doesn't work and I couldn't find any resources helping to find the differences between two date fields, Please help Thanks in Advance -
Celery and django does not work as expected
Celery and django does not work as expected. I'm trying to create a little task to get to know Celery better. Implemented a simple print to analyze the output and nothing happens. What am I doing wrong. Follow the code below. I thank you for your attention. init from __future__ import absolute_import, unicode_literals from .celery import app as celery_app __all__ = ['celery_app'] Task from __future__ import absolute_import, unicode_literals from celery import task @task() def task_number_one(): print('okokokokokokokokok') Celery from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'sistema.settings') app = Celery('sistema') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) Setting CELERY_BROKER_URL = 'redis://REDIS:6379' CELERY_RESULT_BACKEND = 'redis://REDIS:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_RESULT_SERIALIZER = 'json' CELERY_TASK_SERIALIZER = 'json' CELERY_TIMEZONE = 'America/Recife' CELERY_BEAT_SCHEDULE = { 'task-number-one': { 'task': 'base.tasks.task_number_one', 'schedule': 30.0 } } Comand celery -A sistema worker -l info && celery -A sistema beat -l info -
How to get the US state code using django-cities-light?
I'm using django-cities-light for managing region/state models for US. But I can't see in the model how to retrieve the US state code widely available in GeoNames. e.g: CA for California. -
Whats the difference between DjangoModelPermissions and DjangoObjectPermissions
Whats the difference between DjangoModelPermissions and DjangoObjectPermissions? I'm still learning Django and DRF and according to the docs, they seems to do exactly the same thing. DjangoModelPermissions: This permission class ties into Django's standard django.contrib.auth model permissions. DjangoObjectPermissions This permission class ties into Django's standard object permissions framework that allows per-object permissions on models For the later, it seems like it has something to do with Django’s permission framework foundation which has no implementation. and apparently django-guardian fill in this gap. In Django admin, I'm able to assign a Model's CRUD permission to users and groups, so what does the later add? I'm trying to wrap my head around this permission system. What are the difference and what should I know about them? -
Struggling with displaying checkbox data in DetailView page
I have a form that when i submit it need to show the details I submitted in the form. I am really struggling to understand how to get it to display checkbox data. I went thropugh the django documentation on DetailForms but this didnt really help me with how to display ManyToManyFields. My template is as follows: <li>{{theBurger.burger}}</li> <li>{{theBurger.bun}}</li> {% for toppings in theBurger.toppings.all %} <li>{{toppings}}</li> {% empty %} <p>No toppings!</p> {% endfor %} <li>{{theBurger.sauces}}</li> {% for extras in theBurger.extras.all %} <li>{{theBurger.extras}}</li> {% empty%} <p>No extras!</p> {% endfor %} My view is as followes: class OrderDetailView(DetailView): context_object_name = 'theBurger' slug_field = 'id' model = models.Burger def get_context_data(self, **kwargs): context = super(OrderDetailView, self).get_context_data(**kwargs) context['now'] = timezone.now() return context I can get the page to display all the other information except information that has been submitted via checkboxes. the response that is being sent is: <QueryDict: {'csrfmiddlewaretoken': ['l6Qq7tg89cueHV2Fl6Qq7tg89cueHV2F2WrzrbJ'], 'burger': ["Aurion's Famous Beef Burger"], 'bun': ['White Bread'], 'toppings': ['15', '1 6'], 'sauces': ['Our Zesty Barbaque Sauce'], 'Submit': ['Git my food!']}> Lastly here is the form: class BurgerForm(forms.ModelForm): def __init__(self, *args, **kwargs): super(BurgerForm, self).__init__(*args, **kwargs) self.fields['toppings'].widget = forms.CheckboxSelectMultiple() for field_name in self.fields: field = self.fields.get(field_name) if field and isinstance(field , forms.TypedChoiceField): field.choices = field.choices[1:] … -
How should I go about creating an intuitive Django filter to find the best result?
Summary of the problem I have a basic Django form along with a list of dogs with attributes in an SQLite database. The idea is that the user will input/customise a bunch of inputs about the dog they'd most prefer, and the application will find the closest match and return the best result(s) based on the inputs they have submitted. The attributes that are relevant to finding the best dog result are: breed_name activity_level shedding_level grooming_demand intelligence drools coat_length size good_with_children While simply totaling up the number of attribute matches is adequate, it would be preferred if the query for finding the best dog takes into account 'value proximity' (there is probably a better term for that), in the sense that if the user said they want a small dog, and that does not match but most of the other attributes do, then it would be preferable to find a medium sized dog (with the same number of total matches) rather than a large one. At present, my CASE statement does not take this into account. The solution should be written at Django's application-layer level, rather than at a database-layer level. So a Django filter would be appropriate, however a … -
How to update Foreign Key field of Profile model from webpage using django forms?
I have a model called profile that has a field in it that links to another model called advertisement using ForeignKey. I am attempting to allow the profile that is signed in, to change the advertisement instance associated with their profile from a webpage using a checkbox and a submit button. This is the profile Model: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) ethAddress = models.CharField(max_length=42, default='') advertisement = models.ForeignKey(Advertisement, on_delete=models.CASCADE, null=True, blank=True) def __str__(self): return f'{self.user.username} Profile' This is the form for changing the advertisement instance associated with their profile: class AdvertisementUpdateForm(forms.ModelForm): def __init__(self, *args, **kwargs): e = kwargs.pop('e', None) super(AdvertisementUpdateForm, self).__init__(*args, **kwargs) if e is not None: self.fields['advertisement'] = forms.CheckboxInput(queryset=e) class Meta: model = Profile fields = ['advertisement'] This is the View: def ad_update_view(request, my_id): ad_form = ad_update(request.POST, Advertisement.objects.get(id=my_id)) obj = Advertisement.objects.get(id=my_id) if request.method == 'POST': if ad_form.is_valid(): ad_form.save() messages.success(request, f'Your account has been Updated!') return redirect('profile') else: ad_form = ad_update(request.user.profile) context = { 'ad_form': ad_form, 'object': obj, } return render(request, 'users/advertisement_update.html', context) This is the template that the user will use to change the advertisement associated with their profile. {% extends "website/base.html" %} {% block content %} <article class="media content-section"> <div class="media-body"> <form method="POST"> <div class="article-metadata"> <a class="mr-2" … -
Failed to start [/bin/bash, --rcfile, /snap/pycharm-professional/127/plugins/terminal/jediterm-bash.in, -i]
My Pycharm was working perfectly fine all of a sudden I see the below error message. I have pycharm professional version Any suggestions on how to fix this issue Cannot open Local Terminal Failed to start [/bin/bash, --rcfile, /snap/pycharm-professional/127/plugins/terminal/jediterm-bash.in, -i] in /home/path-to-my-project See your idea.log (Help | Show Log in Files) for the details. -
Django: template: To change the display depending on the presence or absence of data
Django2.1 I want to create a button that will be displayed when the user saves data in the past. I thought it could be done with {% if object %}, but it seemed different. Here is the failed code. {% if user.is_authenticated %} {% if object %} <a class="btn" href="{% url 'detail' user.id %}">Check</a> {% else %} <a class="btn" href="{% url 'create' %}">Create</a> {% endif %} {% else %} #models.py class Mymodel(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) title = models.CharField(max_length=20) content = models.TextField(max_length=5000) posted_date = models.DateTimeField(auto_now=True) I will create data in CreateView. class MyCreateView(LoginRequiredMixin, CreateView): model = Mymodel form_class = MyForm def form_valid(self, form): obj = form.save(commit=False) obj.user = self.request.user return super(MyCreateView, self).form_valid(form) def get_success_url(self): return reverse_lazy('detail', kwargs={"pk": self.object.pk}) thank you for reading it until the very end. -
How to properly extend django user model and seed databse
I created a model that extends on Django's user model. I am now trying to seed the database with this type of user, but I get an error when trying to use the loaddata call. I extended the user model, creating a different user type called FocalUser. I created a user.json file with the information. When I got the error the first time, I then double checked this by using dumpdata. The information didn't seem to be correct, or as I imagined it from the dump. This is from the models.py file where I create FocalUser: class FocalUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) userID = CharField(max_length=50) type_id = CharField(max_length=50) is_active = BooleanField() This is my users.json file: [ { "model": "focal_login.FocalUser", "pk": 1, "fields": { "username": "kate@tamu.edu", "email": "kate@tamu.edu", "password": "password", "first_name": "Kate", "last_name": "Catalena", "userID": 2, "type_id": 2, "is_active": "True" } } ] The error resulting from python3 manage.py loaddata users.json: Traceback (most recent call last): File "/Users/kate/.local/share/virtualenvs/login-E6JpMIQ_/lib/python3.5/site-packages/django/db/models/options.py", line 564, in get_field return self.fields_map[field_name] KeyError: 'last_name' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/kate/.local/share/virtualenvs/login-E6JpMIQ_/lib/python3.5/site-packages/django/core/serializers/json.py", line 69, in Deserializer yield from PythonDeserializer(objects, **options) File "/Users/kate/.local/share/virtualenvs/login-E6JpMIQ_/lib/python3.5/site-packages/django/core/serializers/python.py", line 116, in Deserializer field = Model._meta.get_field(field_name) File … -
How to keep assigned attributes to a queryset object after filtering? Alternatives?
Maybe it's a stange answer, so i will explain why i'm doing this. I have a model of Products. I have to assign each of them some stock. So i have a function on the Products model that calculates a lot of neccesary things like stock and returns a QuerySet. Since my db model is a little bit "complicated" i can't use annotations in this case. So i decided to execute this database query manually and then, assign each product on the querySet a stock attribute manually. Something like: for product in queryset_products: product.stock = some_stock_calc... The problem comes when i want to use filters this queryset_product. after executing something like: queryset_products = queryset_products.filter(...) the stock attribute gets lost Any solution? -
My for loop returns the last value for all iteration in my python code
I have a simple Python for loop that iterate throung an object field (4 product.price) and multiply it by a constant value It prints the right calculated 4 values in the console, but when rendering it in the django template, all 4 results have the same value (the calculated value of the last iteration) However with Return instead of Print it bring the following error 'float' object has no attribute 'get' View def reprice(request): list = Product.objects.all() ...... for item in list: rp = item.price * value_USD print (rp) return render(request , 'multi/reprice.html', {'list' : list, 'rp' : rp }) template {% for item in list %} {{ rp }} {% endfor %} -
AttributeError: type object 'ContactRequestSerializer' has no attribute 'get_extra_actions'
I have a REST API created with Django rest. Where I get the following error: AttributeError: type object 'ContactRequestSerializer' has no attribute 'get_extra_actions' class ContactRequestSerializer(serializers.ModelSerializer): class Meta: model = ContactRequest fields = '__all__' class ContactFormSerializer(serializers.ModelSerializer): class Meta: model = ContactForm fields = '__all__' class ProjectRequestSerializer(serializers.ModelSerializer): class Meta: model = ProjectRequest fields = '__all__' I have specified the same attributes in all of my serializers, and I have inherited from the same class, however, the issue still occurs. I have an API file, where I make the viewsets class ContactFormViewSet(viewsets.ModelViewSet): queryset = ContactForm.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = ContactFormSerializer # ProjectRequest Viewset class ProjectRequestViewSet(viewsets.ModelViewSet): queryset = ProjectRequest.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = ProjectRequestSerializer class ContactRequestViewSet(viewsets.ModelViewSet): queryset = ContactRequest.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = ContactRequestSerializer and then my models: ... class ContactRequest(models.Model): topic = models.CharField(max_length=30) description = models.CharField(max_length=200) time = models.CharField(max_length=15) project_request = models.ForeignKey(ProjectRequest, on_delete=models.CASCADE) since they all seem alike, except for the relationship between the two of my models, I can't figure out the issue.