Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Zero-length delimiter error using python psycopg2 to parse a gzip and insert it into a postgres database
I am attempting to load the contents of a gzip file I created into my postgres database using psycopg2. When I run the script, I get the following error: psycopg2.errors.SyntaxError: zero-length delimited identifier at or near """" (photo of traceback here) I understand that the error is most likely due to the single quotes around the empty string value of 'example', but I don't know the reason this would cause an issue. df = pandas.read_csv(cip_location, header=0, encoding='ISO-8859-1', dtype=str) number_loaded_rows += len(df.index) for index, row in df.iterrows(): row = row.squeeze() cip_code = row['CIPCode'] cip_code = cip_code[cip_code.find('"') + 1:cip_code.rfind('"')] if cip_code.startswith('0'): cip_code = cip_code[1:] cip_title = row['CIPTitle'] cip_def = row['CIPDefinition'] exam_string = row['Examples'] exam_string = exam_string.replace('Examples:', '').replace(' - ', '').replace(' -', '') examples = exam_string cip_codes[cip_code] = { 'code': cip_code, 'title': cip_title, 'definition': cip_def, 'examples': examples } with gzip.GzipFile(ending_location, 'r') as f: bytes = f.read() string = bytes.decode('utf-8') loaded_unis = jsonpickle.decode(string) print('Finished loading in ' + str(time.time() - start_load)) import psycopg2 cnx = psycopg2.connect('host=localhost dbname=postgres user=postgres password=password') count = 0 cursor = cnx.cursor() for d in cip_codes.values(): print('Inserted: %s' % count) print('Trying to insert (%s, "%s", "%s", "%s");' % (d['code'], d['title'], d['definition'], d['examples'])) cursor.execute('CALL InsertCIP(%s, "%s", "%s", "%s");' % (str(d['code']), d['title'].replace('"', "'"), … -
Django custom admin messages
I would like to know how to change the link that appears in the Django admin panel success message and redirect it somewhere else The underlined red part is where the link appears -
Best option for Django Logging accross multiple processes
What is the best option for Django logging if I have info.log and error.log which are being shared across multiple processes? One option would be Multiprocessing, another option would be SocketHandler. Here is the link: https://docs.python.org/3/howto/logging-cookbook.html#logging-to-a-single-file-from-multiple-processes -
Setting a field in django admin that is unchangeable
I'm currently developing a Django app that is used by multiple gas stations. I have a station model with every station having it's own object. Each station will have its own account and can only modify values for their own station. I am making a report to be submitted via Django admin, but I want to set the "station" field to their station name, where they can't view other station names nor change the selection to the other stations. In the admin.py, this is what I have (the report is called Shipment), the field in question is called station. class ShipmentAdmin(admin.ModelAdmin): #readonly_fields = ['station'] <- I thought this would work but it removes the value I set if user = manager def get_form(self, request, obj=None, **kwargs): form = super(ShipmentAdmin, self).get_form(request, obj, **kwargs) if str(request.user) == 'manager': form.base_fields['station'].initial = 'Texaco' else: form.base_fields['station'].initial = 'Exxon' Please let me know if you guys know how to fix this. Basically if the user is manager, set the station value to "Texaco", else set it to "Exxon", and don't allow that field to be changed. Thanks! -
Django grouping and filter, ordering
I am creating small project for our cinema web I have models class Movies(models.Model): name = models.CharField(max_length=100) ... class Projections(models.Model): movie = models.ForeignKey(Movies, on_delete=models.DELETE) startshow = models.DateTimeField() Each Movies have several Projections with different startshow. How can I get Movies grouped by name and ordered by first startshow with all projections for that movie ordered by startshow The list is looking like this: Trools: World Tour 2020-11-10 17:00 2020-11-11 17:00 2020-11-12 17:00 Frozen 2020-11-10 19:00 2020-11-11 19:00 2020-11-12 19:00 Tennet 2020-11-10 21:00 2020-11-11 21:00 2020-11-12 21:00 Please help -
django user defined fields and answer model
Similar to this: User defined fields model in django I am creating a COVID Prescreening system for a school project. Event creators will be able to create forms, which consist of basic questions such as temperature, contact with covid in the last 14 days, etc. as well as provide custom questions for the attendee to answer which I cannot predict. For example, the event creator could ask 2 questions: How are you feeling today? Have you been to a party in the last week? And every attendee for that event would have to fill out these 2 questions in addition to the standard questions. The model for this is: class Event(models.Model): ''' model for an event ''' creator = models.ForeignKey("Account", on_delete=models.CASCADE) title = models.CharField(max_length=200, help_text="Enter a title for this event") start_time = models.DateTimeField() uuid = models.UUIDField(primary_key=True, default=uuid.uuid4) custom_questions = models.ManyToManyField(CustomQuestion) def __str__(self): return f'{self.title} {self.uuid}' Each custom question is essentially a key/value model: class CustomQuestion(models.Model): question = models.CharField(max_length=200) response = models.CharField(max_length=200, blank=True) The user will fill out the COVID Form, which will create an object as such: class CovidScreenData(models.Model): custom_responses = models.ManyToManyField(CustomQuestion) temperature = models.DecimalField(max_digits=5, decimal_places=2, default=98.6) contact_with_covid = models.BooleanField(default=False) This data is embedded in the larger response, which ties … -
Problems trying to save data to a set of online forms
I am developing an application which saves the projects that the administrator assign to the developers, for that I have a project model and a task model, because a project can have multiple tasks, in order to save multiple tasks in a project what I am doing is using a inline formset, but I am having a problem and it is that the data is not saved correctly. This is my view. class ProjectCreateView(LoginRequiredMixin, CreateView): login_url = 'users:login' template_name = 'projects/add_project.html' form_class = ProjectForm success_url = reverse_lazy('projects:project') def get_context_data(self, **kwargs): data = super().get_context_data(**kwargs) if self.request.POST: data['formset'] = ProjectFormSet(self.request.POST) else: data['formset'] = ProjectFormSet() return data def form_valid(self, form): context = self.get_context_data() formset = context['formset'] with transaction.atomic(): self.object = form.save() if formset.is_valid(): formset.instance = self.object formset.save() return super().form_valid(form) This is my inline formset: ProjectFormSet = inlineformset_factory( Project, Task, form=TaskForm, fields=['type_task', 'task'], extra=1, can_delete=True, ) This is my template,To use the inline formset I was investigating and they told me that the easiest way is with a jquery library to carry out this process: {% extends "base.html" %} {% load static %} {% block content %} <div class="container"> <div class="card"> <div class="card-content"> <h2>Agregar Proyecto</h2> <div class="col-md-4"> <form method="post"> {% csrf_token %} <div class="input-field … -
Loading Template in Admin Form for Custom Fields
I learned that I can add a custom button in my Admin form by adding it to fields = ["connect"] readonly_fields = ('connect',) def connect(self, obj): return format_html("<button></button>") connect.allow_tags=True connect.short_description = '' However, the html I want to add to the connect is getting out of control. I was wondering if there's a proper (Django-nic) way to move that to a template and load and return the content of the template in the connect function. I can think of reading the content of the template file (open('file.html', 'r')) to read the content, however, I am looking for a suggestion that aligns Django standards (if any). P.S. I also tried creating a view for getting the HTML content of the connect file, but that for some reason doesn't seem to work and feels unnatural to do. -
Can't correctly receive data in Django from Ajax
I wand to receive array data in Django view from jquery/Ajax request but in some reason I cannot correctly do it. This is the piece of js code: var arr = [1, 2]; $.ajax({ type: 'POST', url: '/go/', data: {arr: arr}, success: function (data) { console.log('Success!'); }, }); And this is from Django view: def go(request): if request.method == 'POST': arr = request.POST['arr'] It gives me KeyError: 'arr' If I do print(request.POST) in Django it prints it like this: <QueryDict: {'arr[]': ['1', '2']}>. Some square brackets appear after 'arr' key. Then if I do arr = request.POST['arr[]'] using the key with square brackets it assings arr value 2, so only the last value of the array. Can someone please explain to me why this is happening? -
can i do process with form django python
there is a input and select with options in form tag. i want to get input value and option that entered. and i will do somethings on backend with python that value and option than i will return a result to website. but i dont use to forms.py. how can i do? is it possible? <form action="" method="post"> {% csrf_token %} <input type="text" name="getinputValue"> <select name=""> <option value="1"></option> <option value="2"></option> <option value="3"></option> </select> <button type=""class=""></button> <p>{{result}}</p> </form> -
Why this django formset has stopped saving the content all of a sudden?
I had this view that rendered a form and a formset in the same template: class LearnerUpdateView(LearnerProfileMixin, UpdateView): model = User form_class = UserForm formset_class = LearnerFormSet template_name = "formset_edit_learner.html" success_url = reverse_lazy('pages:home') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) learner = User.objects.get(learner=self.request.user.learner) formset = LearnerFormSet(instance=learner) context["learner_formset"] = formset return context def get_object(self, queryset=None): user = self.request.user return user def post(self, request, *args, **kwargs): self.object = self.get_object() form_class = self.get_form_class() form = self.get_form(form_class) user = User.objects.get(learner=self.get_object().learner) formsets = LearnerFormSet(self.request.POST, request.FILES, instance=user) if form.is_valid(): for fs in formsets: if fs.is_valid(): # Messages test start messages.success(request, "Profile updated successfully!") # Messages test end fs.save() else: messages.error(request, "It didn't save!") return self.form_valid(form) return self.form_invalid(form) Then i wanted to make it prettier and i added the select2 multicheckbox widget and the django-bootstrap-datepicker-plus Nothing has changed elsewhere, yet when i submit the post it only saves the data relative to User and not to Learner (which relies on the formset) According to the messages, the formset data is not validated, I don't understand why since i didn't touch the substance at all but just the appearance. Being a beginner im probably missing something big, I thank in advance whoever can help me find out the problem. … -
Django dumpdata slow after delete all records in table
I cleared a table using RulesUsed.objects.all().delete() There were about 35,000 records in the table (out of a total database of 45,000 records in all tables). python manage.py dumpdata --exclude auth.permission --exclude contenttypes > db_input.json dumpdata went from about 17 seconds before delete to more than 19 minutes after. I have tried rebuilding the container and loading the data with json file from dumpdata -- so there is no data in the (now) empty table. dumpdata time on the new database is the same -- 19 minutes. python manage.py loaddata --ignorenonexistent /scripts/db_input.json I feel I have misunderstood something and there is some relation slowing things down. I tried clearing from command line with same result of 19 minutes; python manage.py shell from appname.models import RulesUsed RulesUsed.objects.all().delete() The table is a child of another, the model is; class RulesUsed(models.Model): hs_input = models.ForeignKey( hs_input, on_delete=models.CASCADE, related_name='rules_used' ) Rule_Type = models.CharField(max_length=50) Rule = models.CharField(max_length=50) Value = models.CharField(max_length=256) Rule_Comment = models.CharField(max_length=100) class Meta: ordering = ['hs_input','Rule_Type','Rule'] def __str__(self): return f'{self.hs_input} : {self.Rule_Type} : {self.Rule} : {self.Value}' def as_dict(self): return {'id': self.hs_input, 'Rule type' : self.Rule_Type, 'Rule' : self.Rule, 'Value' : self.Value, 'Rule comment' : self.Rule_Comment } The database is Postgres. Python 3.8. Django 2.2.5. Running … -
DRF data not validating nexted object while processed with file data (multipart/form-data)
===========JS========== const data = { "id": "d33e6dca-9152-4ded-96e3-51b2f24423d8", "logo": null, "name": "Company 1", "account": { "id": "d33e6dca-9152-4ded-96e3-51b2f24423d9", "name": "Account Name", "company": "d33e6dca-9152-4ded-96e3-51b2f24423d8" }, "modules": [ { "id": "d33e6dca-9152-4ded-96e3-51b2f24423d1", "name": "Module 1" }, { "id": "d33e6dca-9152-4ded-96e3-51b2f24423d2", "name": "Module 2" }, ], "addresses": [ { "id": "d33e6dca-9152-4ded-96e3-51b2f24423d4", "name": "Address 1", "company": "d33e6dca-9152-4ded-96e3-51b2f24423d8" }, { "id": "d33e6dca-9152-4ded-96e3-51b2f24423d5", "name": "Address 2", "company": "d33e6dca-9152-4ded-96e3-51b2f24423d8" }, ], } let formData = new FormData(); Object.keys(data).map(key=>{ formData.append(key, typeof data[key] === "object" && key!=="logo"? JSON.stringify(data[key]):data[key]) }) const config = { headers: {'Content-Type': 'multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW'} }; //axios.put(url, data).then(res => {console.log(".....Response!!! UPDATE")}).catch(err => {console.log(err.response.data)}) axios.put(url, formData, config).then(res => {console.log(".....Response!!! UPDATE")}).catch(err => {console.log(err.response.data)}) ===========Models========== class Address(BaseModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(_('name'), max_length=254, unique=True) company = models.ForeignKey("Company", on_delete=models.CASCADE, related_name="our_addresses") class Module(BaseModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=32) class Account(CompanyBaseModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=32) company = models.OneToOneField("Company", on_delete=models.CASCADE, related_name="account") class Company(BaseModel): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(_('name'), max_length=254, unique=True) logo = models.ImageField(_('Company Logo'), upload_to=logo_path, storage=PublicMediaStorage(), blank=True, null=True, default=None) addresses = models.ManyToManyField(Address, related_name="companies") modules = models.ManyToManyField(Module) ===========Serializers========== class AddressFormSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=False, required=False, allow_null=True) class Meta: model = Address fields = '__all__' read_only_fields = ['company', ] class ModuleFormSerializer(serializers.ModelSerializer): id = serializers.UUIDField(read_only=False) # required ONLY for … -
How can I use Pathlib for configuring the settings for the project in Django/Faker?
Right now I'm trying to put some fake data in my database using Faker just for the checking purposes. I've created separate file, but before starting to work with Faker itself and data manipulation, I need to configure the settings for the project in this separate file. Before DJANGO==3.1 all people have been using OS module and the following syntax. import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'project_name.settings') But now, when Django versions higher than 3.1 switched from OS module to PATHLIB module, how should I write this code using PATHLIB, not OS? Any help would be helpful! -
Can someone pleas tell me why my form is not valid
I'm stuck. I tried to get this forms.py to work but django never said that the form or things i write into the form at the webpage is valid I thought i made this in a nother app excactly the same way and it works there. class Recipe(models.Model): DIFFICULTY_EASY = 1 DIFFICULTY_MEDIUM = 2 DIFFICULTY_HARD = 3 DIFFICULTIES = ( (DIFFICULTY_EASY, u'einfach'), (DIFFICULTY_MEDIUM, u'normal'), (DIFFICULTY_HARD, u'schwer'), ) EVALUATION_V_SATISFIED = 5 EVALUATION_SATISFIED = 4 EVALUATION_NEUTRAL = 3 EVALUATION_DISSATISFIED = 2 EVALUATION_V_DISSATISFIED = 1 EVALUATION_DUNNO = 0 EVALUATIONS = ( (EVALUATION_V_SATISFIED, u'sehr zufrieden'), (EVALUATION_SATISFIED, u'zufrieden'), (EVALUATION_NEUTRAL, u'neutral'), (EVALUATION_DISSATISFIED, u'unzufrieden'), (EVALUATION_V_DISSATISFIED, u'sehr unzufrieden'), (EVALUATION_DUNNO, u'k. A.'), ) CATEGORY_KOCHEN = 1 CATEGORY_BACKEN = 2 CATEGORIES = ( (CATEGORY_KOCHEN, u'Kochen'), (CATEGORY_BACKEN, u'Backen'), ) author = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name=u'Autor',related_name="recipe", null=True, default=1) published = models.DateField(default=timezone.now, editable=False) #picture später hinzufügen mit MEDIA_ROOT title = models.CharField(max_length=250) img_url = models.TextField(null=True,blank=True) evaluation = models.SmallIntegerField(choices=EVALUATIONS, default=EVALUATION_NEUTRAL) category = models.SmallIntegerField(choices=CATEGORIES, default=CATEGORY_KOCHEN) subcategory = models.ManyToManyField(SubCategory,verbose_name=u'Unterkategorien') portions = models.PositiveIntegerField() duration_ges = models.PositiveIntegerField(null=True, blank=True) duration_working = models.PositiveIntegerField(null=True, blank=True) duration_cooking = models.PositiveIntegerField(null=True, blank=True) difficulty = models.SmallIntegerField(u'Schwierigkeit', choices=DIFFICULTIES, default=DIFFICULTY_MEDIUM) tags = TaggableManager() class Meta: verbose_name = u'Rezept' verbose_name_plural = u'Rezepte' ordering = ['-published'] def __str__(self): return self.title this is my forms.py class RecipeForm(forms.ModelForm): class Meta: model = Recipe … -
django simple history doesn't show in admin
I have followed the Django-simple-history documentation to display history from the admin page but somehow the history doesn't seem to appear from the admin page. I am using Django version 3.1.2 Here is my admin from django.contrib import admin from simple_history.admin import SimpleHistoryAdmin from .models import Company admin.site.register(Company, SimpleHistoryAdmin) -
display PIL image object in django template
i have edited the user profile photo with PIL library and trying to display the new image in my django template but somehow the image is not displaying ,here is my code in views.py : enterim = Image.open(get_user_model().objects.get(username=request.user).avatar) width, height = im.size newsize = (50, 50) image = im.resize(newsize) buffer = BytesIO() image.save(buffer, "PNG") img_str = buffer.getvalue() return render(request, '../templates/templates_v2/update_location.html', {'updatelocation_form': updatelocation_form,'user_info':user_info,'img_str':img_str}) and this is the img tag in html template: <img src='data:image/png;"+ {{img_str}} + "'/> Thanks in advance -
Django long model text field not loading from database but value exist in database
Django long model text field not loading from database but value exist in database. Databse used is Postgres. Since value is saved to database without issue I think problem is with Django loading afterwards. file_name in database: 2020-11-20-17-06-29_7e3410a8-4aa2-42d1-8225-3152757d433_v2ol-tHLIO_z7kyOPHfVAUHd13mcIE-7gD2OhFWowLc3RTfS1HKxxnPQ.mp3 In model.py class TestModel(models.Model): ... file_name = models.TextField(null=True) ... In view.py test_model = TestModel.objects.get(id=id) print(test_model.file_name) # file_name is None -
How to parse multipart form data by `MultipartParser`
I try to send list of values as a multipart form data by Swagger but I received comma separated array. attachments = "1,2,3,4" How I can send list of ids instead of comma separated array? class ProjectViewSet(UpdateModelMixin, CreateModelMixin): serializer_class = ProjectSerializer parser_classes = (MultiPartParser, ) permission_classes = (IsAuthenticated,) queryset = Project.objects.all() def create(self, request, **kwargs): serializer = self.get_serializer(data=request.data) if serializer.is_valid(raise_exception=True): project = serializer.create(serializer.validated_data, user=request.user) return Response(self.get_serializer(project).data) -
CSS from static folder in Django
my first question here. I'm still new to both Django and CSS. I'm trying to use CSS from Static folder in my Django project. It's all at a pretty basic stage. In the 'static' subfolder 'css' I have one main.css file with example code: body{ font-size: 20px; background-color: black; } h1{ color: #008000; } In my settings.py file I have: import os (...) DEBUG = True (...) STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static') ] And in my base.html template: {% load static %} <html lang="en"> <head> <meta charset="UTF-8"> <title>Shopping List</title> <link rel="stylesheet" type="text/css" href="{% static '/css/main.css' %}"> </head> <body> <h1>TEST</h1> {% block content %} {% endblock %} </body> </html> I've tried moving the css file, changing the view/url, and adding/deleting bootstrap (which alone works). In the end my page just turns light blue-ish. Thanks in advance. -
DRF Reverse Relationship Unable to Filter in Serializer
Having an interesting problem with DRF and wondering if anyone has any ideas. For a simplified example, take these two Django models: class Vote(models.Model): user_who_voted = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) vote = models.IntegerField(choices = [(-1, "down"), (1, "up")]) timestamp_voted = models.DateTimeField(auto_now = True) sample_model = models.ForeignKey('SampleModel', on_delete=models.CASCADE, related_name = 'sample_model_votes') class Meta: constraints = [models.UniqueConstraint(fields=['user_who_voted', 'sample_model_id'], name='one_vote_pp_sample_model')] class SampleModel (models.Model): #does some stuff In serializing SampleModel, I want to be able to get the value for vote for the request user (of which there is guaranteed to only be one vote, if any). In a Django shell, I can pull an instance/item of SampleModel easily: samplemodelexample = SampleModel.objects.get(pk = 1) and then I can traverse the reverse relationship to Vote successfully to return the vote value: samplemodelexample.sample_motel_votes.filter(user_who_voted_id = 1).get().vote Taking this exact same code (simplified to show relevant portions) into DRF seems to create an issue: class SampleModelSerializer(serializers.ModelSerializer): user_vote = serializers.SerializerMethodField() class Meta: model = SampleModel fields = ['user_vote'] read_only_fields = fields def get_user_vote(self, obj): try: vote = obj.sample_model_votes.filter(user_who_voted == self.context['request'].user).get().vote #stacktrace on this line return f"{vote}" except: traceback.print_exc() return '0' I get an error on the line indicated that NameError: name 'user_who_voted' is not defined Does anyone have any idea why? … -
AttributeError at /admin/pizza/topping/add/ 'NoneType' object has no attribute 'attname'
When i try to add entries from admin server i get the above error class Pizza(models.Model): name_text = models.CharField(max_length=200) def __init__(self): self.name_text class Topping(models.Model): name = models.ForeignKey(Pizza, on_delete=models.CASCADE) text = models.CharField(max_length=100) def __init__(self): self.text -
Dynamic Display of Address on Google Map Triggered by Selection
I have a list of products that I display on a web page. Each product has a seller with an address. When I click on a product, I want a Google Map on the same page to show the address of the seller of that product on the map. I'm using Django for my server-side technology but the solution I'm looking for can be pure HTML/CSS/JavaScript which I will then integrate. Any help would be greatly appreciated. Thanks. -
can't find mod_wsgi.so after yum installation
I'm trying to move an old client to a new server and get WSGI working for his django backend. I installed wsgi using yum; the httpd -M command shows that it is installed. However, the file mod_wsgi.so appears to be nowhere on the server. Earlier I had tried to include a WSGIScriptAlias command in the httpd.conf file, and received this error: /etc/apache2/conf.d/includes/pre_main_global.conf.tmp: Invalid command 'WSGIScriptAlias', perhaps misspelled or defined by a module not included in the server configuration --- /etc/apache2/conf.d/includes/pre_main_global.conf.tmp --- 1 ===> WSGIScriptAlias /spdre /home/pdr887629/django/sullivan/wsgi.py <=== --- /etc/apache2/conf.d/includes/pre_main_global.conf.tmp --- Another Stack Overflow solution on that error message said I should include this first: LoadModule wsgi_module modules/mod_wsgi.so But the mod_wsgi.so file does not actually exist in that directory, or anywhere else on the server. How can I get mod_wsgi working? Do I need to reinstall via another method, or is there somewhere I can go from here (with the current install)? Thank you for any assistance. -
The proper way to upset field in Mongodb using Djongo?
I have following Person model class Person(models.Model): id = models.ObjectIdField() # ----------------- CharFields ------------------ name = models.CharField(max_length=255) city = models.CharField(max_length=255) status = models.CharField(max_length=20) phone_number = models.CharField(max_length=10) objects = models.DjongoManager() def __str__(self): return self.name and comment model class Comment(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) comments = models.JSONField() objects = models.DjongoManager() The add_coment method looks like this @api_view(['POST']) def add_comment(request): comment_data = JSONParser().parse(request) comment_serializer = CommentSerializer(data=comment_data) if comment_serializer.is_valid(): comment_serializer.save() return JsonResponse(comment_serializer.data, status=status.HTTP_201_CREATED) return JsonResponse(comment_serializer.errors, status=status.HTTP_400_BAD_REQUEST) Then I call add_coment methods twice with the same request instead of update this field it create the other document. What is the proper way to perfume upsert operation?