Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
__init__() got multiple values for argument 'crescator'
I have a ModelForm and in a ModelChoiceField I need to filter objects by request.user. When data is submitted, I got the error "init() got multiple values for argument 'crescator' ". How can I repair that? #My Form class AdaugaPereche(forms.ModelForm): boxa = forms.IntegerField(label="Boxa", min_value=1) sezon = forms.CharField(label="Sezon reproducere", initial=datetime.now().year) mascul = forms.ModelChoiceField(queryset=None, label="Mascul", empty_label="Alege mascul") femela = forms.ModelChoiceField(queryset=None, label="Femela", empty_label="Alege femela") serie_pui_1 = forms.TextInput() serie_pui_2 = forms.TextInput() culoare_pui_1 = forms.ModelChoiceField(queryset=None, label="Culoare pui 1", empty_label="Alege culoarea", required=False) culoare_pui_2 = forms.ModelChoiceField(queryset=None, label="Culoare pui 2", empty_label="Alege culoarea", required=False) data_imperechere = forms.DateInput() primul_ou = forms.DateInput() data_ecloziune = forms.DateInput() data_inelare = forms.DateInput() comentarii = forms.TextInput() # Functie pentru filtrarea rezultatelor dupa crescator def __init__(self, crescator, *args, **kwargs): super(AdaugaPereche, self).__init__(*args, **kwargs) self.fields['mascul'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Mascul", perechi_masculi__isnull=True) self.fields['femela'].queryset = Porumbei.objects.filter(crescator=crescator, sex="Femelă", perechi_femele__isnull=True) self.fields['culoare_pui_1'].queryset = CuloriPorumbei.objects.filter(crescator=crescator) self.fields['culoare_pui_2'].queryset = CuloriPorumbei.objects.filter(crescator=crescator) class Meta: model = Perechi fields = "__all__" #My view def perechenoua(request): if request.method == "POST": form = AdaugaPereche(request.POST, crescator=request.user) if form.is_valid(): obj = form.save(commit=False) obj.crescator = request.user obj.save() return HttpResponseRedirect("/perechi/") else: form = AdaugaPereche(crescator=request.user) context = { 'form': form } template = loader.get_template("adauga-pereche.html") return HttpResponse(template.render(context, request)) May the problem be obj = form.save(commit=False) obj.crescator = request.user obj.save() ? -
how can I upload & play audio files in Django
I have a project where I can upload & view pdf files but i want to upload & play audio files instead . What changes do I need to make ? Please Help This is my models.py What changes do I need to make for audio files ? from django.db import models class PDF(models.Model): title = models.CharField(max_length=100) pdf = models.FileField(upload_to='books/pdfs/') def __str__(self): return self.title This is my views.py of the app . What changes do I need to make for uploading and playing audio files? from django.shortcuts import render, redirect, HttpResponseRedirect from django.views.generic import TemplateView, ListView, CreateView from django.core.files.storage import FileSystemStorage from django.urls import reverse_lazy from .forms import * from .models import * def upload(request): context = {} if request.method == 'POST': #when request method is POST , the files are being uploaded uploaded_file = request.FILES['document'] fs = FileSystemStorage() name = fs.save(uploaded_file.name, uploaded_file) context['url'] = fs.url(name) return render(request, 'upload.html', context) #this function shows the "list of pdfs" in the database on pdf_list.html def pdf_list(request): pdfs = PDF.objects.all() return render(request, 'pdf_list.html', { 'pdf': pdfs }) #this function ensures that the file being uploaded is PDF def upload_pdf(request): if request.method == 'POST': form = PDFForm(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('pdf_list') else: … -
How to fix TemplateSyntaxError?
I'm trying to render template, but it always get an TemplateSyntaxError error. For solve this I tried to change construction. Instead {% if value %} -some action {% else %} {% endif %} I tried: {% if value_1 %} - some action {% endif %} {% if value_2 %} - some action {% endif %} But it didn't bring success, always the same error. I thought, that I made mistake with '{' or '%', but I didn't found anything, that couldn't be properly. Then I tried to find solve my problem, but all the problems that were considered had problems with the wrong syntax, like '%{' or '{ %'. --- VIEW --- class HumanList(TemplateView): def post(self, request): search_type = request.POST.get('type', False) search_object = request.POST.get('object', False) def separate(search_type, search_object): try: if search_type == 'name': return Human.objects.all().get(name__exact=search_object) if search_type == 'surname': return Human.objects.all().filter(name__contains=search_object) if search_type == 'company': return Human.objects.filter(company=search_object) if search_type == 'position': return Human.objects.filter(position=search_object) if search_type == 'language': return Human.objects.filter(language=search_object) except ObjectDoesNotExist: return None search_result = separate(search_type, search_object) if search_result: context = { 'result': search_result, 'searched': search_object, } else: context = { 'empty': 'We couldn\'t find anything', 'searched': search_object, } return render(request, 'result.html', context) --- HTML TEMPLATE --- {% extends 'human_list.html' … -
django passenger_wsgi issue something went wrong
hosting done successfully but error:we are sorry something went wrong looks like there is error in passenger_wsgi.py file, working on Django framework website should be live -
Disable Delete and Edit on condition
I want my Django program to check if my my entry is authorized and if it's either Manual or Auto. If it is authorized, then I want to prevent it from being deleted so basically disable the delete option for it and if it is Automatic, I want to prevent it from being edited when I click on the model object in the Django admin. Here is an example of my model: class ModelName(models.Model): AUTO_ATT = "AU" MANUAL_ATT = "MA" ENTRY_TYPES = ( (AUTO_ATT, "Auto-Attendance"), (MANUAL_ATT, "Manual-Attendance"), ) AUTHORIZED = "AU" UNAUTHORIZED = "UA" ENTRY_STATUSES = ( (AUTHORIZED, "Athorized"), (UNAUTHORIZED, "Un-Authorized"), ) status = models.CharField(max_length=2, choices=ENTRY_STATUSES, default=WORK_ENTRY_STATUSES[1][0]) type = models.CharField(max_length=2,choices=ENTRY_TYPES) So everytime I click on the object in the Django Admin, I want the program to first see if the entry is authorized and if its auto and display me the functions accordingly. -
How to return a message and redirect users in Django middleware
In my Django application, I pull a user's IP address and set a local city. However, if a user is out of the geographical area that the app covers, I want to raise an error and redirect them to the geographical area that this app covers. I'm trying to do this with middleware, but not sure how to do this. class RestrictUserMiddleware(object): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ipaddress = x_forwarded_for.split(',')[-1].strip() else: ipaddress = request.META.get('REMOTE_ADDR') ip = get_client_ip(request) reader = geoip2.database.Reader(path) try: location = reader.city(ip) except: location = True if not response.subdivisions.most_specific.iso_code in 'CA': # raise error message here that it's not available outside CA request.session['city'] = 'Beverly Hills' return HttpResponseRedirect(reverse('index')) response = self.get_response(request) return response -
I'm not understanding this part of the code, need some suggestions to understand it
This part is for street - ##Street street = entry['street'] if entry['street']!=None else '' if street!=''and [{'exportHint':'street','subcategory':'street','value':street}] not in street: street_names.append([{'exportHint':'street','subcategory':'Street','value':street}]) for st in street_names: category.append([st]) This part is for displaying its value in template - <div class="{%if not responses%}span-19 {%endif%} last componentName" style="{%if responses%}width:{{responseDim.totalWidth|add:750}}px;{%endif%}padding-top:5px;"> <b>{{category.label}}</b> {% for entry in category.entries %} {% for group in entry %} {% for kv in group %} But, I'm not understanding how this works. Confused... -
How to filter if a store(point) lies inside a specific rectangle?
I am making an API with django rest framework. The app need to take of 4 corner coordinates and i need to filter all my stores out whether if it is in this rectangle or not. As a result i will filter out stores which is in this rectangle and serve it. How to make it with Django how to filter? thank you in advance. -
Django Wagtail Deployment Static File Server
After deployment today, for some reason, the project no longer shows style from items that would have been collected during the collectstatic process. I have full access to the files from any browser. I have checked all permissions. I have browsed to the site from the development server, and other machines to eliminate software\font possibilities. No idea what's going on here. I serve the files from a different server. Other django projects are unaffected. No other django projects use anything like wagtail though. Pulling my hair out at this point and probably just missing something simple. What am I missing? base.py config STATIC_ROOT = '/var/www/html/static.xxxxxx.net' STATIC_URL = 'http://static.xxxxxx.net/' MEDIA_ROOT = '/var/www/html/media.xxxxxx.net' MEDIA_URL = 'http://media.xxxxxx.net/' Checking for file existence on server: -rw-rw-r-- 1 xxxxxx xxxxxx 13648 Aug 24 09:18 /var/www/html/static.xxxxxx.net/wagtailadmin/css/userbar.3d5222a7eba2.css Checking CSS relative references -rw-rw-r-- 1 xxxxxx xxxxxx 68812 Aug 24 09:18 /var/www/html/static.xxxxxx.net/wagtailadmin/css/../../wagtailadmin/fonts/opensans-regular.45f80416d702.woff2 -
How to serve an image in django without using <img> tag in django?
Recently I started learning Django and at the first actually I want to prepare an API in order to serve images. for this purpose, when anybody requests to access to an image, my program should read raw image data from local library and serve it and prepare an access to this image for anybody who requests that image. notice that i don't want to show image with tag in my html file. just prepare an access to raw data in order to manipulation that image or anything similar. -
How to sanitise image field content to make sure it doesn't contain html form in django?
I have included imagefield in my django app and in the documentation I read that the validation done by the ImageField is not sufficient. I wanted to validate the image content to make user doesn't submit any html form. Is there any way to make sure that the image content is valid that it is not any sort of html under image extension. -
Execute function and print result in template without refresh
I'm using django to develop my website. In this page I have x as input, when i press enter a function will be executed and then the page will refresh and the result will be displayed. I would like to make it dynamic: capture input, execute function and show the result then another tag appears etc.. I will be very thankful. This is my python code: def console (request): import paramiko import time import getpass import re ip = '192.168.43.10' username = 'osboxes' password = 'osboxes.org' ssh = paramiko.SSHClient() ssh.set_missing_host_key_policy(paramiko.AutoAddPolicy()) ssh.connect(ip, username=username, password=password, look_for_keys=False, allow_agent=False) print('Successfully connected to %s' % ip) remote_conn = ssh.invoke_shell() time.sleep(.005) output = remote_conn.recv(65535) print (output) def escape_ansi(line): ansi_escape = re.compile(r'(\x9B|\x1B\[)[0-?]*[ -/]*[@-~]') return ansi_escape.sub('', str(line)) x=request.GET['x'] time.sleep(1) remote_conn.send(x+'\n') time.sleep(0.1) if remote_conn.recv_ready(): output = remote_conn.recv(5000) op=output.decode() oo=escape_ansi(op) return render(request,'shell.html', {'oo' : oo}) This is my html file: {% extends 'base.html' %} {% block content %} <div class="mb-3 card text-white card-body" style="background-color: rgb(51, 51, 51); border-color: rgb(51, 51, 51);"> <h5 class="text-white card-title">Console log to the gateway</h5> <form action="console"> <div class="position-relative form-group" > <input rows="15" style="color: #FFFFFF; background-color: rgb(51, 51, 51)" name="x" id="x" class="form-control"> </div> </form> </div> <h3>result : {{oo}}</h3> {% endblock %} -
Set session in DRF not called in other request
I try create session in Django Rest API request but session not stored and fail get session in other page. settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', ] 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', ] api.py class PersonApiView(viewsets.ViewSet): permission_classes = (AllowAny,) parser_class = (FormParser, FileUploadParser, MultiPartParser,) # Sub-action send email persons @action(methods=['post'], detail=False, permission_classes=[AllowAny], url_path='send-validation', url_name='send_validation') @transaction.atomic def send_validation(self, request): request.session['user_id'] = 123 # set session request.session.create() return Response('OK!', status=status.HTTP_200_OK) home.py class HomeView(View): template_name = 'web/home.html' context = {} def get(self, request): user_id = request.session.get('user_id', None) print(user_id) # Always None return render(request, self.template_name, self.context) The session always return None Where i missed? -
Python or java script Dynamic maps
please I need help building a map for a ride sharing app ,I will like to build an app that updates the positions of customer on the drivers screen and also shows potential drivers on the passengers screen; So this are what I need 1. A map api that can load maps canvasses dynamically 2. A guide on how to do 1 3. I would like to use python or js -
“Context must be a dict rather than type.” Cannot be resolved
I want to use the obtained URL parameter for filter, but the error cannot be solved. I understand that "context ['group'] = belong.objects.get (user = user) .group" is the cause, but I don't know what to do. "username" has been acquired. #error context must be a dict rather than type. #view def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) user = self.kwargs.get('username') print(user) try: context['group'] = belong.objects.get(user=user).group except belong.DoesNotExist: pass except: return HttpResponseBadRequest try: context['count'] = URC.objects.filter(user=user).count() except URC.DoesNotExist: pass except: return HttpResponseBadRequest context['username'] = user return context -
Django forms custom backend validation
I'm trying to run backend validations (which takes ~3-4 seconds) on 1 of the fields (query field) only on POST request (i.e. only after the "Submit" button is clicked). When form is loaded on a GET request - i don't want to make run this validation because it takes lot of time. I tried to look on the django form validation documentation But i couldn't understand a way to run the clean method only on a POST request. Anytime i'm creating a SomeForm instance, the clean method is taking place. forms.py: class SomeForm(forms.Form): is_active = forms.ChoiceField(label='Is Active?', required=False, choices=IS_ACTIVE_DROPDOWN) query = forms.CharField(label='Query',help_text='This is help text', widget=forms.Textarea) last_successful_run = forms.DateTimeField(label='Last Run') def clean(self): ... Execute "regular" cleaning ... return self.cleaned_data views.py def mng_tables_form(request, resource, action, item_id): form = SomeForm() if request.method == 'POST': form = form(data=request.POST) if form.is_valid(): ## UPDATE DB api_driver.run_api_request(item_id, request.fields) return redirect('mng_tables_form_page', resource, 'show_item', item_id) else: form = _get_resource_objects(resource, RESOURCES_MODELS_MAPPING).get(action) ## Get Data from DB item_object = api_driver.run_api_request(resource=resource, item_id=item_id, params={'fields':form}).json().get('response') form = form(item_object) context = {'form': form, 'item_object': item_object, 'item_id': item_id} return render(request, 'mng_tables/form.html', context=context) What i want to do is to somehow recognize the request method when i create the form instance, and run more validation only … -
How to pass raw <html> to xxx.html using dictionary values in python django
After collecting some data in html format I need to display it on base.html using views.py render function. But it shows the raw code instead of showing the proper view (select dropdown). I'm using django python on windows pc models.py class query(models.Model): connection = mysql.connector.connect(host="localhost",database="ameya",user="root",password="") html = '<table class="table table-bordered datatable responsive" id="table-2"><thead><tr><th>Schedule NO.</th><th>Farmer Name</th><th>University</th><th>District</th><th>Taluk</th><th>Panchayet</th><th>Village</th><th>Crop</th></tr></thead><tbody id="tab_tbody">' def __str__(self): htm = '<form action="getFarmer" method="post"><select class="form-control" name="season"><option value="0">-- Select Year --</option><option value="333">All Data</option>' now = datetime.datetime.now() cdt = now.year for i in range( 2017,int(cdt) ): htm += '<option value="'+str(i)+'">'+str(i)+' - '+str(int(i)+1)+'</option>' htm += '</select><input type="submit" value="Search >"></form>' return htm views.py def index(request): t = query() return render(request,"mainapp/base.html",{'html':t}) base.html <html> <head><title>AmeyaKrishi Version 2</title></head> <body> <h2>AmeyaKrishi V2 (testing mode): All University Filter</h2><hr> <p>{{ html }}</p> </body> </html> OUTPUT local server output -
Django / django-templates - how to check if a looped variable exists in the reverse of an object?
I'm working on a webapp that contains the following: A SchoolGroup model, that (among other things) contains various students. A GroupMaterial model that contains educational material that the group can access. This is linked to the SchoolGroup model with an ManyToMany relationship. There are (for now) 3 GroupMaterial objects, (Group 1, Group 2, Group 3) The models are defined as follows: class GroupMaterial(models.Model): name = models.CharField( max_length=255, choices=GROUPMATERIALS.items(), primary_key=True ) order = models.IntegerField(null=True) class SchoolGroup(models.Model): name = models.CharField( max_length=255 ) ( ... ) groupmaterials = models.ManyToManyField('schoolapp.GroupMaterial') I want to create a template that contains a table for SchoolGroup objects (with the columns [name, group1, group2, group3]) where each row show not only the name but also a checkmark if the GroupMaterial object appears in .groupmaterials attribute of the current SchoolGroup. To do so I created the following view and template: class SchoolGroupListView(GroupSettingsMixin, generic.ListView): model = models.SchoolGroup template_name = "templates/settings/group_list.html" def get_context_data(self, *args, **kwargs): data = super(SchoolGroupListView, self).get_context_data(*args, **kwargs) data['groupsmaterials'] = GroupMaterial.objects.all() return data <table> <th>Name</th> {% for material in groupmaterials %} <th>{{ material.name }}</th> {% endfor %} {% for schoolgroup in object_list %} <td>schoolgroup.name</td> {% for material in groupmaterials %} <td> {% if material in schoolgroup.groupmaterials.all %} <div>Div containing 'there … -
How can I upload an InMemoryUploadedFile to Amazon s3
I am trying to uplaod an image onto Amazon s3. The image is in the object "request.FILES['image']" as can be seen in the code below. My problem is that the boto3 "upload_file()" function expects a path to the image and I on the other hand have an in memory image objects and because of that i get this error.raise ValueError('Filename must be a string') ValueError: Filename must be a string My code here. @csrf_protect def file_upload_view(request): if request.method == 'POST': img_list = request.FILES['image'] s3 = boto3.client('s3') s3.upload_file(img_list, settings.AWS_STORAGE_BUCKET_NAME, img_list.name) else: print('not post...') return HttpResponse([{}], content_type='application/json') Any ideas would be appreciated. -
Can't show image uploaded with ImageField in template
So, I have a blog application, when I want to add cover image to article with ImageField file browser my image name is getting red in PyCharm and not showing in template. But when I inspect its HTML codes source, path to image is true. Here are my codes: articles.html: <a href="/"><img src="{{ article.image.url }}" class="image"/></a> settings.py: STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' models.py: class Article(models.Model): title = models.CharField(max_length=100) description = models.CharField(max_length=200) content = HTMLField() # image = models.CharField(max_length=2000) image = models.ImageField(upload_to='media') category = models.ForeignKey(Category, on_delete=models.CASCADE, null=True) post_date = models.DateTimeField(auto_now_add=True) slug = models.SlugField(unique=True, null=True, editable=False) def __str__(self): return self.title def save(self, *args, **kwargs): self.slug = latin_slugify(self.title) super(Article, self).save(*args, **kwargs) urls.py: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Flip a row of the table after every 10 seconds
i have an html table and i want to flip vertically each row of the table to display a "front" and "back" data. the flip should occur every 10s. this website is for displaying stocks from a website and i want a table showing recently updated stocks which flip(change) every 10s <div class="row "> <div id="draggable"> <div id="dashboard" class="shadow"> <div class="widget-inner loadable" id="a"> <div class="widget-inner loadable" id="b"> <div class="row" style="margin-top:-90px"> <div id="draggable"> <div id="dashboard" class="shadow"> <div class="widget-inner loadable" id="a"> {% for rec in stockrecent1 %} <tr> <td class="name">{{rec}}</td> <td class="other">{{rec.currentprice}}</td> <td class="other">{{rec.change}}</td> <td class="other">{{rec.percent}}%</td> <td class="other">{{rec.lastprice}}</td> </tr> {% endfor %} </div> <div class="widget-inner loadable" id="b"> {% for rec in stockrecent %} <tr> <td class="name">{{rec}}</td> <td class="other">{{rec.currentprice}}</td> <td class="other">{{rec.change}}</td> <td class="other">{{rec.percent}}%</td> <td class="other">{{rec.lastprice}}</td> </tr> {% endfor %} </div></div></div></div> .row:after { content: ""; display: table; clear: both; } #draggable { position: relative; margin: 10px auto; width: 1550px; height: 40px; z-index: 1; } #dashboard { -webkit-perspective: 1000; perspective: 1000; } #dashboard { width: 100%; height: 100%; -webkit-transform-style: preserve-3d; transform-style: preserve-3d; -webkit-transition: all 1.0s linear; transition: all 1.0s linear; } .loadable { position: absolute; width: 100%; height: 100%; -webkit-backface-visibility: hidden; backface-visibility: hidden; } #a{ -webkit-transform: rotateY(-180deg); transform: rotateY(-180deg); -webkit-animation: mymoveback 20s infinite; animation: mymoveback … -
how to change django template and app folder?
I'm working on a project and my project structure looks like this. - project name - apps - app1 - app2 - templates - app1 - app2 To make django find app i have changed my project base directory path as import os import sys BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) APPS_DIR = os.path.join("apps") sys.path.append(APPS_DIR) I want to change my template setting so that django could easily find the template directory. currently my template directory looks like this TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': False, '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', ], }, }, ] -
Django Object filter buy foreign key value reference
I want to filter models object of Django by using foreign key references. Here is my models class Category(models.Model): name = models.CharField(max_length=255, unique=True) slug = models.CharField(max_length=255, unique=True) icon = models.CharField(max_length=255, blank=True, null=True) class Article(models.Model): title = models.CharField(max_length=255) slug = models.CharField(max_length=255, unique=True) category = models.ForeignKey(Category, on_delete=models.CASCADE) My Query: Article.objects.filter(category__name=value) Article.objects.filter(category__slug=value) I want to get all Article that category name that specify. But Error: return Database.Cursor.execute(self, query, params) django.db.utils.OperationalError: no such table: report_article_category -
Timezone issue in admin
I have set up a timezone aware django app. Now I have the issue that somehow the times are mixed up. In my form where I show and input the time everything is fine: class WeekView(FormView): template_name = "week.html" form_class = EntryForm def form_valid(self, form): ei = Entry() ei.start =(datetime.datetime.fromtimestamp(float(form.cleaned_data['start_div'])/1000)) Note that in the last line localizing is not necessary (and indeed does not have an effect) as the cleaned data does that already. For the rendering I use a model method that I call in the template: def get_time(self): return self.start.strftime("%Y-%m-%d %H:%M:%S") So those two work fine together: if I enter a time and save the form it redirects to the form again and shows the entered time. However, if I look into the record in the admin, the time is off. It seems to show me the timezone corrected time, where the other values seem to be UTC (or the server time). Settings should be correct: TIME_ZONE = 'Europe/Vienna' USE_TZ = True Where is my mistake? As my main motivation to use timezone aware times is the daylight save time issue, I do not want to jerry-rig a solution by subtracting the hours. -
django.db.utils.IntegrityError: in POST request
I am creating a post function to save data in a model, Here's the code: Views.py class take_quizapi(CreateAPIView): def post(self, request,pk, *args, **kwargs): supplier = request.user.supplier data = request.data.copy() data["supplier_id"] = supplier.user_id data["score"] = 0 data["quiz"] = pk print("data is", data) serializer = takenquizSerializer(data=data) if serializer.is_valid(): serializer.save() print("Serializer data", serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) when I call the API from postman it says: django.db.utils.IntegrityError: null value in column "supplier_id" violates not-null constraint But I am clearly providing the data["supplier_id"] = supplier.user_id. What is it that I am doing wrong here ? Serializers.py class takenquizSerializer(serializers.ModelSerializer): supplier = ReadOnlyField(source='supplier.supplier_fname') class Meta: model = TakenQuiz fields = "__all__" Models.py class TakenQuiz(models.Model): supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE, related_name='taken_quizzes') quiz = models.ForeignKey(Quiz, on_delete=models.CASCADE, related_name='taken_quizzes') score = models.FloatField() date = models.DateTimeField(auto_now_add=True) least_bid = models.IntegerField(default=0) confirmed = models.CharField(max_length=100, default='Not Confirmed')