Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
NoReverseMatch at /cars/
i am working on a project . i use crispy_form in my project. it is my cars urls.py:: from django.urls import path from . import views app_name = 'cars' urlpatterns = [ path('', views.CarsListView.as_view(), name='cars'), path('add-car/', views.AddCarView.as_view(), name='add_car'), path('car/', views.RepairsListView.as_view(), name='car_detail'), path('car/<int:pk>/update/', views.UpdateCarView.as_view(), name='update_car'), path('car/<int:pk>/delete/', views.DeleteCarView.as_view(), name='delete_car'), path('car/<int:pk>/new-repair/', views.AddRepairView.as_view(), name='add_repair'), ] it is my cars views.py :: from .models import Car, Repair from django.views.generic import ListView, UpdateView, DeleteView, CreateView from django.contrib.auth.mixins import LoginRequiredMixin, UserPassesTestMixin from django.urls import reverse_lazy from django.contrib import messages class CarsListView(LoginRequiredMixin, ListView): model = Car template_name = 'cars/cars.html' context_object_name = 'cars' paginate_by = 10 def get_queryset(self): if self.request.GET.get('q'): q = self.request.GET.get('q') make_results = self.model.objects.filter( user=self.request.user, make=q).order_by('-pk') model_results = self.model.objects.filter( user=self.request.user, model=q).order_by('-pk') if make_results.exists(): return make_results elif model_results.exists(): return model_results else: return self.model.objects.none() return self.model.objects.filter(user=self.request.user).order_by('-pk') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['q'] = self.request.GET.get('q', '') return context class AddCarView(LoginRequiredMixin, CreateView): model = Car fields = ['make', 'model', 'vrn', 'year'] success_url = '/' def form_valid(self, form): form.instance.user = self.request.user return super().form_valid(form) class DeleteCarView(LoginRequiredMixin, UserPassesTestMixin, DeleteView): model = Car success_url = '/' def test_func(self): if self.get_object().user == self.request.user: return True return False def delete(self, request, *args, **kwargs): success_message = f'Car {self.get_object()} has been deleted' messages.success(self.request, success_message) return super().delete(request, *args, **kwargs) … -
How can I create such a form in Django and what is the name of this type of form?
I'm trying to create a form in Django, part of which is a long list of strings (component names). The user using the form should be able to select one or more components, move them from the left list to the right, and submit these names (in the right list) with the form. This is also used in the Django administration interface as you can see on my screenshot. Django admin interface Unfortunately, I have no idea what this type of form is called. Therefore it is difficult to find a solution on google if you don't have the right search parameters ...;) If someone even had a snippet of code to create this form, it would be even better. -
Django option set displaying only one value and passing Null
I have a following code in django html <select name="my_option"> {% for things in my_data %} <option value="{{things.accountid}}"> {{ things.address1_name }} {{ things.address1_city }}</option> {% endfor %} </select> views.py def my_view(request): my_data = my_data.objects.all if request.method == "POST": my_option = request.POST.get('my_option', None) post_data = {'my_option': my_option} if my_option is not None: response = requests.post('my_working_url', json=post_data) content = response.content messages.success(request, 'Data passed') return redirect('home') else: return redirect('home') else: return render(request, 'my_view.html', {'my_data':my_data}) In the option set I can see only things.address1_name being displayed and I'm absolutely sure I have values in the database for all other fields used. Also my request.POST.get returns Null instead of accountid as I would like the user to be able to see only address values and not accountid but pass the accountid value to the code in views.py How can I fix this? -
Django email as username with already custom-made sign up form?
I followed this tutorial to set up a custom sign up form which requires an email and password to sign up new user (i.e. no username). I also followed this tutorial to send an email with a confirmation link to create the accounts. How can I then assign a username to each account? Perhaps using the name in their name@domain.com, and adding random numerical characters to the end of name to make it unique if identical to other already registered names. my-website/views.py from django.utils.encoding import force_bytes, force_text from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.template.loader import render_to_string from .tokens import account_activation_token from users.models import CustomUser from django.core.mail import EmailMessage from random import choice import string def index(request): return render(request, 'index.html') def signup(request): if request.method == 'POST': form = SignUpForm(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False user.save() current_site = get_current_site(request) mail_subject = 'Activate your account.' message = render_to_string('acc_active_email.html', { 'user': user, 'domain': current_site.domain, 'uid':urlsafe_base64_encode(force_bytes(user.pk)), 'token':account_activation_token.make_token(user), }) to_email = form.cleaned_data.get('email') email = EmailMessage( mail_subject, message, to=[to_email] ) email.send() return HttpResponse('Please confirm your email address to complete the registration') else: form = SignUpForm() return render(request, 'signup.html', {'form': form}) def activate(request, uidb64, token, backend='django.contrib.auth.backends.ModelBackend'): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = CustomUser.objects.get(pk=uid) except(TypeError, ValueError, … -
Django complex date filter
I couldn't find relative answer, I have sql table like: +------------+---+----+---+ | date | x | y | z | +------------+---+----+---+ | 2019-01-01 | 1 | 3 | 5 | | 2019-01-02 | 2 | 10 | 2 | | 2019-01-03 | 5 | 4 | 3 | +------------+---+----+---+ Can you please suggest me an efficient query to get data below: "x": { "today": int, "yesterday": int, "this_week": int, "last_week": int, "this_month": int, "last_month": int, "this_year": int, "all_times": int }, "y": { "today": int, "yesterday": int, "this_week": int, "last_week": int, "this_month": int, "last_month": int, "this_year": int, "all_times": int }, "z": { "today": int, "yesterday": int, "this_week": int, "last_week": int, "this_month": int, "last_month": int, "this_year": int, "all_times": int } I can get one column daily or monthly but I couldn't combine them. -
Technique of using if, elif and Else statement in Django python
Let me start with my code for better understanding. models Items(models.Model): first_frame = models.ManyToManyField(settings.AUTH_USER_MODEL,blank=True, default=None,related_name='frame_one') second_frame = models.ManyToManyField(settings.AUTH_USER_MODEL,blank=True, default=None,related_name='frame_two') View def choose_frame(request): frame = get_object_or_404(Item, id=request.POST.get('frame_id')) is_frame_one=False is_frame_two=False if frame.first_frame.filter(id=request.user.id).exists(): frame.first_frame.remove(request.user) is_frame_one=False else: frame.first_frame.add(request.user) is_frame_one=True elif frame.second_frame.filter(id=request.user.id).exists(): frame.second_frame.remove(request.user) is_frame_two=False else: post.first_frame.add(request.user) is_frame_two=True if request.is_ajax(): context={'frame':post, 'is_frame_one':is_frame_one} html=render_to_string('business/frame.html', context, request=request) return JsonResponse({'form':html}) If you take a look at my view, you'll understand I've an if statement were if the user exist the first frame should be removed, Else, you can add frame. But I've another frame in my models just like my first frame called second frame. I want to make the exact functionality, but seems the elif is not the right coding. Thanks for your assistance in advance -
run long process in django without celery and multiprocess
i have a project which gets large csv file from user and process it in django view with multithreading. i can't use multiprocess because process contains external objects which can't be pickled. celery have similar problem with pickling data. I want to use view which handles this large CSV process externally and don't wait for process to complete. and if anyone refresh the page same view calls and another 2 threads creates and i want to prevent to create a new thread. i have something like this code: q = Queue() def view(request): t1 = Thread(target = threadfunction, args=(request,csvdata)) t2 = Thread(target = threadfunction, args=(request,csvdata)) q.put(t1) 1.put(t2) t1.start() t2.start() t1.join() t2.join() data = [] while not q.empty(): data.extend(q.get()) return HttpResponse(str(data)) def threadfunction(receiverequest,csvdata): # reading csv and doing some process takes 100secs returns #somelistdata -
"detail": "Method \"GET\" not allowed." in TokenAuthentication Django rest framework
I am trying to build a token-based authentication system by following https://www.django-rest-framework.org/api-guide/authentication/. But on sending a request, I am getting an error msg as a response: { "detail": "Method "GET" not allowed." } Here is what I have tried so far: urls.py urlpatterns = [ path('api-token-auth/', views.obtain_auth_token), ] models.py @receiver(post_save, sender=settings.AUTH_USER_MODEL) def create_auth_token(sender, instance=None, created=False, **kwargs): if created: Token.objects.create(user=instance) views.py def index(request): return render(request,'index.html') Any help would be beneficial. -
Use python packages from another docker container
How can I use python packages from another container? ydk-py is set up with everything that I need, including all python packages and their dependencies. I want to use those python packages in my django application. However python imports packages installed in my main container, web, and not ydk-py. docker-compose: version: '3.7' services: web: container_name: webserver build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code/ ports: - 8000:8000 env_file: - .env.dev depends_on: - db db: container_name: database image: postgres:13.0-alpine volumes: - postgres_data:/var/lib/postgresql/data/ env_file: - .env.dev ydk-py: container_name: ydk-py image: ydkdev/ydk-py:latest tty: true volumes: postgres_data: Dockerfile: FROM python:3.6.12-alpine WORKDIR /code ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN apk update && apk add jpeg-dev zlib-dev postgresql-dev gcc python3-dev musl-dev RUN pip install --upgrade pip COPY ./requirements.txt /code/requirements.txt RUN pip install -r requirements.txt COPY ./entrypoint.sh /code/entrypoint.sh COPY . /code ENTRYPOINT ["sh", "/code/entrypoint.sh"] -
Django Rest Framework - Validate email before updating
I need to add a condition in updating the user model. Here is my serializers.py class UserDetailsSerializer(serializers.ModelSerializer): email = serializers.EmailField() def validate_email(self, email): if User.objects.filter(email=email).exists(): raise serializers.ValidationError("Email exists") return email class Meta: model = User fields = __all__ Am I doing this right or I have to add an additional update function? I am new to Django and I'm not quite familiar yet with its structure and with the serializer and default functions. In this function, my goal is only to update the specific email value. the other values should be the same. -
Perform async task in view and return response before it's finished
Let's say I have a view like this in rest-framework which retrieves same data to be saved. class MyView(generics.CreateAPIView) def get(self, request): data = # logic to save data here. response data My question is if there's a neat solution to between saving the data and returning a response it's possible to make an asynchronous call to a method which will process some of the new data in the database. So I would like for Django to NOT wait for that method to finish running since that would make the response to the user very slow and it might time-out depending on server config. class MyView(generics.CreateAPIView) def get(self, request): data = # logic to save data here. # send async call to method which django does not wait for. response data -
How to use BlacklistView ('rest_framework_jwt.blacklist') in django
I need to implement logout in django project. For login I use JWT token(rest_framework_jwt). For logout I want to use BlacklistView, but I didn't find any examples how to implement it. Could someone provide me some example of usage BlacklistView? -
Not Found: /build/three.module.js Django and Threejs uploading a OBJ file
i would be very grateful if someone help me, i've traying upload a obj file with Django and threejs but i get this error:enter image description here 1: https://i.stack.imgur.com/ti131.png also i'm uploading images JPG and PNG too and this upload correctly but the obj imge doesn't work in my localhost. then, i don´t know if i'm importinting well the module or if my static files are wrong 'use strict'; import * as THREE from '../build/three.module.js' import { TrackballControls } from "../jsm/controls/TrackballControls.js"; import { MTLLoader } from "../jsm/loaders/MTLLoader.js"; import { OBJLoader2 } from "../jsm/loaders/OBJLoader2.js"; import { MtlObjBridge } from "../jsm/loaders/obj2/bridge/MtlObjBridge.js"; this is a part of my TrackballControls.js import { EventDispatcher, MOUSE, Quaternion, Vector2, Vector3 } from '../build/three.module.js'; {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>three.js webgl - OBJLoader2 basic usage</title> <meta charset="utf-8"> {% load static %} <meta name="viewport" content="width=device-width, user-scalable=no, minimum-scale=1.0, maximum-scale=1.0"> <link rel="stylesheet" type="text/css" href="{% static 'css/site.css' %}" /> <style> #glFullscreen { width: 100%; height: 100vh; min-width: 640px; min-height: 360px; position: relative; overflow: hidden; z-index: 0; } #example { width: 25%; height: 50%; margin-top: 250px; margin-left: 1010px; background-color: #000000; } #feedback { color: darkorange; } #dat { user-select: none; position: absolute; left: 0; top: 0; z-Index: 200; } … -
Django admin list filter calculated field based on two fields
I have a django model shown here. class Allocation(models.Model): allocated = models.IntegerField(default=5) used = models.IntegerField(default=0) user = models.ForeignKey(to=User, on_delete=models.CASCADE) I use a calculated field as follows. def limit_exceeded(self, obj): return obj.allocated == obj.used I want to use the same logic to use it on the list_filter. But SimpleListFilter only allows one parameter_name and no way to use both fields to check the condition. How can I achieve this? -
Gitlab CI/CD deploy Django Docker container
I have been tring to setup gitlab ci/cd config for a django project which will be deployed as a container. This is what i have tried: CI/CD - image: creatiwww/docker-compose:latest services: - docker:dind stages: - lint - build - deploy variables: TAG_LATEST: $CI_REGISTRY_IMAGE/$CI_COMMIT_REF_NAME:latest TAG_COMMIT: $CI_REGISTRY_IMAGE/$CI_COMMIT_REF_NAME:$CI_COMMIT_SHORT_SHA lint: stage: lint image: python:3.8 before_script: - pip install pipenv - pipenv install --dev script: - pipenv run python -m flake8 --exclude=migrations,settings.py backend allow_failure: false build: stage: build script: - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY_IMAGE - echo "IMAGE_APP_TAG=$TAG_LATEST" >> .env - docker-compose build - docker-compose push only: - master deploy-to-prod: stage: deploy script: - eval $(ssh-agent -s) - echo "${ID_RSA}" | tr -d '\r' | ssh-add - > /dev/null - docker login -u gitlab-ci-token -p $CI_BUILD_TOKEN $CI_REGISTRY_IMAGE - echo "IMAGE_APP_TAG=$TAG_LATEST" >> .env - echo "SECRET_KEY=$SECRET_KEY" >> .env - docker-compose -H "ssh://$SERVER_USER@$SERVER_IP" down --remove-orphans - docker-compose -H "ssh://$SERVER_USER@$SERVER_IP" pull - docker-compose -H "ssh://$SERVER_USER@$SERVER_IP" up -d only: - master when: manual The pipeline succeds but while checking the log of container i get following output- python: can't open file 'manage.py': [Errno 2] No such file or directory also my image field in docker ps is emoty. Please help -
Django, guidelines for writing a clean method for a ModelChoiceField
I have read the docs and I can only find guidelines on how to write a clean method for a field within a form: https://docs.djangoproject.com/en/3.1/ref/forms/validation/#cleaning-a-specific-field-attribute However I have created a field which inherits from ModelChoiceField. I wish to add some custom validation and cleaning, attached to the field and not the form, because the field is used in multiple forms, hence keeping it DRY. I can take a stab at creating a clean method, but eactly what args are passed in, and what should be returned seems to be lacking in the documentation, or I can't find it. Here my field that I wish to add custom cleaning and validation to: class FooChoiceField(forms.ModelChoiceField): def __init__(self, required=True): queryset = Foo.objects.filter(enabled=True).order_by('name') super().__init__( widget=forms.RadioSelect, queryset=queryset, to_field_name='id', # The radio button value field required=required, empty_label=None, ) self.error_messages = { 'required': "Please select a Foo.", 'invalid_choice': "Invalid Foo selected, please try again.", } # Pass the whole DB object into the template so one can access all fields def label_from_instance(self, obj): return obj Heres a guess at it? Is it good, bad? How about validation? def clean(self, value): if value != 'correct': raise ValidationError('Value is challenged in it's correctness') return value -
RuntimeWarning: DateTimeField received a naive datetime, with correct timezone and settings
I am receiving this error message: RuntimeWarning: DateTimeField Z.data_zal received a naive datetime (2020-11-05 07:13:24) while time zone support is active. warnings.warn("DateTimeField %s received a naive datetime (%s)" At this step of creating my models instance: views.py from django.utils import timezone t = Z(data_z=timezone.now().strftime('%Y-%m-%d %H:%M:%S'), data_r=data_r, author=request.user) try: t.save() So as far as I know this error occurs when using datetime module instead of timezone. Sometimes the problem lies in wrong settings.py but I am running: TIME_ZONE = 'Europe/Warsaw' USE_TZ = True What seems to be the issue? -
Datatables Pagination Does Not Show
What I'm trying to do is set up a table just like this: https://datatables.net/examples/basic_init/alt_pagination.html Copied the code but then no success. I've tried so many different variables and removing all but the necessary code and I'm at a loss for what the issue may be. I've gone through several other similar SOF questions and some mentioned "sDom" could be the case so I tried a few variations I've found online but no luck yet. table.html {% extends "dashboard/base.html" %} {% load i18n %} {% block content %} {% block styles %} <script type="text/javascript" href="https://code.jquery.com/jquery-3.5.1.js"></script> <script type="text/javascript" href="https://cdn.datatables.net/1.10.22/js/jquery.dataTables.min.js"></script> <link rel="stylesheet" type="text/css" src="https://cdn.datatables.net/1.10.22/css/jquery.dataTables.min.css"> {% endblock styles %} <!-- Page Heading --> <div class="d-sm-flex align-items-center justify-content-between mb-4"> <h2 class="text-gray-800">{% block title %}{% trans "Imported Entries" %}{% endblock %}</h2> <a role="button" class="btn btn-success" href="{% url 'import' %}"><i class="fas fa-plus-circle"></i> Import New Entires</a> </div> <!-- Content Row --> <div class="row"> <div class="col-md-12"> <table id="example" class="table table-striped table-bordered" style="width:100%"> <thead> <tr> <th>Name</th> <th>Position</th> <th>Office</th> <th>Age</th> <th>Start date</th> <th>Salary</th> </tr> </thead> <tbody> <tr> <td>Tiger Nixon</td> <td>System Architect</td> <td>Edinburgh</td> <td>61</td> <td>2011/04/25</td> <td>$320,800</td> </tr> <tr> <td>Garrett Winters</td> <td>Accountant</td> <td>Tokyo</td> <td>63</td> <td>2011/07/25</td> <td>$170,750</td> </tr> <tr> <td>Ashton Cox</td> <td>Junior Technical Author</td> <td>San Francisco</td> <td>66</td> <td>2009/01/12</td> <td>$86,000</td> </tr> <tr> <td>Cedric Kelly</td> <td>Senior … -
View uploaded files for specific object in django
I want to upload files to a client. So when I check the client they all show the same uploaded files. How do I filter through the files to show only for the specific clients who have files added to them? Model: class Document(models.Model): client = models.ForeignKey(Client,on_delete=models.CASCADE, related_name='docs') title = models.CharField(max_length=50) docs = models.FileField() Views.py: def fileDetails(request,pk): files = UploadFile.objects.all() client = Client.objects.all() notes = Note.objects.all() docs = Document.objects.all() context = {'files':files,'client':client,'notes':notes,'docs':docs} return render(request, 'clients/file_detail.html',context) Forms.py: class DocumentForm(forms.Form): file_field = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) I tried using a filter but nothing shows on any of my queries. I just would like to see the docs updated on a client and not see the same for all. Might be something I missed or I'm overthinking this query. -
Get_Absolute_URL Reverse Slugs By Many To Many Field From Another Model in Django
I use Slugs to address the URL. It all works but when I want to show product details. I don't know how can I get two slugs from another model and put it beside the details slug. (the category is in the main URL) (show me all products Samsung mobile) Works: site.com/category/mobile/samsung/ (I want when I want to click one of them, show me the details, but it doesn't work) Doesn't Work: site.com/category/mobile/samsung/s10 Model: from Django.db import models from Django.shortcuts import reverse class Category(models.Model): name = models.CharField(max_length=150) slug = models.SlugField(unique=True, max_length=200) child_category = models.ForeignKey('self', max_length=150, null=True, blank=True, on_delete=models.CASCADE) is_child = models.BooleanField(default=False) def get_absolute_url(self): return reverse('shop:brands', args=[self.slug]) def get_absolute_url_product(self): return reverse('shop:products', args=[self.child_category.slug, self.slug]) class Product(models.Model): category = models.ManyToManyField(to=Category, related_name='products') name = models.CharField(max_length=150) slug = models.SlugField(unique=True, max_length=200) description = models.TextField() # Here I did what I knew, but It didn't work. =============================================== def get_absolute_url_details(self): return reverse('shop:product_details', self.category.model.slug, self.category.model.child_category.slug, self.slug) When I use this reverse way, it gives me this Error: 'ForwardManyToOneDescriptor' object has no attribute 'slug' URL: from Django.urls import path from Shop import views app_name = 'shop' urlpatterns = [ path('<slug:brands_slug>/', views.brands, name='brands'), path('<slug:brands_slug>/<slug:product_slug>/', views.products, name='products'), path('<slug:brands_slug>/<slug:product_slug>/<slug:product_details>/', views.details_products, name='product_details'), ] View: def products(request, brands_slug, product_slug): product = Product.objects.filter(category__slug=product_slug, category__child_category__slug=brands_slug) context = … -
Django: how to change the width of AdminDateWidget?
In admin page, I am trying to customise the width of DateField by tweaking attrs of AdminDateWidget in formfield_overrides as below formfield_overrides = { models.DateField: { 'widget': admin.widgets.AdminDateWidget(attrs={'size': '8', 'style': 'width:8ch !important;'}), } } Either changing the size nor style works. What should I do to change the width? Thank you! -
calculate numbers of anuual leave for employees every month
I have Django program for calculating salary of every employee and detect leave days that taken in this month from salary ,the problem that some of employee they apply for leave before like one or to month and program start detecting from salary in month that they apply , so can I write code that can detect from salary only if leave date in the current month. -
Is there any method of integrating ReactJS and Django without implementing Django Restful API?
Guys as you may know when using Vanilla JS you can just deliver html files to Django and just code between the lines in Python language in order to create the functionalities that you need in your backend side of your web application. However this is not the case when we use React JS. Is there any similar way(as vanilla JS and html files)for integrating REACT.JS and Django(except for using rest api endpoints)? -
Django python ValueError: not enough values to unpack (expected 2, got 1)
I have this code to in my views.py that will export to excel, i combined two query in 1 loop but i receive this error ValueError: not enough values to unpack (expected 2, got 1) reports = TrEmployeeSuppliersFeedbackQuestionsSubmittedRecords.objects.filter( fmCustomerID__company_name__in=company.values_list('fmCustomerID__company_name')).order_by('-inputdate') daily = FmCustomerEmployeeSupplier.objects.filter(id__in=reports.values_list('fmCustomerEmployeeSupplierID')) pairs = [reports, daily] for report, day in pairs: writer.writerow( [ smart_str(report.id), smart_str(report.dateSubmitted), smart_str(report.fmCustomerEmployeeSupplierID), # smart_str(report.fmCustomerEmployeeSupplierID.lastname), # smart_str(report.fmCustomerEmployeeSupplierID.middleInitial), smart_str(day.fmCustomerLocationID), smart_str(day.contact_number), smart_str(day.fmCustomerSectionID), smart_str(day.bodyTemperature), smart_str(report.q1Answer), smart_str(report.q2Answer), ] ) return response -
perform_create function in the django view. How it is different from create function?
I am new to django rest api. I need to create a comment api which is posted in database for a particular blogdetail page. But I dont understand this perform_create function? What does this method does and how it is different in create function?? class CommentCreateAPIView(CreateAPIView): permission_classes= [IsAuthenticated] queryset = Comment.objects.all() serializer_class = CommentListSerializer def perform_create(self, serializer): # user = self.request.user blog = get_object_or_404(BlogPost, pk= self.kwargs['pk']) serializer.save(blog=blog) class BlogPostDetailSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name='api-blog-post_details', read_only=True) comments= CommentListSerializer (many=True) class Meta: model = BlogPost fields = ['id', 'url', 'image', 'categories', 'description', 'content', 'tags', 'date_created', 'comments'] # fields = '__all__' class Comment(models.Model): # user = models.ForeignKey(User, on_delete=models.CASCADE) blog = models.ForeignKey(BlogPost, on_delete=models.CASCADE, related_name='comments') name = models.CharField(max_length=255) email = models.EmailField() subject = models.CharField(max_length=255) comment = models.TextField() created_at = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) class Meta: ordering = ('created_at',) Also, when I used 'user' in that perform_create function inside serializer.save, it generates error. what is the issue?