Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
To pass the Response from the nested function `Django REST framework`
I am using python django with Django REST framework It can return the Reponse to the browser like this, in the views.py from rest_framework.response import Response @api_view(['GET']) def get_by(request): res = {"test":"answer"} return Response(res) I want to pass the Response to the browser where nested function from rest_framework.response import Response @api_view(['GET']) def get_by(request): x(t) def x(): #error happens here!! res = {"error":"error happens!!"} return Response(res) in this case, it is simple, I can return the error to the first function and first function can return the error Response. but when you have three four,five nested function? What is the best practice? -
Setting up a good python development environment/editor
I've been developing a project web application in VSCode, using eslint and prettier. It's great and saves me a lot of time. I'm trying to setup a similar environment for a django project, but I'm either lacking a lot of features (no automatic linting, no intellisense) or Pylance is throwing errors like Expected class type but received "LazySettings" Cannot access member "XX" for type "YY" I've tried using the template (https://github.com/wemake-services/wemake-django-template) to combat some of these issues, but I end up in the same place. It feels like I'm lacking some fundamental knowledge. I am able to run the server without issues. Using python 3.9.10. Any suggestions (new editor, vscode settings, stubs) would be very appreciated. -
Автозаполнение поля формы получая id вопроса django
Создаю свой форум. Пытаюсь сделать ответы на вопросы я сделал автозаполнение поле User_id в таблице Quetions и а таблице Answer user_id : models.py class Quetions(models.Model): User_id = models.ForeignKey (User,to_field='id',on_delete=models.DO_NOTHING,verbose_name='Пользователь',blank=True) category_id = models.ForeignKey (Category,to_field='id',on_delete=models.DO_NOTHING,verbose_name='Предмет') schoolclass = models.ForeignKey (SchoolClass,to_field='id',on_delete=models.DO_NOTHING,verbose_name='Класс') subject = models.CharField(max_length=255,verbose_name='Тема вопроса') text = models.TextField(verbose_name='Вопрос') img = models.ImageField(blank=True) date_published = models.DateTimeField(auto_now_add=True) def __str__(self): return f'Тема {self.subject}' class Meta: verbose_name_plural = 'Вопрос' class Answer(models.Model): id_questions = models.ForeignKey(Quetions,to_field='id',on_delete=models.DO_NOTHING,verbose_name='К какому вопросу',blank=True) user_id = models.ForeignKey. (User,to_field='id',on_delete=models.DO_NOTHING,verbose_name='Пользователь', blank=True) Text = models.TextField(verbose_name='Вопрос') date_published = models.DateTimeField(auto_now_add=True) def __str__(self): return f'Тема {self.id_questions}' class Meta: verbose_name_plural = 'Ответ' Автозаполнение в двух таблицах я сделал так: views.py def Questions(request): if request.method == 'POST': user = request.user form = QuestionsForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.User_id = user form.save() return redirect('/') else: return redirect('/') else: form = QuestionsForm() model = Quetions.objects.all() return render(request, 'Questions.html', {'form': form,'model':model}) Не понимаю как сделать автозаполнение поле id_questions в таблице Answer? Заранее СПАСИБО -
Django Rest Swagger Not showing up all the APIs
I am working with Django Rest swagger. But it's not showing up all the APIs. The url paths for /tickets are missing: Even path to /dj-rest-auth/user/ is missing as well: Backend/urls.py from django.contrib import admin from django.urls import path, include from rest_framework_swagger.views import get_swagger_view schema_view = get_swagger_view(title='API') urlpatterns = [ path('admin/', admin.site.urls), #path('api/v1/', include(api_urlpatterns)), #path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/', include('dj_rest_auth.urls')), path('dj-rest-auth/registration/', include('dj_rest_auth.registration.urls')), path('api/', include('ticket.urls')), path('swagger/', schema_view) ] Tickets/urls.py from django.urls import path from ticket import views urlpatterns = [ path('tickets/', views.ticket_list), path('tickets/<int:pk>/', views.ticket_detail), ] My directory structure: -
Override dispatch() method in PasswordResetConfirmView
I have written a class that inherits from PasswordResetConfirmView PasswordResetConfirmView can be found here: https://github.com/django/django/blob/7f4fc5cbd4c26e137a1abdd9bd603804ddc0e769/django/contrib/auth/views.py#L260 For what it's worth here is the part of the class that I have written (nothing ground breaking I know!): class PwdResetConfirm(PasswordResetConfirmView): template_name = 'account/password_reset_confirm.html' success_url = reverse_lazy('two_factor:login') form_class = PwdChangeForm What I want to do is change the behaviour of PasswordResetConfirmView dispatch() method so that a message is created if a password reset is unsuccessful, so the lines in PasswordResetConfirmView: # Display the "Password reset unsuccessful" page. return self.render_to_response(self.get_context_data()) would effectively become: messages.success(self.request, _(mark_safe( 'Your password change link appears to be invalid.'))) # Display the "Password reset unsuccessful" page. return self.render_to_response(self.get_context_data()) I am new to overriding classes and as such,I am not even sure where to start. In summary, my question is: How can I add the message to PasswordResetConfirmView class's dispatch() method without overriding the entire method? -
django-activity-stream and django-comments-xtd
On a django project i'm using both django-activity-stream and django-comments-xtd, Is there a way to build a stream of the comments posted via the django-comments-xtd package ?? because obviously I will not modifiy the code of the comment package... to add action in it (see action help in the help) How am I supposed to do so ?? Thanks for your help -
how to join in queryset
I have some problems with QuerySet in Django python. I have 2 tables/models. class PP(models.Model): imei = models.BigIntegerField(primary_key=True) name = models.CharField(max_length = 50) val2 = models.IntegerField(default = 0) def __str__(self): return self.name class Mea(models.Model): imei = models.ForeignKey(PP, on_delete=models.CASCADE) v1 = models.IntegerField(default = 0) v2 = models.IntegerField(default = 0) v3 = models.IntegerField(default = 0) dates = models.DateField(default=datetime.date.today) def __str__(self): return self.imei PP +----+--------+------+ |imei| name | val2 | +----+--------+------+ | 1 | john | 12 | | 2 | adam | 5 | | 3 | alfred | 3 | +----+--------+------+ Mea +----+----+----+-----+---------------------+ |imei| v1 | v2 | v3 | date | +----+----+----+-----+---------------------+ | 1 | 4 | 15 | 18 | 2020-10-16 11:15:53 | | 1 | 2 | 12 | 17 | 2020-10-16 11:22:53 | | 1 | 3 | 13 | 16 | 2020-10-16 11:32:53 | | 2 | 1 | 16 | 15 | 2020-10-16 13:22:53 | | 2 | 3 | 13 | 25 | 2020-10-16 13:42:53 | | 2 | 4 | 12 | 35 | 2020-10-16 14:12:53 | | 3 | 1 | 21 | 12 | 2020-10-16 14:12:53 | | 3 | 2 | 28 | 42 | 2020-10-16 15:12:53 | | 3 … -
Calling value from ajax to Django views
Im confused why it returns None when I print the value that comes from ajax, I used request.POST.get("ajaxvalue") to get the value from ajax requests but it didn't work, can anyone know what's the problem I encountered? it's very helpful for me. views.py @csrf_exempt def updateStatus(request): if request.method=="POST": taskId = request.POST.get('id') source = request.POST.get("sources") target = request.POST.get('targets') print(taskId); print(source); print(target); return JsonResponse({'datas': 'test'}) html ajax $.ajax({ data: { id, 'sources':0, 'targets':1 }, url: "{% url 'updateStatus' %}", type: 'POST', cache: false, contentType: false, processData: false }) .done(function(data){ console.log("success"); }); urls.py urlpatterns = [ path('updateStatus/',views.updateStatus, name='updateStatus'), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) -
Using geograpy4 on server
URGENT!!!!!!!!!! NEED HELP!!!!!! ----- i've install geograpy4 on my centos7 server because i wrote a function that could detect a citiy's name on an extracted text. it walked fine when working in local but when i try it on server an error was throwed as shown in the first picture. the 3rd picture is the code portion where i use geograpy4. i want to precise that before geograpy4 i was using locationtagger and it gave me the same error so i'm thinking that it's nltk the problem but i'm not sur... -
Getting the origin (absolute path) of a uploaded file in Django
In my django app I ask for files. The user can select multiple audio files via: django.forms.ClearableFileInput(attrs={'multiple': True}) However, for my use case the absolute file paths were the selected files originated from is important. When I access the files with request.FILES.getlist(), I can only see the name of the selected file, but not the full path. How do I get the absolute paths? -
Django-Models extend Data
Is there any way to extend the Information created in one Model Class to another? I want to have all Informations that someone created in Admin for "Form" in class "Test" aswell for further evaluation. from django.db import models import requests as rq class Form(models.Model): ipName = models.CharField(max_length=100) ipAddress = models.CharField(max_length=100) ipKey = models.CharField(max_length=100) ipSecret = models.CharField(max_length=100) ipMask = models.CharField(max_length=100) ipWahrheit = models.BooleanField(default=True) def __str__(self): URL = "https://" + self.ipAddress Key = self.ipKey Secret = self.ipSecret r = rq.get(f'{URL}/api/routes/gateway/status', auth=(Key, Secret), verify=False) return self.ipName + str(r) + "Test" class Test (Form): pass -
Forms dont populate with data on edit with Django 4
I have make an override on my User class, i have add fields. I have make a template for update the fields of the User class. But the problem is i have only some fields having a data. "Firstname, Lastname" This is my views for editing an user: # Vue de la page User (édition) @staff_member_required(login_url='user_login') def admin_users_edit(request, pk): if request.method == "POST": user = User.objects.get(id=pk) form = UserEditForm(instance=user, data=request.POST) if form.is_valid(): user.save() messages.add_message(request, messages.SUCCESS, "L'utilisateur à bien été modifié") return redirect('admin_users_index') else: print(form) print("Invalid Form") print(form.errors) return redirect('admin_departements_index') else: user = User.objects.get(id=pk) form = UserEditForm(instance=user) return render(request, 'back/users/edit.html', {"user":user,"form":form}) And this is my forms, i have try to render the checkox with different solutions, but the radio or checkbox dont populate with the data, they are empty on the form... # Formulaire de l'édition d'un utilisateur YES_OR_NO = ( (True, 'Oui'), (False, 'Non') ) class UserEditForm(forms.ModelForm): username = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Pseudo','autocomplete':'off'})) first_name = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Prénom','autocomplete':'off'})) last_name = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Nom','autocomplete':'off'})) email = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Pseudo','autocomplete':'off'})) password = forms.CharField(label="", help_text="", widget=forms.PasswordInput(attrs={'class': 'form-control', 'placeholder':'Mot de passe','autocomplete':'off','required':'false'})) phone = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Téléphone fixe','autocomplete':'off'})) mobile = forms.CharField(label="", help_text="", widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder':'Portable','autocomplete':'off'})) is_staff … -
How to get a CharField's value as a string inside the model class?
class Comment(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='commenter', null=True) txt = models.CharField(max_length=1000, null=True) summary = str(txt)[:30] + '...' how can I get txt's value as a string and save it in summary? The code above returns somthing like this as string: <django.db.models.fields.CharF... -
How to to make Django default id (pk) to random and bigger in length
I am creating an where in my model Profile i am getting the default id with the name id, but the issue it is generating ids from 0 to onwards like 1,2,. What I want is a random id which should also be longer length like 343347 etc. -
Django/wagtail admin page links pointing to invalid address
I have a wagtail site and have a problem with the ‘users’ section of the admin page My users/admin.py is : from django.contrib import admin from django.contrib.auth import admin as auth_admin from django.contrib.auth import get_user_model from psymatik.users.forms import ( UserChangeForm, UserCreationForm, ) User = get_user_model() admin.site.register(User) class UserAdmin(auth_admin.UserAdmin): form = UserChangeForm add_form = UserCreationForm fieldsets = ( ("User", {"fields": ("username",)}), ) + auth_admin.UserAdmin.fieldsets list_display = ["username", "is_superuser"] search_fields = ["username"] And my users/wagtail_hooks.py is: from wagtail.contrib.modeladmin.options import ModelAdmin, modeladmin_register from .models import User class UserAdmin(ModelAdmin): model = User menu_label = "Users" menu_icon = "pick" menu_order = 200 add_to_settings_menu = False exclude_from_explorer = False list_display = ( "name") list_filter = ("name") search_fields = ("name") modeladmin_register(UserAdmin) The issues I have is that when I am at admin/users and I click on the Users link in the sidebar I am taken to admin/users/user and get the error “ValueError at /admin/users/user/ Field 'id' expected a number but got 'user’.” Why is the sidebar link pointing to admin/users/user rather than just admin/users (which does work)? What is the best way to set this up? -
Why Django ignores the order of conditions in filter()?
When filtering multiple conditions with Django queryset filter(), the order of conditions in filter() is not guaranteed. Especially when I filter date/datetime fields, they're filtered at the last in the WHERE clause. These two querysets generate the same SQL with the same WHERE clause. dt = datetime(2022, 1, 1) User.objects.filter(joined_at__lt=dt, is_active=True) User.objects.filter(is_active=True, joined_at__lt=dt) SELECT * FROM `user` WHERE (`user`.`is_active` = 1 AND `user`.`joined_at` < '2022-01-01 00:00:00') I know I can fix this problem with chaining filters. But I'm wondering why Django ignores the order of conditions in filter(). And what is the rule for Django to decide the order in the filter()? -
Filter in the template if the product is in wishlist or no. Django ecommerce website
I had a question about django-templates. I was wondering about if we can add a filter in django template. I want to know if the product is in wishlist or no while rendering it. So, how can we know if it's in the wishlist or no? views.py def store(request): data = cartData(request) cartItems = data['cartItems'] order = data['order'] items = data['items'] categories = Category.objects.all() products = Product.objects.all() if request.user.is_authenticated: user=request.user wishedProducts = Wishlist.objects.filter(user=user) else: wishedProducts = {} """popularnye = Product.objects.filter(popularnye=True)""" context = {'products':products, 'cartItems':cartItems, 'order':order, 'items':items, 'categories':categories,'wishedProducts':wishedProducts} return render(request, 'store/store.html', context) models.py class Wishlist(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, verbose_name="Название товара",null=True) user = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: unique_together = ( ('user', 'product'), ) verbose_name = 'Избранные' verbose_name_plural = "Избранные" def __str__(self): return str(self.product) template {% for product in products %} <div class="store col-lg-3 col-6"> <div class="single-product"> <div class="single-product"> <div class="header-single-product"> <p style="margin-top:-10px;margin-bottom:-10px" class="code">Код: 51265</p> {% if product in wishedProducts.products %} <i class="bi bi-heart-fill addWishlist" style="color: red" data-product="{{product.id}}" data-action="add"></i> {% else %} <i class="bi bi-heart addWishlist" data-product="{{product.id}}" data-action="add"></i> {% endif %} <i class="fa fa-balance-scale" style="margin-right:5px;"></i> ........ -
Serializer gets null for columns in a table in a foreign key’s reverse direction
In a scenario of transaction processing, we have: table order to record incoming transactions, and table order_log to log updates on a recorded order, with a foreign key to table order. A recorded order may have zero to multiple updates on the log. We want to make a flattened view of the two tables like a SQL query selecting from order left outer join order_log, with the following behaviour: if the order has no update, list the order in joint with null values; if the order has one update, list the order in joint with the update log; if the order has multiple updates, list the order multiple times in joint with each update log. As the sample source code below, we used .prefetch_related('orderlog_set'), and it gets the wanted flattening effect, and the Django backend log shows a left-outer-join SQL query sent to the database as expected. So, the mutual relation works correctly for all the three conditions above. However, we cannot retrieve columns in order_item, as the table is in a foreign key's reverse direction. The serializer FlatOrderLogSerializer bases its meta-model on the table order, so it refers to table order_log by a foreign key's reverse or backward direction. … -
No matching distribution found for django-modeltranslation==0.17.3
I want to install an existing Django project which has dependencies. The project dependencies can be installed with pipenv install command. Running pipenv install resulting: pipenv install /home/mahdi/anaconda3/lib/python3.9/site-packages/pkg_resources/__init__.py:122: PkgResourcesDeprecationWarning: 4.0.0-unsupported is an invalid version and will not be supported in a future release warnings.warn( Pipfile.lock (6ab9a1) out of date, updating to (5b3760)... Locking [dev-packages] dependencies... Building requirements... Resolving dependencies... ✔ Success! Locking [packages] dependencies... Building requirements... Resolving dependencies... ✘ Locking Failed! ERROR:pip.subprocessor:Command errored out with exit status 1: command: /home/mahdi/.local/share/virtualenvs/WeSync-UUOFIsQX/bin/python /tmp/pip-standalone-pip-qah9wd89/__env_pip__.zip/pip install --ignore-installed --no-user --prefix /tmp/pip-build-env-gm4__bne/overlay --no-warn-script-location --no-binary :none: --only-binary :none: -i https://pypi.org/simple -- 'setuptools>=40.8.0' wheel cwd: None Complete output (17 lines): Traceback (most recent call last): File "/home/mahdi/anaconda3/lib/python3.9/runpy.py", line 197, in _run_module_as_main return _run_code(code, main_globals, None, File "/home/mahdi/anaconda3/lib/python3.9/runpy.py", line 87, in _run_code exec(code, run_globals) File "/tmp/pip-standalone-pip-qah9wd89/__env_pip__.zip/pip/__main__.py", line 16, in <module> File "<frozen zipimport>", line 259, in load_module File "/tmp/pip-standalone-pip-qah9wd89/__env_pip__.zip/pip/_internal/cli/main.py", line 10, in <module> File "<frozen zipimport>", line 259, in load_module File "/tmp/pip-standalone-pip-qah9wd89/__env_pip__.zip/pip/_internal/cli/autocompletion.py", line 9, in <module> File "<frozen zipimport>", line 259, in load_module File "/tmp/pip-standalone-pip-qah9wd89/__env_pip__.zip/pip/_internal/cli/main_parser.py", line 7, in <module> File "<frozen zipimport>", line 259, in load_module File "/tmp/pip-standalone-pip-qah9wd89/__env_pip__.zip/pip/_internal/cli/cmdoptions.py", line 24, in <module> File "<frozen zipimport>", line 259, in load_module File "/tmp/pip-standalone-pip-qah9wd89/__env_pip__.zip/pip/_internal/exceptions.py", line 10, in <module> ModuleNotFoundError: No module named … -
Validate form data and query params in one serializer in APIView in django rest framework
I am using django rest framework for my web API. In my post API I need both the form data and the query params from the request and pass it to serializer for validation. To achieve this I am doing this: version = request.query_params.get('version', 'v1') serializer = MySerializer( data=request.data, context={'version': version}) and in the serializer I am accessing it like this: version = serializers.CharField(required=False, default='v1') and then accessing it in my APIView as: if serializer.is_valid(): data = serializer.validated_data print("version: ", data['version']) Even if I pass v2 as the query params it always prints v1. What am I doing wrong here? -
Best way to get chatroom from a consumer - Django channels
I want to store messages sent through a django-channels websocket connection to be stored in the db. This interaction would happen in the recieve function of the consumer(I would think). I need the chatroom model which this chat is happening in. I can get the pk of the chatroom(its in the url) but it seems like a bad idea to make a query for the room every time that a message is sent. Anyone got better ideas? -
Django - Cannot find URL "Using the URLconf defined in contactform.urls, Django tried these URL patterns, in this order"
I am able to successfully compile my program, but when I go to the localhost address, it gives me an error. I have searched other forums about the same problem, but I couldn't find a solution for mine. Am I missing something here? I'm new to Django, so any is appreciated. Using the URLconf defined in contactform.urls, Django tried these URL patterns, in this order: admin/ showform The empty path didn’t match any of these. settings.py: INSTALLED_APPS = [ 'contact.apps.ContactConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'contactform.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, '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', ], }, }, ] WSGI_APPLICATION = 'contactform.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'userInfo', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': '3306', 'OPTIONS': { 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" } } } apps.py from django.apps import AppConfig class ContactConfig(AppConfig): default_auto_field = 'django.db.models.BigAutoField' name = 'contact' manage.py #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys import pymysql pymysql.install_as_MySQLdb() def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'contactform.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: … -
problem setting up django cant run " manage.py runserver"
my situation : i have windows 10 ppython 3 on the pycharm terminal i type pip install django success Then I create a folder named "pycal". On the command prompt I went to the folder "pycal". Then django-admin.py startproject newproject. This is successful. Then I run python manage.py runserver. It tells me "The system cannot execute the specified program" any feedback would be really appreciated -
OPT delete after verification in database
I am working with Django and I verified my user with email OTP, and OTP saved in the database. After verification, I want to delete OTP in the database. Otherwise, the user does not verify the account within two minutes, so I want to delete OTP from the database views.py class MyTokenObtainPairSerializer(TokenObtainPairSerializer): def validate(self, attrs): data = super().validate(attrs) serializer = UserSerializer(self.user).data for k, v in serializer.items(): data[k] = v return data class MyTokenObtainPairView(TokenObtainPairView): serializer_class = MyTokenObtainPairSerializer class RegisterView(APIView): permission_classes = [AllowAny] def post(self, request): try: data = request.data serializer = UserSerializer(data=data) if serializer.is_valid(): serializer.save() send_otp_via_email(serializer.data['email']) return Response({ 'status': '200', 'message': 'User registered successfully Please Check your email for verification', 'data': serializer.data }) return Response({ 'status': '400', 'message': 'User registration failed', 'data': serializer.errors }) except Exception as e: return Response({ 'status': '400', 'message': 'User registration failed', 'data': str(e) }) class VerifyOTP(APIView): permission_classes = [AllowAny] def post(self, request): try: data = request.data serializer = VerifyAccountSerializer(data=data) if serializer.is_valid(): email = serializer.data['email'] otp = serializer.data['otp'] user = User.objects.filter(email=email) if not user.exists(): return Response({ 'status': '400', 'message': 'email, user not exists', 'data': 'invalid email' }) if user[0].otp != otp: return Response({ 'status': '400', 'message': 'something went wrong', 'data': 'invalid OTP' }) user = user.first() user.is_valid … -
django.db.utils.IntegrityError: UNIQUE constraint failed: store_wishlist.user_id
I am working on ecommerce website. I wanted to implement wishlist function on my website. And, it is working if its the first time for user that is adding to the list. In the second time giving an error. What's the problem? Can someone please help me? views.py def addWishlistView(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print('Action:', action) print('Product:', productId) user = request.user product = Product.objects.get(id=productId) if (Wishlist.objects.filter(user=user) and Wishlist.objects.filter(product=product)).exists(): print("Item is exists") else: Wishlist.objects.create(user=user,product=product) return JsonResponse('Item was added', safe=False) models.py class Wishlist(models.Model): product = models.ForeignKey(Product, on_delete=models.SET_NULL, null=True, verbose_name="Название товара") user = models.OneToOneField(User, on_delete=models.CASCADE,null=True, blank=True) script js for (i = 0; i < wishlist.length; i++) { wishlist[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action if (user == 'AnonymousUser'){ Console.log("Not logged in"); }else{ addToWishlist(productId, action) } }) } function addToWishlist(productId, action){ console.log('User is authenticated, sending data...') var url = '/add_wishlist/' fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((data) => { location.reload() }) }