Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django + djongo + mongodb to delete all data
I want to delete all data through djongo to operate mongodb, but django error: FAILED SQL: DELETE FROM "app01_test" Version: 1.2.24 The delete ORM is : models.Test.objects.all().delete() Anyone can help me? Thanks! -
how can I add CSRF token in VUE or reqwest?
when I send data to server, I get such reply: Forbidden (CSRF token missing or incorrect.) my questiong how can I add CSRF token for sending data with reqwest? because there is no beforesend hook. var app6 = new Vue({ el: '#app-6', data: { realtimecost:0, }, created() { setInterval(() => { this.realtimecost=this.realtimecost+1; if(this.realtimecost==5) this.sendData();// here }, 1000); }, methods: { sendData:function ()//send data { var self = this; reqwest({ url:'http://127.0.0.1:8000/tasks/', method:'post', type:'json', data: { realtimecost:5, },//end data success:function(resp){ //self.getData() }//end success })//end reqwest },//end senddata }//end method })//end app6 -
confusion when to use viewsets.Viewset and viewsets.ModelViewSet in django
According to django rest frame work 3.7 (viewsets.ViewSet) will provide routes for a standard set of create/retrieve/update/destroy style actions and (viewsets.ModelViewSet) also will provide routes for a standard set of create/retrieve/update/destroy style actions so when use this two class and what is the difference between this two.Thanks -
How to create micro services in django with python3
Write a micro services in django project to create a event drive architecture . -
Django: save foreign key according to string parameter?
Here is the thing. A branch may contains many products. A form would post path and branch to product model, in string format. How could I use like this Product.objects.create(path="path1", branch="branch1") when got the posted data? or the branch instance must be created in forms.py? Here is the wrong version: it would raise ValueError: Cannot assign "'branch1'": "Product.branch" must be a "Branch" instance. class Branch(models.Model): name = models.CharField(max_length=63, unique=True, blank=True) class Product(models.Model): path = models.CharField(max_length=255) branch = models.ForeignKey(Branch, on_delete=models.CASCADE) def save(self, *args, **kwargs): kwargs['branch'], _ = Branch.objects.get_or_create(name=kwargs['branch']) super(Product, self).save(*args, **kwargs) -
Urls not working after ssl in django site on nginx
I had a fully functional site at which I converted to be served through https:// using lets-encrypt free certbot using the tutorial at https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-16-04. Now after applying this my django urls for views as well as static files aren't working as expected. I have tried all the solutions I could find to the above problem from various forums but am unable to get it to work probably because I am new to https secure websites.Kindly Help Thanking you in advance :) nginx settings file - (/etc/nginx/sites-available/default) limit_conn_zone $binary_remote_addr zone=addr:10m; limit_req_zone $binary_remote_addr zone=one:10m rate=30r/m; server { server_name bits-bosm.ml www.bits-bosm.ml; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/sammy/regsoft/regsoft; expires max; } location / { include proxy_params; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; # proxy_set_header Host $http_host; proxy_redirect off; proxy_pass http://unix:/home/sammy/regsoft/regsoft/regsoft.sock; limit_req zone=one; limit_conn addr 10; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/bits-bosm.ml/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/bits-bosm.ml/privkey.pem; # managed by Certbot include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot gzip on; gzip_comp_level 5; gzip_min_length 256; gzip_proxied any; gzip_vary on; location ~* \.(ico|css|js|svg)$ { expires 7d; } } server { if ($host = www.bits-bosm.ml) { return 301 https://$host$request_uri; } # managed by β¦ -
Unable to install Python argon2_cffi
I am trying to install argon2_cffi in my python 3.5 virtual environment without using pip. I have downloaded the package from github . When I am trying to install this , python setup.py build or install , it fails with the error running install running bdist_egg running egg_info creating src/argon2_cffi.egg-info writing requirements to src/argon2_cffi.egg-info/requires.txt writing src/argon2_cffi.egg-info/PKG-INFO writing dependency_links to src/argon2_cffi.egg- info/dependency_links.txt writing top-level names to src/argon2_cffi.egg-info/top_level.txt writing manifest file 'src/argon2_cffi.egg-info/SOURCES.txt' reading manifest file 'src/argon2_cffi.egg-info/SOURCES.txt' reading manifest template 'MANIFEST.in' warning: no previously-included files found matching 'src/argon2/_ffi.py' warning: no previously-included files found matching '.gitmodules' warning: no previously-included files found matching 'extras/libargon2/.git' warning: no previously-included files found matching 'appveyor.yml' warning: no previously-included files matching '*.pyc' found under directory 'tests' no previously-included directories found matching 'docs/_build' writing manifest file 'src/argon2_cffi.egg-info/SOURCES.txt' installing library code to build/bdist.linux-x86_64/egg running build_clib building 'libargon2' library x86_64-linux-gnu-gcc -pthread -DNDEBUG -g -fwrapv -O2 -Wall -Wstrict- prototypes -g -fstack-protector-strong -Wformat -Werror=format- security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -msse2 - Iextras/libargon2/src/../include -Iextras/libargon2/src/blake2 -c extras/libargon2/src/argon2.c -o build/temp.linux-x86_64- 3.5/extras/libargon2/src/argon2.o x86_64-linux-gnu-gcc: error: extras/libargon2/src/argon2.c: No such file or directory x86_64-linux-gnu-gcc: fatal error: no input files compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 -
ImportError: cannot import name UnoBaseElement
File "/home/manohar/myenv/local/lib/python2.7/site-packages/uno/core.py", line 8, in from .base import UnoBase, UnoBaseElement, UnoBaseGroup -
Logout a user in Django when request comes from Vue.js
I have an app that uses Django for authorizations and REST API backend, but i am using Vue.js for front end. I was able to successfully create and log in users using this set up, but I am kinda struggling to log out users using Django's native functionality. Is there a way to do that besides using Django's logout(request), since this method requires a valid Django request? Thank you -
Django javascript text input not sending
So I'm working on a Django project and am trying to incorporate some javascript to make a instant messaging system. When I enter text and hit submit. Text doesn't pop out in the text box (like it does on im). However, if I got to the admin and create a message, I see the message pop up in the text box. In my powershell terminal I only see this: [11/Apr/2018 21:56:01] "GET /api/messages/25/1/ HTTP/1.1" 200 2 its a list [11/Apr/2018 21:56:01] "GET /api/messages/25/1/ HTTP/1.1" 200 2 It just spams that every few seconds. I have the string "it's a list' to show me that the view message_list is being hit. In IE console I only see this: The server encountered an unexpected condition that prevented it from fulfilling the request. (XHR)POST - http://127.0.0.1:8000/api/messages In firefox console I see this ( I can expand it a lot, but I can't make any sense of it): Object { originalEvent: submit, type: "submit", isDefaultPrevented: wa(), target: form#chat-box.form-group, currentTarget: form#chat-box.form-group, relatedTarget: undefined, timeStamp: 454442, jQuery3210627253594676053: true, delegateTarget: form#chat-box.form-group, handleObj: {β¦}, β¦ } And in chrome console I still see an old error for a line in chat.js that I changed in amazon aws s3 β¦ -
Gunicorn ImportError: No module named polls
I'm installing a previously built Django website on a new server using gunicorn and nginx. /home/ragequittech/manage.py runserver runs fine, however, when I shut it down and run /home/rageqquittech/ragequittech gunicorn --bind 0.0.0.0:8030 wsgi:application I get: [2018-04-12 01:36:06 +0000] [1842] [INFO] Starting gunicorn 19.4.5 [2018-04-12 01:36:06 +0000] [1842] [INFO] Listening at: http://0.0.0.0:8030 (1842) [2018-04-12 01:36:06 +0000] [1842] [INFO] Using worker: sync [2018-04-12 01:36:06 +0000] [1846] [INFO] Booting worker with pid: 1846 [2018-04-11 20:36:06 +0000] [1846] [ERROR] Exception in worker process: Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 515, in spawn_worker worker.init_process() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 122, in init_process self.load_wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/workers/base.py", line 130, in load_wsgi self.wsgi = self.app.wsgi() File "/usr/lib/python2.7/dist-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 65, in load return self.load_wsgiapp() File "/usr/lib/python2.7/dist-packages/gunicorn/app/wsgiapp.py", line 52, in load_wsgiapp return util.import_app(self.app_uri) File "/usr/lib/python2.7/dist-packages/gunicorn/util.py", line 366, in import_app __import__(module) File "/home/ragequittech/ratequittech/wsgi.py", line 21, in <module> application = get_wsgi_application() File "/usr/local/lib/python2.7/dist-packages/django/core/wsgi.py", line 13, in get_wsgi_application django.setup(set_prefix=False) File "/usr/local/lib/python2.7/dist-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python2.7/dist-packages/django/apps/config.py", line 94, in create module = import_module(entry) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named polls Traceback (most recent call last): File "/usr/lib/python2.7/dist-packages/gunicorn/arbiter.py", line 515, β¦ -
"sass.CompileError: Error: It's not clear which file to import" arising when using Django Compressor and Django Sass Processor
I'm trying to add the Materialize source to a Django project. In my stylesheets directory, I have the following structure: (venv) Kurts-MacBook-Pro-2:lucy kurtpeek$ tree lucy-web/lucy_web/static/stylesheets lucy-web/lucy_web/static/stylesheets βββ mixins.scss βββ terms_of_use.scss βββ vendor βββ components β βββ _badges.scss β βββ _buttons.scss β βββ _cards.scss β βββ _carousel.scss β βββ _chips.scss β βββ _collapsible.scss β βββ _color-classes.scss β βββ _color-variables.scss β βββ _datepicker.scss β βββ _dropdown.scss β βββ _global.scss β βββ _grid.scss β βββ _icons-material-design.scss β βββ _materialbox.scss β βββ _modal.scss β βββ _navbar.scss β βββ _normalize.scss β βββ _preloader.scss β βββ _pulse.scss β βββ _sidenav.scss β βββ _slider.scss β βββ _table_of_contents.scss β βββ _tabs.scss β βββ _tapTarget.scss β βββ _timepicker.scss β βββ _toast.scss β βββ _tooltip.scss β βββ _transitions.scss β βββ _typography.scss β βββ _variables.scss β βββ _waves.scss β βββ forms β βββ _checkboxes.scss β βββ _file-input.scss β βββ _forms.scss β βββ _input-fields.scss β βββ _radio-buttons.scss β βββ _range.scss β βββ _select.scss β βββ _switches.scss βββ materialize_v1.scss where materialize_v1.scss and components are downloaded from the source version available at http://materializecss.com/getting-started.html; I've renamed materialize.scss to materialize_v1.scss to avoid name collision with a legacy version. In terms_of_use.scss, I import materialize as follows: @import "vendor/materialize_v1"; // Materialize v1.0.0beta On my local machine in development β¦ -
Django 1.11 pass kwarg to modelform field
I would like to pass a kwarg to set a modelform field but im struggling to figure out how to do it. My URL is as follows: url(r'^tent/create/(?P<munc>\d+)',views.TentCreate.as_view(),name='tent_create'), My view is simply: class TentCreate(CreateView): model = Tent form_class = TentForm And my form: class TentForm(ModelForm): class Meta: model = Tent exclude =('asfo','niho') def __init__(self, *args, **kwargs): super(TentForm, self).__init__(*args, **kwargs) self.fields['primary'].queryset = Mark.objects.filter(munc=self.kwargs['munc']) from the model: class Tent(models.Model): primary = models.ForeignKey(Mark,on_delete=models.CASCADE) I can render the form fine without overriding def __init, with no filtering applied to the 'primary' field. However attempting to use the def __init code I've described above to pass the munc kwarg to the form field is resulting in the following error: "'TentForm' object has no attribute 'kwargs'" I've been going around in circles trying to work through this so I would be really appreciative if anyone is able to provide me some guidance to solve this. This is my first Django project so I'm learning how I go so I assume I have made some fundamental error somewhere here! -
How to filter parents based on multiple children django
I found a related question here: How can filter parent based on children in django However, I am stuck trying to find the parents who have a specific set of children. Using the same models as the related question: class Kid(models.Model): name = models.CharField(max_length=200) class Toy(models.Model): name = models.CharField(max_length=200) owner = models.ForeignKey(Kid) How can I find Kids who have a specific set of toys? Kid.objects.distinct().filter(has some toy__name='x', and another toy__name='y', and another toy__name='z', and another .... ) -
Django models.py migrate
I know that there are already a couple of threads about the migration/ makemigrations commands but none of them worked out for me, even after I reset the entire database with the flush command. The error after I executed migrations is: `Exception Type: OperationalError Exception Value: no such column: geruestproject_billing.id` The weird thing is that the 0001.initial.py creates the class but adds the attribute via migrations.AddField. The code is posted below initial = True dependencies = [ ] operations = [ migrations.CreateModel( name='Billing', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ], options={ 'verbose_name_plural': 'Rechnungen', }, ), migrations.CreateModel( name='Client', fields=[ ('Client', models.AutoField(primary_key=True, serialize=False)), ('Company_Name', models.CharField(blank=True, max_length=50, verbose_name='Firma')), ('Company_Email', models.EmailField(blank=True, max_length=254, verbose_name='Firma Email')), ('Company_Phone', models.CharField(blank=True, max_length=20, verbose_name='Telefon Firma')), ('Company_PostalCode', models.CharField(blank=True, max_length=6, verbose_name='Postleitzahl')), ('Company_City', models.CharField(blank=True, max_length=20, verbose_name='Stadt')), ('Company_Street', models.CharField(blank=True, max_length=20, verbose_name='Strasse')), ('Contact_LastName', models.CharField(blank=True, max_length=50, verbose_name='Nachname')), ('Contact_FirstName', models.CharField(blank=True, max_length=50, verbose_name='Vorname')), ('Contact_Phone', models.CharField(blank=True, max_length=20, verbose_name='Telefon Kontakt')), ], options={ 'verbose_name_plural': 'Kunden', }, ), migrations.CreateModel( name='Inventory', fields=[ ('Item', models.DecimalField(decimal_places=2, max_digits=5, primary_key=True, serialize=False)), ('Name', models.CharField(max_length=50)), ('Price', models.DecimalField(decimal_places=2, max_digits=7, null=True, verbose_name='Preis in β¬')), ('Amount', models.IntegerField(default=1000)), ], options={ 'verbose_name_plural': 'Lager', }, ), migrations.CreateModel( name='Project', fields=[ ('Project', models.AutoField(primary_key=True, serialize=False)), ('Project_Amount', models.IntegerField(default=10)), ('Item', models.ForeignKey(on_delete='SET_NULL', to='geruestproject.Inventory')), ], options={ 'verbose_name_plural': 'Projekte', }, ), migrations.AddField( model_name='billing', name='invoice_client', field=models.ForeignKey(default='', on_delete='CASCADE', to='geruestproject.Client'), ), ] My model is posted β¦ -
cannot get mod_wsgi working for https but it works for http. 'Client denied by server configuration'
I have a web application using Django and I am trying to use mod_wsgi to run my web server over https. The following command generates configuration that works and allows me to connect via port 80. sudo python3.6 manage.py runmodwsgi --setup-only --port=80 --user apache --group apache --server-root=/etc/mod_wsgi-express-80 However when I use following command I am getting a client denied by server configuration error. I get this error whether I try to access it from the same host or external. sudo python3.6 manage.py runmodwsgi --setup-only --user=apache --group=apache --server-root=/etc/mod_wsgi-express-443 --https-only --https-port=443 --ssl-certificate-file=/etc/pki/tls/certs/localhost.crt --ssl-certificate-key-file=/etc/pki/tls/private/localhost.key --server-name=myhost.local From web browser Forbidden You don't have permission to access /login/ on this server. in the error_log Wed Apr 11 18:47:33.429059 2018] [mpm_event:notice] [pid 12053:tid 140251110680704] AH00489: Apache/2.4.6 (CentOS) mod_wsgi/4.6.4 Python/3.6 OpenSSL/1.0.2k-fips configured -- resuming normal operations [Wed Apr 11 18:47:33.429098 2018] [core:notice] [pid 12053:tid 140251110680704] AH00094: Command line: 'httpd (mod_wsgi-express) -f /etc/mod_wsgi-express-443/httpd.conf -D MOD_WSGI_VIRTUAL_HOST -D MOD_WSGI_WITH_HTTPS -D MOD_WSGI_HTTPS_ONLY -D MOD_WSGI_MPM_ENABLE_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_EVENT_MODULE -D MOD_WSGI_MPM_EXISTS_WORKER_MODULE -D MOD_WSGI_MPM_EXISTS_PREFORK_MODULE' [Wed Apr 11 18:47:50.725314 2018] [authz_core:error] [pid 12061:tid 140251110143744] [client 10.16.18.11:63623] AH01630: client denied by server configuration: /etc/mod_wsgi-express-443/htdocs/ many thanks. -
how to set Non-expiring access tokens in Oauth_provider_toolkit Django rest_framework?
Is it posible to configure the django-oauth-toolkit in order to all the tokens created never expires? -
Regarding django views views.py :: "model.objects.filter(first_name__icontains=auth , last_name__icontains=auth)"
I have a very basic question though In "model.objects.filter(first_name__icontains=auth , last_name__icontains=auth)" this filters names by matching the keywords in both first name AND last name. For an instance if names in database are: Rachel Green Chandler Bing Joey Tribiani and I search for keyword 'n' Then it shows only 'Chandler Bing' because its contains 'n' in both first name AND last name.But how to make changes in the code so that it shows results that contains 'n' in either first name OR last name OR in both. -
Post with image using python-twitter in django project
I am using django 1.11 and python-twitter==3.3. With my code below I would like to post tweet (with celery) with image. But I got error: FileNotFoundError: [Errno 2] No such file or directory: '/media/logo.png' My settings for media in setting.py: MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Here is part of my code in tasks.py t = twitter.Api(consumer_key=_consumer_key, consumer_secret=_consumer_secret, access_token_key=oauth_token, access_token_secret=oauth_token_secret) tweet_list = Tweet.objects.all() for tweet in tweet_list: t.PostUpdate(tweet.status, media=tweet.image.url) tweet.save() -
Postgres - How to Join Tables without duplicates
I'm working on a project that locally used SQLite, now when moving to PostGres (On Heroku) my query reported an error "r.social must appear in the GROUP BY clause or be used in an aggregate function" The original query is: SELECT DISTINCT c.name, r.social, c.description, p.price FROM cryptomodels_coin c LEFT JOIN cryptomodels_coinprice p ON p.coin_id = c.name LEFT JOIN cryptomodels_CoinRating r ON r.coin_id = c.name GROUP BY c.name Which works fine locally, with one unique row returned for each coin When I added this to the PostGres environment, it threw the aggregate function error mentioned above - I managed to resolve this by adding all columns to the "Group by" clause, as seen below: SELECT DISTINCT c.name, r.social, c.description, p.price FROM cryptomodels_coin c LEFT JOIN cryptomodels_coinprice p ON p.coin_id = c.name LEFT JOIN cryptomodels_CoinRating r ON r.coin_id = c.name GROUP BY c.name, r.social, c.description, p.price The issue is that I now have duplicate rows for each coin I've done a fair bit of reading and tried numerous solutions, some of which throw errors and others still result in duplicate rows, really not sure how to proceed, thank you for any assistance -
argparse: "unrecognized arguments" when supplying an optional argument?
With argparse as used in Django management commands, how can I specify an optional argument, that is stored as false unless included? I want to ensure that certain things in my code only run if I explicitly include a --not_a_dry_run argument. I've got this code: class Command(BaseCommand): def add_arguments(self, parser): parser.add_argument('not_a_dry_run', action='store_false') def handle(self, *args, **options): print (options) if options['not_a_dry_run']: # actually run If I run python manage,py mycommand (ie without the argument) then not_a_dry_run is False, as expected. But if I run python manage.py mycommand --not_a_dry_run then I get error: unrecognized arguments: --not_a_dry_run. -
Django form outputting the default field value every time
Here's my model/form: class AdvertisePost(Post): position = models.IntegerField(default=DURATION_CHOICES[2][0], choices=DURATION_CHOICES) duration = models.IntegerField(default=48) def __str__(self): return self.title class AdvertisePostForm(forms.ModelForm): position = forms.ChoiceField(widget=forms.RadioSelect, required=False, choices=DURATION_CHOICES) duration = forms.IntegerField(widget=forms.NumberInput(attrs={'type':'range', 'step': '1', 'min': '1', 'max': '148'}), required=False) class Meta: model = AdvertisePost fields = [ ... 'position', 'duration' ] views def options(request): options_form = AdvertisePostForm(request.POST or None, request.FILES or None) if options_form.is_valid(): instance = options_form.save(commit=False) print(instance.duration) #prints 8 every time (default value) print(instance.position) #prints 48 every time (default value) context = { 'options_form': options_form } return render(request, 'advertising/options.html', context) and my template <form method="post" enctype="multipart/form-data" autocomplete="off">{% csrf_token %} {{ options_form.position }} {{ options_form.duration }} <input type="submit" /> </form> Even though I change the values it outputs the same default value every time. Any idea why this is and how I can fix this? -
Check if string matches dynamic regexp and find variables
In django web app, user may define urls with dynamic parameters, for example: /users/:id or /posts/:postid/:commentid now, I have given strings, for example: /users/mysername <- it matches /users/:id - how can I exstract "myusername" from it? /users/mysuername/something <- doesn't match /posts/10/382 - match, extract two variables - postid and commentid my models.py: class Server(BaseModel): url = models.CharField(verbose_name=_('URL'), max_length=64) in my view, I want to compare request's PATH_INFO: endpoint_url = request.META.get('PATH_INFO').lower().strip().lstrip('/') lets say I have a Server model instance with url: /users/:someid now, when request path is: /users/somestring0 I want to match it and extract variable someid to be "somestring0". Parmeters may contain anything - except slash (/) probably. How can I achieve something like that? -
Django view not saving to model
I have a view I am calling when a user clicks a button on the site, it pulls JSON data(from the Coinbase API) and converts it to a string and should save the string pulled to the current user's account. Whenever they click the button it will pull the string, but nothing is saved to the account, which is the issue. views.py from django.shortcuts import render from django.http import HttpResponse from django.contrib.auth.decorators import login_required from ico_login.models import UserAddress from coinbase.wallet.client import Client @login_required() def generate_address_btc(request, *args, **kwargs): client = Client('api', 'key') r = client.get_addresses('account_id') address = r['data'][0]['address'] request.user.address = str(address) request.user.save() return HttpResponse(address) models.py from django.db import models from django.contrib.auth.models import User class UserAddress(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) address = models.CharField(max_length=300, default=' ') urls.py from django.contrib import admin from django.urls import path, include from ico_details import views urlpatterns = [ path('create_address/', views.generate_address_btc, name='generate') ] -
How to update field in another model
i am trying to update field in another model by serializer.py but i get this error: duplicate key value violates unique constraint "sales_company_company_name_8f098bd8_uniq" DETAIL: Key (company_name)=(fdsfasf) already exists. serializer.py code: Company model is a FK in Customer model class CompanySerializer(serializers.ModelSerializer): model = models.Company fields = ('company_name',) class CustomersIsCompanySerializer(serializers.ModelSerializer): company = CompanySerializer company_name = serializers.CharField(max_length=255) def update(self, instance, validated_data): instance.company_name = models.Company.objects.update(company_name=validated_data.get('company_name', instance.company_name)) instance.phone = validated_data.get('phone', instance.phone) instance.mobile = validated_data.get('mobile', instance.mobile) instance.email = validated_data.get('email', instance.email) instance.website = validated_data.get('website', instance.website) instance.save() return instance class Meta: model = models.Customers fields = ( 'id', 'company_name', 'phone', 'mobile', 'email', 'website', ) extra_kwargs = { 'phone': {'validators': []}, 'mobile': {'validators': []}, 'email': {'validators': []}, 'website': {'validators': []}, } def create(self, validated_data): company = models.Company.objects.create(company_name=validated_data['company_name']) validated_data['company_name'] = company customer = models.Customers.objects.create(**validated_data) return customer and my view code : class CustomerIsCompanyGetIdPutPatchView(generics.RetrieveAPIView, mixins.UpdateModelMixin): permission_classes = (AllowAny,) queryset = models.Customers.objects.all() serializer_class = CustomersIsCompanySerializer def get_object(self): id = self.kwargs['id'] obj = generics.get_object_or_404(User, id=id) return obj def put(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) def patch(self, request, *args, **kwargs): return self.update(request, *args, **kwargs) but if i replace update and but create it work fine but it make a new line in the DB not update the old line. for example if β¦