Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Compare two numbers from django rest framework model
New to django here. I want to compare two values from a model like the following inside an API made with django rest framework: class SalaryRangeModel(models.Model): salary_min = models.PositiveIntegerField salary_max = models.PositiveIntegerField I want to compare them. If salary_min is bigger than salary_max return a error. Should I code this on the model? On the serializer? On the front-end? Thanks! -
How to add None values in pandas?
I am reading xl file and xl file containing some data some rows are empty in date fields when i am uploading xl it is showing errors because empty fields so i need to add none or empty , null values to xl( in empty places)? projectid name reference jurisdiction_doctype shipping_datedue isthis_a_rush workflow allocated_date 0 CF805011 Calib 9802476632 Lien Release 03-31-2021 yes In DR 03-25-2021 1 CF80501 Calib 9802476632 Lien Release 03-31-2021 yes In DR 2 Calib 9802476632 Lien Release yes In DR 03-25-2021 3 CF80501yyy Calib Lien Release 03-31-2021 yes In DR 03-25-2021 4 CF8050 Calib 9802476632 Lien Release 03-31-2021 yes In DR 03-25-2021 -
Sharing static folder between backend and nginx containers
I have following Dockerfile FROM python:3.9 RUN adduser --disabled-password --gecos '' user WORKDIR /src COPY . ./ USER user and docker-compose.yml nginx: build: ./nginx volumes: - ./static:/static - ./nginx/etc:/etc/nginx/conf.d backoffice: ... container_name: backoffice command: bash -c "sh core/run_backoffice.sh" volumes: - ./core:/src - ./static:/static run_backoffice.sh #!/bin/bash python ./core/run.py collectstatic --no-input files structure total 56 drwxr-xr-x 9 root root 4096 Apr 11 12:53 . drwxr-xr-x 3 root root 4096 Apr 8 11:57 .. drwxr-xr-x 6 root root 4096 Apr 11 12:48 core drwxr-xr-x 5 root root 4096 Apr 11 12:54 core/. drwxr-xr-x 9 root root 4096 Apr 11 12:53 core/.. -rw-r--r-- 1 root root 384 Apr 11 12:48 core/Dockerfile -rw-r--r-- 1 root root 654 Apr 8 11:28 core/run.py -rw-r--r-- 1 root root 270 Apr 11 12:40 core/run_backoffice.sh -rw-r--r-- 1 root root 3099 Apr 11 12:53 docker-compose.yml drwxr-xr-x 3 root root 4096 Apr 8 11:28 nginx When I run collectstatic I get error backoffice | Traceback (most recent call last): backoffice | File "/src/./core/run.py", line 22, in <module> backoffice | main() backoffice | File "/src/./core/run.py", line 18, in main backoffice | execute_from_command_line(sys.argv) backoffice | File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line backoffice | utility.execute() backoffice | File "/usr/local/lib/python3.9/site-packages/django/core/management/__init__.py", line 440, in execute backoffice | … -
Django-allauth login page is too simple
I have created a project in which I provided a login system. I also want to provide a login with the google option. I have installed Django-allath and made the necessary changes to log in and retrieve the necessary data. But when I click on login with google it sends me to the simple login page and after continuing it redirects me to the google login page. I want when I click on login with [ <a href="{% provider_login_url 'google' %}"> <img src="https://img.icons8.com/color/480/000000/google-logo.png" /> </a> ]1google, It automatically redirects me <a href="{% provider_login_url 'google' %}"> <img src="https://img.icons8.com/color/480/000000/google-logo.png" /> </a> to the google login page. Please help me. -
django model fields dropped in validated data while using nested serializers
I'm writing a post req view in my api, but when I try to create the object using validated_data in the overriden create method, django tells me that one of the required model fields are missing (the field exists in the request data before validation) models.py: class Workout(models.Model): owner = models.CharField(max_length=20) name = models.CharField(max_length=50) def __str__(self) -> str: return self.name class ExerciseData(models.Model): name = models.CharField(max_length=60) muscles_worked = models.CharField(max_length=15) def __str__(self) -> str: return self.name class ExerciseObject(models.Model): sets = models.IntegerField() reps = models.IntegerField() exercise_data = models.ForeignKey(ExerciseData,on_delete=models.CASCADE,related_name='exercise_instances') workout = models.ForeignKey(Workout,on_delete=models.CASCADE,related_name='workout_exercises') def __str__(self) -> str: return f"Exercise: {self.exercise_data.name} Workout: {self.workout.owner} {self.workout.name}" serializers.py class ExerciseDataSerializer(serializers.ModelSerializer): class Meta: model = ExerciseData fields = ('name','muscles_worked') class ExerciseObjectSerializer(serializers.ModelSerializer): exercise_data = ExerciseDataSerializer() class Meta: model = ExerciseObject fields = ('sets','reps','exercise_data','workout') #TODO: finish create function def create(self,validated_data): print("validated data", validated_data) return ExerciseObject(**validated_data) views.py: class ExerciseObjectView(APIView): def post(self,request): data = request.data.copy() # required: sets,reps,workout_id,exercise_id data['exercise_data'] = ExerciseData.objects.filter(id=data['exercise_id']).first() print("request data", data) s_data = ExerciseObjectSerializer(data=data) print(s_data) if s_data.is_valid(): print("valid") print(s_data.create(s_data.validated_data)) else: print(s_data.errors) return JsonResponse({'data':{}}) output from print("request data, data): request data <QueryDict: {'sets': ['2'], 'reps': ['15'], 'workout': ['2'], 'exercise_id': ['185'], 'exercise_data': [<ExerciseData: calf stretch hands against wall>]}> serializer error: {'exercise_data': [ErrorDetail(string='This field is required.', code='required')]} -
Unable to deploy django app with websockets and channels using daphne . Asgi application error
I am currently deploying my chat app on web with daphne using mobaxterm . This is the site -> http://139.59.6.41/ But the thing is asgi application error is being shown when I run the command sudo journalctl -u daphne.service I am unable to understand what is the error. here is the error log : root@ubuntu-s-1vcpu-1gb-blr1-01:~# sudo journalctl -u daphne.service -- Logs begin at Sat 2022-04-09 18:40:30 UTC, end at Mon 2022-04-11 12:26:26 UTC. -- Apr 09 19:09:46 ubuntu-s-1vcpu-1gb-blr1-01 systemd[1]: Started WebSocket Daphne Service. Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: Traceback (most recent call last): Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: File "/home/django/Chatapp/venv/lib/python3.8/site-packages/channels/routing.py", line 32, in get_default_application Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: value = getattr(module, name) Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: AttributeError: partially initialized module 'Chatapp.asgi' has no attribute 'application' (most likely due to a circular import) Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: During handling of the above exception, another exception occurred: Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: Traceback (most recent call last): Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: File "/home/django/Chatapp/venv/bin/daphne", line 8, in <module> Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: sys.exit(CommandLineInterface.entrypoint()) Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: File "/home/django/Chatapp/venv/lib/python3.8/site-packages/daphne/cli.py", line 170, in entrypoint Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: cls().run(sys.argv[1:]) Apr 09 19:09:47 ubuntu-s-1vcpu-1gb-blr1-01 python[3411]: File "/home/django/Chatapp/venv/lib/python3.8/site-packages/daphne/cli.py", line … -
How to retrieve single object from many to many relationship using elasticsearch in django
I am trying to use elasticsearch for search functionality in my django site. Here is my code. models.py: class Category(MPTTModel): name = models.CharField() class Product(models.Model): name = models.CharField() description = models.TextField() category = TreeManyToManyField(Category) class ProductImage(models.Model): product = models.ForeignKey( Product, on_delete=models.PROTECT, related_name= "product_pictures", ) image = models.ImageField(...) class ProductInventory(models.Model): product = models.ForeignKey(Product, related_name="product", on_delete=models.PROTECT) product_images = models.ManyToManyField( ProductImage, related_name = "product_inventory_images", through="MediaProductImage") is_default_varient = models.BooleanField(default=False) class MediaProductImage(models.Model): product_inventory = models.ForeignKey( ProductInventory, on_delete=models.PROTECT, related_name="media_product_inventory", ) image = models.ForeignKey( ProductImage, on_delete=models.PROTECT, related_name="media_product_image", ) is_feature = models.BooleanField( default=False, ) documents.py: @registry.register_document class ProductInventoryDocument(Document): product = fields.ObjectField( properties={ "name": fields.TextField(), "description": fields.TextField() } ) category = fields.ObjectField( properties={ "name": fields.TextField() } ) product_images = fields.NestedField( properties={ 'image': fields.FileField(), }) media_product_inventory = fields.ObjectField( properties={ 'is_feature': fields.BooleanField(), }) class Index: # Name of the Elasticsearch index name = 'productinventory' class Django: model = ProductInventory # The model associated with this Document # The fields of the model you want to be indexed in Elasticsearch fields = [ 'id', 'is_default_varient', ] I want to search product from ProductInventory table matching with by matching name by matching description by matching category # if possible filter by is_deafult_varient=True # for getting default ProductInventory object filter by media_product_inventory__is_feature=True # for … -
I have change custom user model in middle of project so admin page is giving me this error But my Api is working fine only admin page has problem
enter image description herei have change my custom user model in middle of the project so iam getting such error inside table which is having foreign relationship Template error: In template C:\Users\User\.virtualenvs\tagon-lucky_wheel_api-OldNbhB5\lib\site-packages\django\contrib\admin\templates\admin\includes\fieldset.html, error at line 19 __str__ returned non-string (type NoneType) 9 : {% for field in line %} 10 : <div{% if not line.fields|length_is:'1' %} class="fieldBox{% if field.field.name %} field-{{ field.field.name }}{% endif %}{% if not field.is_readonly and field.errors %} errors{% endif %}{% if field.field.is_hidden %} hidden{% endif %}"{% elif field.is_checkbox %} class="checkbox-row"{% endif %}> 11 : {% if not line.fields|length_is:'1' and not field.is_readonly %}{{ field.errors }}{% endif %} 12 : {% if field.is_checkbox %} 13 : {{ field.field }}{{ field.label_tag }} 14 : {% else %} 15 : {{ field.label_tag }} 16 : {% if field.is_readonly %} 17 : <div class="readonly">{{ field.contents }}</div> 18 : {% else %} 19 : {{ field.field }} 20 : {% endif %} 21 : {% endif %} 22 : {% if field.field.help_text %} 23 : <div class="help">{{ field.field.help_text|safe }}</div> 24 : {% endif %} 25 : </div> 26 : {% endfor %} 27 : </div> 28 : {% endfor %} 29 : </fieldset> -
Django dynamic nested model forms
Suppose I have the following models, where there is a 1:many relationship from Teacher to Course, and from Course to Student: class Teacher(Model): name = CharField(max_length=64) degree = CharField(max_length=64) class Course(Model): title = CharField(max_length=64) level = CharField(max_length=64) teacher = ForeignKey(Teacher, on_delete=CASCADE) class Student(Model): name = CharField(max_length=64) year = CharField(max_length=64) course = ForeignKey(Course, on_delete=CASCADE) If I want to have a "register teacher" page, where a user can input the details of a Teacher, and also be able to add any number of Courses with their corresponding details, and to each Course add any number of Students, how could this be done? I am aware of ModelForms, which would make constructing a basic form for a single instance of a model rather trivial, but how can I create a form or forms that essentially nests the models within each other, and allows for a dynamic number of Course and Student? For example, within the Teacher form, there is an "add Course" button, that adds another Course form under that Teacher, such that any details entered into it populate a Course that belongs to that Teacher, and then for each Course form, there is an "add Student" button that adds a Student form … -
How do I check if such a field exists for a product (product model)?
I'm a beginner in django....... I have such a model class Product(models.Model): title = models.CharField(max_length=50) description = models.TextField(blank=True) owner = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) slug = models.SlugField(unique=True) # "штрих код" price = models.DecimalField(max_digits=8, decimal_places=2, ) creation_date = models.DateTimeField(auto_now_add=True) last_update_time = models.DateTimeField(auto_now=True) image1 = models.ImageField(blank=True) mark = models.CharField(max_length=50, blank=True) class Review(models.Model): review = models.TextField(max_length=500) author = models.ForeignKey(User, on_delete=models.CASCADE) product_connected = models.ForeignKey(Product, on_delete=models.CASCADE, related_name="reviews") creation_date = models.DateTimeField(auto_now_add=True) last_update_time = models.DateTimeField(auto_now=True) rating = models.IntegerField(default=0, validators=[MinValueValidator(0), MaxValueValidator(5)]) and here is such a views class ProductDetailView(LoginRequiredMixin, DetailView): model = Product template_name = "product.html" context_object_name = "product" @staticmethod def round_custom(num, step=0.5): return round(num / step) * step def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) data["pictures_list"] = Photo.objects.filter(product_connected=self.get_object()) data["comments"] = Review.objects.filter(product_connected=self.get_object()) if self.request.user.is_authenticated: data['comment_form'] = CommentForm(instance=self.request.user) average_rt=Review.objects.filter( product_connected=self.get_object()).aggregate(Avg('rating')) avr_intermediate = str(average_rt.get("rating__avg")).replace(",", ".") data["average_rating"] = self.round_custom(float(avr_intermediate)) return data This whole scheme with average is needed to display a rating on the site (rating), the problem is that a product is created in the product model, and the review class is created only when the user writes a review. So, how do I check that there is a Review for this Product, and if there is, then return return data["average_rating"] through my scheme, and if not, then just return 0 in data … -
Factory Boy FuzzySubFactory available?
I am wondering if there is something like FuzzyChoice for Objects. Background is that I have a base factory and 3 different implementations. Another Factory which uses these factories should randomly choose one of the three implementations. So I did not found that specify FuzzySubFactory within the docs but is there another way to achieve this? Thanks and regards Matt -
How to get the output parameter as the response in python
I'm trying to get the list of user's based whose name starts based on the typing the name from the SQL database. In SQL there is an output parameter in which I want to return as API response views.py: @api_view(['POST']) def FetchSuggestionAuditAgent(request): if request.method =='POST': agents = request.data.get('Agents') sql = """\ DECLARE @response NVARCHAR; EXEC dbo.sp_FetchSuggestionAuditAgent @agents = %s, @response = @response OUTPUT; SELECT @response AS out_value; """ params = (2,) cursor = connection.cursor() cursor.execute(sql, params) result_set = cursor.fetchall() print(result_set) for row in result_set: agents = row[0] return Response({'Agents':agents}) SQL SP: ALTER PROCEDURE [dbo].[sp_FetchSuggestionAuditAgent] -- 'apolonia ','' @agents nvarchar(max),@response nvarchar(1000) OUTPUT AS BEGIN set @agents = LTRIM(RTRIM(@agents)) select top 1 @response = FullName from tblusers where FullName like '%'+@agents+'%' and isactive =1 and IsDeleted = 0 order by FullName desc END -
How can I solve the Not found problem when getting from pytest-django through pk?
I have a problem with django-pytest I'm using, djnago-rest-framework There is a problem testing the details. As shown in the code below, I entered the same details, detail1, detail2, and detail3 codes. However, only detail1 succeeds and detail2, detail3 indicates that '/api/v1/stats/1/' could not be found. It also occurs when implementing delete. I am curious about the cause and solution of this error. enter image description here // tests/test_apis.py import json from django.urls import reverse from rest_framework import status from rest_framework.test import APITestCase from stats.models import Stats class StatsApiTests(APITestCase): def setUp(self): Stats.objects.get_or_create(blockshots=1, memo='test1') Stats.objects.get_or_create(blockshots=2, memo='test2') self.create_read_url = reverse('api:stats:stats-list') self.read_update_delete_url = reverse('api:stats:stats-detail', kwargs={'pk': '1'}) def test_detail1(self): response = self.client.get(self.read_update_delete_url) data = json.loads(response.content) content = { 'blockshots': 1, 'memo': 'test1', } self.assertEqual(data, content) def test_detail2(self): response = self.client.get(self.read_update_delete_url) data = json.loads(response.content) content = { 'blockshots': 1, 'memo': 'test1', } self.assertEqual(data, content) def test_detail3(self): response = self.client.get(self.read_update_delete_url) data = json.loads(response.content) content = { 'blockshots': 1, 'memo': 'test1', } self.assertEqual(data, content) def test_list(self): response = self.client.get(self.create_read_url) self.assertContains(response, 'test1') self.assertContains(response, 'test2') -
how to email check on unique in django (@ya.ru == @yandex.ru)
how to check email address is unique, if example@yandex.ru and example@ya.ru it`s identically equal. i use [django-registration 3.2][1], to check unique email in urls.py add from django_registration.forms import RegistrationFormUniqueEmail from django_registration.backends.activation.views import RegistrationView ... urlpatterns = [ ... path('accounts/register/', RegistrationView.as_view(form_class=RegistrationFormUniqueEmail),name='django_registration_register',), ... ] all good for to check. I don't understand how to check it. help please. [1]: https://django-registration.readthedocs.io -
Constructing Dynamic Tables in Django with editable cells and nested categories
I am trying to get an excel-like setup (but more dynamic and customisable) using Django. On the right-hand side there is a filter list. The rows list is fully expanded. I want to be able to dynamically add or remove columns/rows and to be able to enter values into the cells. The cells should be either dropdowns or text cells. So for example, I could be able to delete Column Category A which would delete the Column and all sub-columns. Similarly, I could "Add Category" to the rows creating Row Category C and then add sub-categories. Of course, all names should be editable. Once that is all complete, I want to be able to save the final table into a database for a particular user. I am struggling to find any way to implement this. Are there any sub-libraries of Django which can build this? -
How to filter for Records in the admin backend
class OrderSVO(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) customer = models.ForeignKey(Customer, on_delete=models.CASCADE) seller = models.CharField(max_length=100, default='', blank=True) class OrderSVOAdmin(admin.ModelAdmin): def queryset(self, request): """Limit Pages to those that belong to the request's user.""" qs = super(OrderSVOAdmin, self).queryset(request) if request.user.is_superuser: # It is mine, all mine. Just return everything. return qs # Now we just add an extra filter on the queryset and # we're done. Assumption: Page.owner is a foreignkey # to a User. return qs.filter(seller='A Seller Name') admin.site.register(OrderSVO,OrderSVOAdmin) I want to filter records in the backend for a specific seller -
Calling a Django Api in Vue that has date parameter in between
How do I pass this Api call in Vue2 and calling it http://127.0.0.1:8000/api/2022-03-18 10:55/2022-04-18 10:55/displaydate parameter -
I keep getting this error in my django project and I have literally tried everything I could find on stackoverflow but nothing works
Error: Uncaught TypeError: $(...).autocomplete is not a function included in base.html: <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.6.0/jquery.min.js"></script> <script src="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/jquery-ui.min.js"></script> <link rel="stylesheet" href="https://ajax.googleapis.com/ajax/libs/jqueryui/1.12.1/themes/smoothness/jquery-ui.css"> autocomplete code reference: https://www.geeksforgeeks.org/implement-search-autocomplete-for-input-fields-in-django/ -
pyodbc.ProgrammingError: ('42S22', "[42S22] [Microsoft][ODBC Driver 17 for SQL Server][SQL Server]Invalid column name 'xyzxyz'
I have one Django app which was working fine but after changing the data type of one column in DB from varchar to NVarchar I am getting the above error. Can anyone please guide me what am I missing? Do I need to do migration? -
How to display model inheritance in Pyhon Django?
I have this code : from django.db import models from category.models import Category # Create your models here. class Item(models.Model): item_name = models.CharField(max_length=200, unique=True) slug = models.SlugField(max_length=200,unique=True) description = models.TextField(max_length=500, blank=True) price = models.IntegerField() images = models.ImageField(upload_to='photos/products') stock = models.IntegerField() is_available = models.BooleanField(default = True) category = models.ForeignKey(Category,on_delete = models.CASCADE) created_date = models.DateTimeField(auto_now=True) modified_date= models.DateTimeField(auto_now=True) def __str__(self): return self.item_name class Meta: abstract = true class BookItem(Item): author = models.CharField(max_length=200) class LaptopItem(Item): cpu = models.CharField(max_length=200) ram = models.CharField(max_length=200) I want to display all BookItem and LaptopItem only by using model Item . Can someone show m3 how to do that ? -
Django Rest Framework - common nested serializer for multiple models with the same base class
Assuming that we have the following models: from django.db import models class BaseModel(models.Model): field_a = models.TextField() field_b = models.IntegerField() class Meta: abstract = True class ModelA(BaseModel): some_relation = models.ForeignKey( "app.RelatedModelA", related_name="model_a_set", ... ) class ModelB(BaseModel): different_relation = models.ForeignKey( "app.RelatedModelB", related_name="model_b_set", ... ) class RelatedModelA(models.Model): pass class RelatedModelB(models.Model): pass I would like to be able to define serializers in the following way: from rest_framework import serializers class RelatedModelASerializer(serializers.ModelSerializer): model_a_set = BaseModelSerializer(many=True) class Meta: model = RelatedModelA fields = ("id", "model_a_set") class RelatedModelBSerializer(serializers.ModelSerializer): model_b_set = BaseModelSerializer(many=True) class Meta: model = RelatedModelB fields = ("id", "model_b_set") The question is - how to define BaseModelSerializer? I found a solution that takes into account overriding to_representation, although it requires writing serializers for each type separately (ModelASerializer and ModelBSerializer), so it would look like this: class BaseModelSerializer(serializers.ModelSerializer): def to_representation(self, obj): if isinstance(obj, ModelA): return ModelASerializer(obj, context=self.context).to_representation(obj) elif isinstance(obj, ModelB): return ModelBSerializer(obj, context=self.context).to_representation(obj) raise NotImplementedError class Meta: model = BaseModel fields = ("id", "field_a", "field_b") The ideal solution for me would be something like that, without defining serializers for ModelA and ModelB: class BaseModelSerializer(serializers.ModelSerializer): class Meta: model = BaseModel fields = ("id", "field_a", "field_b") but unfortunately it won't work that way, because an abstract model cannot be … -
How to create a django model record using get_or_create and select_related
I have a class like below: class GroupProduct(models.Model): product = models.ForeignKey( 'myapp.Products' related_name='myapp_group_product') @classmethod def create_group_product(cls, p_id, product_id): cls.objects.get_or_create(id=p_id, defaults=dict(product=product_id).select_related('product') So I expect it creates a record in the table with the following params, however it doesn't. GP = GroupProduct() GP.create_group_product(3, 225) It says it product must be a myapp.Products instance. Is there any way to use select_related in this way rather than doing a seprate query and hit the database? -
Mapboxgl breaks when I change django language in settings
Basically my code works well when language in django settings.py is set to "en-us" But when I try to change it I get: Uncaught Error: Invalid LngLat object: (NaN, NaN) at new Ha (lng_lat.js:39:19) at Function.convert (lng_lat.js:142:20) at Rr.setLngLat (marker.js:337:31) at dodaj_marker ((indeks):282:37) at (indeks):296:9 I'm changing lang because I need to get months in different language, but how does it affect mapbox? Is there any mapbox language variable I have to edit in order to get it working ? -
win10 netstat -ano|findstr 8000 return empty and error ’WinError 10013” when python manage.py runserver 8000
receive Error: [WinError 10013] when i use 'python manage.py runserver 8000'. then netstat -ano|findstr 8000, but nothing is return,only empty list. I use win10, what missing? thanks. But run python manage.py runserver 9000 is ok? what problem with port 8000? why netstat -ano|findstr 8000 return empty? -
django.db.utils.OperationalError: no such table: main.authentication_user
I am getting the error mentioned in the title during my try to save some information to a postgres database. My models.py script is the following: from django.db import models from django.contrib.auth import get_user_model CustomUser = get_user_model() class Event(models.Model): user_id_event = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True) dr_notice_period = models.IntegerField(blank=True, null=True) dr_duration = models.IntegerField(blank=True, null=True) dr_request = models.FloatField(blank=True, null=True) CustomeUser is from the models.py of a custom authentication application: from django.db import models from django.contrib.auth.models import AbstractUser class User(AbstractUser): demo = models.CharField(max_length=40) My serializers.py script is the following: from rest_framework import serializers from vpp_optimization.models import Event class EventSerializer(serializers.ModelSerializer): class Meta: model = Event fields = ('__all__') And my views.py where I am trying to add a specific event to the database is the following: from rest_framework.response import Response from rest_framework.decorators import api_view, permission_classes from rest_framework.permissions import IsAuthenticated from rest_framework import status from vpp_optimization.serializers import EventSerializer @api_view(['POST']) @permission_classes([IsAuthenticated,]) def event(request): serializer = EventSerializer(data=request.data) if serializer.is_valid(): serializer.save(user_id_event=request.user) return Response({"status": "success", "data": serializer.data}, status=status.HTTP_200_OK) else: return Response({"status": "error", "data": serializer.errors}, status=status.HTTP_400_BAD_REQUEST) The full error is the following: Traceback (most recent call last): File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/backends/utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "/root/energy_efficiency_flexibility_services/venv/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 413, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: no such table: main.authentication_user …