Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to organize apps/sub apps in Django
This is more of a conceptual question - I'm new to Django and I'm building a series of apps. Inside of these apps I'd like there to be other apps, or at least a way to organize them so that there arent just apps everywhere in my project. ie. inside my project there will be app 1, 2, 3, 4, 5, etc. and related to app 1 is app a, b, c, d, and e, although app a, b, c, d, and e might also have a relation to apps 2 and 3 in some way, they would still most definitely belong to app 1. Its a very big project and there will probably end up being hundreds of apps when I'm done. Whats the best way to do this? Thank you for any suggestion or advice -
Communicate AJAX and Django View in template
Hello I am trying to communicate my view to my ajax script. urls.py from .views import ( video_testimonial, ) urlpatterns = [ url(r'^(?P<id>\d+)/video_testimonial/$', video_testimonial, name='video_testimonial'), ] So basically it requires an integer in order the url can be access. e.g 0/video_testimonial/ Here's my views.py def video_testimonial(request, id): testimonial = Testimonial.objects.filter(id=id) if request.is_ajax(): context = { 'testimonial': testimonial, } return JsonResponse(context) else: raise Http404 my script (internal script) in my html: presentation.html function showVideoTestimonial() { var id = parseInt($('.carousel-inner a').attr('id')); $.ajax({ url: id +'/video_testimonial/', success: function (data) { console.log(data.testimonial); $('.carousel-inner a').click(function () { console.log(id); }); } }) } showVideoTestimonial(); url: id +'/video_testimonial/', am i missing something accessing the url? thanks for responding EDIT: error shows: -
Why capture a regex expression in Django?
Why capture a url regex expression without name in Django? url(r'^books/([\w-]+)/$', PublisherBookList.as_view()), [\w-]+ is captured with () but why? -
Django server - 502 error bad gateway
I have a centOS with a virtualenv, i can use the project in my localhost , but when the project is upload to a server give an error : 502 - bad gateway I think the problem probably is in my nginx file. server { listen 80; server_name www.site.com.br site.com.br; root /var/www/html/agrodez/src/; if ($http_host != "www.site.com.br") { rewrite ^ http://site.com.br$request_uri permanent; } location /static/ { alias /var/www/html/site/src/sistema/static/; } location /{ proxy_pass http://localhost:8000; include /etc/nginx/proxy_params; } -
Custom django foreignfield
Anybody knows how to create a foreignkey field and make it always point to same model, so far I got these. class PanMachineTimeUnitField(models.ForeignKey): def __init__(self, **kwargs): to = 'panbas.PanBasTimeUnit' kwargs['verbose_name'] = _('Machine Unit') kwargs['related_name'] = 'machine_unit' super(PanMachineTimeUnitField, self).__init__(to, **kwargs) But I got errors when on start. I aim to use it like, machine_unit = PanMachineTimeUnitField() No further declarations needed. -
Need clarity on using django-rest-framework-jwt with django-rest-auth for social login
I am able to receive a facebook authentication access_token from django-rest-auth by following their instructions in their docs, but it doesn't look like it's a JWT token generated by django-rest-framework-jwt. I did set REST_USE_JWT = True in settings.py. That's all I've done, I'm not sure if there's anything else I need to do to ensure that the token is being generated by JWT. I set up an endpoint to verify a jwt token like so: from rest_framework_jwt.views import obtain_jwt_token, verify_jwt_token urlpatterns = [ url(r'^api/token-verify/', verify_jwt_token), ] that's how I'm testing if the access token received by this endpoint url(r'^rest-auth/facebook/$', views.FacebookLogin.as_view(), name='fb_login'), is a valid JWT token. When I try to verify the token I get an error Error decoding signature. On a side note, I noticed when I try to do a POST request to rest-auth/facebook/ API endpoint twice using the same access_token returned by a Facebook login I am receiving a 403 Forbidden from django. Can someone please explain a bit how to make JWT work with django-rest-auth? -
Django: Iterating over a reversed many-to-many relationship
I have created a many-to-many relationship between my User model and my Projects model, and I want to list all the projects a specific user is part of on the user's profile page. My models are: class User(auth.models.User,auth.models.PermissionsMixin): def __str__(self): return "@{}".format(self.username) class Prosjekter(models.Model): id = models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') ... users = models.ManyToManyField(settings.AUTH_USER_MODEL, blank=True, verbose_name="Project participants") ... The Django documentation states that: Reverse m2m queries are supported (i.e., starting at the table that doesn’t have a ManyToManyField): >>> Publication.objects.filter(article__id=1) <QuerySet [<Publication: The Python Journal>]> I am able to print the QuerySet of a specific user by typing (here illustrated with the user whose primary key is 2): class UserDetailView(generic.DetailView): model = User template_name = 'accounts/user_detail.html' results = Prosjekter.objects.filter(users__pk=2), print(results) This will return: (<QuerySet [<Prosjekter: Project 1>, <Prosjekter: Project two>, <Prosjekter: Project third>]>,) However, as you can see, I am only calling the user whose primary key is 2. Instead, I want to create a view that can be used in the general sense. Specifically, that I can see: all user 1's projects on http://.../users/1/ all user 2's projects on http://.../users/2/ and so on I am new to Python and Django and have trouble creating this view. Among many other … -
Manipulate Excel Data Before Adding to Database with Django - Order of Operations?
I receive 6 weekly excel reports that I've been manually compiling into a very large monthly report. Each report has between 5-30 columns, and 4000 to 130,000 rows. I'm putting together a simple Django app that allows you to upload each report, and the data ends up in the database. Here's my models.py: #UPEXCEL models from django.db import models ############## LISTS ############### class TransactionTypeList(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class TransactionAppTypeList(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name class CrmCaseOriginList(models.Model): name = models.CharField(max_length=100) def __str__(self): return self.name ############## CLIENTS AND STAFF ############### class Staff(models.Model): name = models.CharField(max_length=40) employee_id = models.CharField(max_length=40) start_date = models.TimeField(blank=True, null=True) end_date = models.DateField(blank=True, null=True) first_name = models.CharField(blank=True, null=True, max_length=40) last_name = models.CharField(blank=True, null=True, max_length=40) email = models.EmailField(blank=True, null=True) phone = models.CharField(blank=True, null=True, max_length=20) street = models.CharField(blank=True, null=True, max_length=100) city = models.CharField(blank=True, null=True, max_length=100) state = models.CharField(blank=True, null=True, max_length=2) zipcode = models.CharField(blank=True, null=True, max_length=10) is_team_lead = models.BooleanField(default=False) boss = models.ForeignKey('Staff', related_name='Boss', null=True, blank=True) def __str__(self): return self.name class Meta: app_label="upexcel" class Client(models.Model): name = models.CharField(max_length=40) short_name = models.CharField(max_length=20, blank=True, null=True) start_date = models.DateField(default=timezone.now, blank=True, null=True) end_date = models.DateField(blank=True, null=True) team_lead = models.ForeignKey(Staff, related_name='client_team_lead') def __str__(self): return self.name class ClientNameChart(models.Model): client_name = models.ForeignKey(Client, related_name='client_corrected_name') name_variation = … -
Can not access admin on Heroku
So i pushed my Code to Heroku and I have a lot of trouble getting things to work. The Static files do not work, I installed WhiteNoise and so on but I break the site as soon as I use {%static 'js/whatever.js'%} but {% load staticfiles %} can be used without breaking the server. Currently my theory is that the admin won't load because of the static files but they are not required for the normal django admin right? Here are my important lines I hope somebody finds the mistake. settings.py DEBUG = False ALLOWED_HOSTS = [u'....herokuapp.com'] import dj_database_url DATABASES ={'default':dj_database_url.parse('postgres://...jl4',conn_max_age=600)} INSTALLED_APPS = [ 'rest_framework',"rest_framework.authtoken",'django.contrib.admin','django.contrib.auth','django.contrib.staticfiles',] AUTHENTICATION_BACKENDS =('django.contrib.auth.backends.ModelBackend',) SITE_ID = 1 WSGI_APPLICATION = 'ABC.wsgi.application' STATIC_URL = '/static/' STATICFILES_DIRS =[os.path.join(BASE_DIR, 'static'), ] STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), 'static') STATICFILES_STORAGE ='whitenoise.django.GzipManifestStaticFilesStorage' wsgi.py import os from django.core.wsgi import get_wsgi_application from whitenoise.django import DjangoWhiteNoise os.environ.setdefault("DJANGO_SETTINGS_MODULE", "ABC.settings") application = get_wsgi_application() application = DjangoWhiteNoise(application) application.add_files('/ABC/static/', prefix='/static/') Procfile file, requirements.txt, .git folder are present and look normal. I have no problems on 127.0.0.1 at all. No migration problems anywhere. Heroku is configured with a Python Buildpack and Postgres. 404 500 etc Handlers are installed and working (Btw I get a 500 Internal Server Error). When I push the Code online … -
Django: Override {{form.as_p}} to add style to each field
Hello I want to override {{form.as_p}} because i need to add styles to every field but every field has a differente style, example: The first field I need to be like a checklist and the others only text something like tha. My project is in Django 1.11 and Python 3.4.3 -
Model thinks my string is tuple and won't save
I have a model that I'm trying to override save on, but when I pass the information it thinks the string is a tuple, and won't save the information in the model. The particular field I'm pulling in is a single line address that looks like this: 3107 Eric Motorway, Lake William, GU 71954, but my model thinks the commas are a tuple. I've tried casting it to a string and everything. Models.py: class AddressBook(models.Model): address = models.CharField(max_length=250, unique=True) name = models.CharField(max_length=250) def __str__(self): return self.address class Freight(models.Model): pu_location = models.OneToOneField(AddressBook, to_field='address', related_name='pu_location') pu_customer = models.CharField(max_length=200) pu_appt_time = models.DateTimeField(default=datetime.now) po_number = models.CharField(max_length=20) load_number = models.CharField(max_length=10, blank=True, null=True) pallet_count = models.IntegerField(validators=[MaxValueValidator(999)]) content_type = models.CharField(max_length=20, choices=[('Frozen', 'Frozen'), ('Chilled', 'Chilled'), ('Dry', 'Dry')]) cases_count = models.IntegerField(validators=[MaxValueValidator(9999)]) weight = models.IntegerField(validators=[MaxValueValidator(99999)]) del_customer = models.CharField(max_length=200) del_location = models.OneToOneField(AddressBook, to_field='address', related_name='del_location') del_city = models.CharField(max_length=50, blank=True, null=True) del_state = models.CharField(max_length=2, blank=True, null=True) del_appt_time = models.DateTimeField(default=datetime.now) invoice_amount = models.FloatField(default=0.00, validators=[MinValueValidator(0.00), MaxValueValidator(999999.00)]) def save(self, *args, **kwargs): reg = re.compile(r',+?(?P<city>[^,]+),\s+(?P<state>[A-Za-z]{2})') print(self.del_location) extract = reg.search(self.del_location) city = extract.group('city') state = extract.group('state') if not self.del_state: self.del_city = city if not self.del_city: self.del_state = state def __str__(self): return self.po_number, self.pu_customer, self.del_location traceback info: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/admin/dispatch/freight/add/ Django Version: 1.11.2 Python Version: … -
setup.py install not working for django-visits
I am not sure what I am doing wrong, the process seemed pretty straight forward: I had to fix something for the django-visits module and so I forked this: https://bitbucket.org/jespino/django-visits Did the fix. Then in the source folder tried to do a: python setup.py install on my mac os x. First it gives an error: Using /usr/local/lib/python2.7/site-packages Searching for setuptools==21.2.1 Best match: setuptools 21.2.1 Adding setuptools 21.2.1 to easy-install.pth file error: [Errno 13] Permission denied: '/usr/local/lib/python2.7/site-packages/setuptools.pth' So I did: sudo python setup.py install and I got this output: running install running bdist_egg running egg_info writing requirements to django_visits.egg-info/requires.txt writing django_visits.egg-info/PKG-INFO writing top-level names to django_visits.egg-info/top_level.txt writing dependency_links to django_visits.egg-info/dependency_links.txt reading manifest file 'django_visits.egg-info/SOURCES.txt' writing manifest file 'django_visits.egg-info/SOURCES.txt' installing library code to build/bdist.macosx-10.11-x86_64/egg running install_lib running build_py creating build/bdist.macosx-10.11-x86_64/egg copying build/lib/.DS_Store -> build/bdist.macosx-10.11-x86_64/egg creating build/bdist.macosx-10.11-x86_64/egg/visits copying build/lib/visits/__init__.py -> build/bdist.macosx-10.11-x86_64/egg/visits copying build/lib/visits/admin.py -> build/bdist.macosx-10.11-x86_64/egg/visits copying build/lib/visits/context_processors.py -> build/bdist.macosx-10.11-x86_64/egg/visits copying build/lib/visits/middleware.py -> build/bdist.macosx-10.11-x86_64/egg/visits creating build/bdist.macosx-10.11-x86_64/egg/visits/migrations copying build/lib/visits/migrations/0001_initial.py -> build/bdist.macosx-10.11-x86_64/egg/visits/migrations copying build/lib/visits/migrations/0002_auto__chg_field_visit_uri.py -> build/bdist.macosx-10.11-x86_64/egg/visits/migrations copying build/lib/visits/migrations/__init__.py -> build/bdist.macosx-10.11-x86_64/egg/visits/migrations copying build/lib/visits/models.py -> build/bdist.macosx-10.11-x86_64/egg/visits copying build/lib/visits/settings.py -> build/bdist.macosx-10.11-x86_64/egg/visits creating build/bdist.macosx-10.11-x86_64/egg/visits/templatetags copying build/lib/visits/templatetags/__init__.py -> build/bdist.macosx-10.11-x86_64/egg/visits/templatetags copying build/lib/visits/templatetags/visits_tags.py -> build/bdist.macosx-10.11-x86_64/egg/visits/templatetags copying build/lib/visits/tests.py -> build/bdist.macosx-10.11-x86_64/egg/visits copying build/lib/visits/utils.py -> build/bdist.macosx-10.11-x86_64/egg/visits byte-compiling build/bdist.macosx-10.11-x86_64/egg/visits/__init__.py to __init__.pyc byte-compiling build/bdist.macosx-10.11-x86_64/egg/visits/admin.py to admin.pyc byte-compiling build/bdist.macosx-10.11-x86_64/egg/visits/context_processors.py … -
Django Rest Framework - Column 'brith_date' cannot be null (when it isn't)
I'm getting the following error when posting to my api to create a user: I'm using the following function: def create(self, validated_data): user_data = validated_data.pop('user') print(validated_data) user = User.objects.create(**user_data) validated_data.user_id = user.id print(validated_data) profile = Profile.objects.create(**validated_data) return profile My user is created perfectly but the error comes up when I'm trying to create the profile. validated_data contains the following after the user pop: {'phone': '81156598', 'birth_date': datetime.date(2017, 6, 29)} I'm adding afterwards the user_id from the user that was created and passing that in my Profile.objects.create(**validated_data) but I get the birth_date cannot be null error. Do I need to get all my date formats from a post and then send it back to validated_data? There should be another way shouldn't it? Thank you -
django upload file on a ftp server
I would like to upload a file on a distant server by FTP for example or other protocol. For now, my files are saved on media/$user_id$/avatar/my_file But I want something like sftp://USER@x.x.x.x/folder/ def user_directory_path(instance, filename): return 'media/user_{0}/avatar/{1}/'.format(instance.user.id, filename) class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birthdate = models.DateField(null=True, blank=True) avatar = models.ImageField(upload_to=user_directory_path, blank=True, null=True) -
Visibility of class definition
This may be a simple Python question, however after searching for "imported name not defined" and similar criteria, I did not find an answer to this. I have a models.py, as prescribed by django, with class definitions for all models. I then have a loadtestdata.py which is simply a programmatic way to populate the database with some initial entries. Within loadtestdata.py, I import all the models using "from myproject.models import *". This seems to work as 'global code' within loadtestdata.py is able to see all the class names imported from models.py. It can populate the database just fine. However if I define a function inside loadtestdata.py, suddenly that function is unable to see any of the imported class names. For example, this function would not see ImportedModelName: def AddSomeEntries(list1): for value in list1: new_model = ImportedModelName() # set some stuff on the model new_model.save() AddSomeEntries([1,2,3,4,5]) However, I could write this and it sees ImportedModelName just fine new_model = ImportedModelName() # set some stuff on the model new_model.save() Why does the former example not see the imported class, but the latter example can? -
Unable to django app to ElasticBeanstalk
I am trying to deploy a django app to Elasticbeanstalk and I receive this error. my Dockerfile already run pip install -r requirements.txt and django is part of the extensions installed. -
Traefik + Docker + Django
I have a docker swarm with running traefik. Everything works fine for the Most services when i set traefik.port it works perfect. Except the following: I have a django app with the service entrypoint in docker: python manage.py runserver the Service does Start and stays alive. But i am Not getting any docker service logs and if i call it with traefik service.domain.de i get an "Bad Gateway". Does someone has a Clou where my mistake is? I know that traefic is a http reverse proxy, but is there a Dirty tunneling trick how i can for example connect to a mysql dB via traefik with heidisql from external? Thanks :) -
Adding Filter to Django REST API
I am pretty new to Django and REST and I want to be able to specify a value and have the REST api only return a row where that value is met. Kinda like in sql select * from exampleTBL where id = 1 and then the first row is returned. But it would be done through the url: www.website/api/tmpHost/?id=1 and t hen the first row is returned through the REST API My view looks like: class tmp_HostList(APIView): def get (self, request, format=None): tmp_hosts = tmp_Host.objects.all() serializer = tmp_HostSerializer(tmp_hosts, many=True, context={'request': request}) return Response(serializer.data) def post(self, request, format=None): serializer = tmp_HostSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) else: return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) my url looks like: url(r'^api/tmpHost/$', views.tmp_HostList.as_view()), my serializer looks like: class tmp_HostSerializer(DynamicFieldsMixin, serializers.ModelSerializer): class Meta: model = tmp_Host fields = '__all__' How would I go about doing this? I've seen solutions around here but they don't seem to work for me. The differences where that I use APIView and my serializer line would be: serializer = tmp_HostSerializer(tmp_hosts, many=True, context={'request': request}) while theirs would be simple like: serializer = tmp_HostSerializer -
How to set created_by field for formset
I have this CreateView below, where I am trying to set the user who created the Hour model via the hour_formset, by the currently logged in user. I have tried answers from online but I still get new errors. This time the error I am getting is 'ManagementForm data is missing or has been tampered with']. This is my CreateView: class AddElement(LoginRequiredMixin, SuccessMessageMixin, CreateView): form_class = ElementForm template_name = "template.html" def get_form_kwargs(self): kwargs = super(AddElement, self).get_form_kwargs() kwargs['voip_user'] = self.request.user kwargs['phone_id'] = self.kwargs['phone_id'] return kwargs def form_valid(self, form): context = self.get_context_data() formset = context['hour_formset'] element = form.save(commit=False) phone_id = self.kwargs["phone_id"] phone = get_object_or_404(Phone, id=phone_id) element.phone = phone form.instance.phone = Phone.objects.get(id=phone_id) form.instance.created_by = MyUser.objects.get(user=self.request.user) if formset.is_valid(): self.object = form.save() formset.instance = self.object formset.save() element.save() form.save_m2m() return super(AddElement, self).form_valid(form) else: return self.render_to_response(self.get_context_data(form=form)) def get_context_data(self, **kwargs): data = { 'form-TOTAL_FORMS': '2', } my_user = MyUser.objects.get(user=self.request.user) context = super(AddElement, self).get_context_data(**kwargs) phone_id = self.kwargs["phone_id"] phone = Phone.objects.get(id=phone_id) context["phone_name"] = phone.name if self.request.POST: context['hour_formset'] = HourFormSet( data, self.request.POST, user=MyUser.objects.get(user=self.request.user)) else: context['hour_formset'] = HourFormSet(instance=Rule) In forms.py: class BaseElementFormSet(BaseModelFormSet): def __init__(self, *args, **kwargs): self.my_user = kwargs.pop('user') super(BaseElementFormSet, self).__init__(*args, **kwargs) def save_new(self, form, commit=True): obj = form.save(commit=False) obj.created_by = self.my_user if commit: obj.save() return obj HourFormSet = inlineformset_factory( Element, Hour, … -
How update relation fiels in DjangoRestFramework
I recently began to learn DRF library, I do not understand how in this example make method update in AlbumSerializer to save foreign key. Thank you in advance. -
django.db.utils.ProgrammingError: column owner_id does not exist
I encountered a strange problem and would appreciate any help. I added the following owner field to my model: owner = models.ForeignKey(User, on_delete=models.CASCADE, related_name='experiments', null=True, blank=True, default=None) The command ./manage.py migrate works fine, and everything seems to work, but I can't run the tests, since ./manage.py test always returns the following error: django.db.utils.ProgrammingError: column owner_id does not exist P.S.: the Django version is 1.10.5, the database engine is PostgreSQL. -
Making a custom id field in Django models
I'm trying to make a model in Django that has a custom id attribute. I want it to always equal the sum of 10000 and the current id number of that instance. How exactly do I write that? And do I have to do anything in the view? -
Fixing broken django module that was installed from pip, where is the code?
I have been trying to use the django-visits module, though I seem to not even get this to run cause the minute I follow the instructions for just adding it to my application here: https://bitbucket.org/jespino/django-visits/src/c3ac83b91969?at=default It gives me an error when I try to run server: ERRORS: visits.Visit.ip_address: (fields.E900) IPAddressField has been removed except for support in historical migrations. HINT: Use GenericIPAddressField instead. Their hint was helpful enough, but I have no idea where pip instaleld my django-visits to where I can change the model code of this module to fix the IPAdressField Am I approaching solving this error wrong? Should I not be looking for the original code that was installed somewhere on my machine? Do I need to somehow install this from source and not use Pip since I have to change the models.py in this module? -
Sending data by websockets from parallel thread
Today i have been trying to create an asynchronous task between Javascript and Django. To create websockets and manage them, I used third party API pusher (Please make sure that question is not specific for the pusher). This system worked well at first when it was used in the main thread: import pusher import time from django.shortcuts import render ... def myView(request): ... def sendData(): time.sleep(10) pusher_client = pusher.Pusher( args='values', ) pusher_client.trigger('my-channel', 'my-event', {'message': 'Test'}) ... return render('My.html', {'keys': 'values'}) And this is the listener in the Javascript: var channel = pusher.subscribe('my-channel'); channel.bind('my-event', function(data) { alert(data.message); }); Then i wanted to create a parallel thread, So the user wouldn't wait 10 seconds to receive parallel thread. Instead, The template would be displayed and user would get alerted in 10 seconds after request. So i added following code: import pusher import time from django.shortcuts import render from threading import Thread ... def myView(request): ... def sendData(): time.sleep(10) pusher_client = pusher.Pusher( keys='values', ) pusher_client.trigger('my-channel', 'my-event', {'message': 'Test'}) th = Thread(target=sendData) th.daemon = True th.start() ... return render('My.html', {'keys': 'values'}) After creating another thread for the function, The function itself would be executed, However, Data could not be transmitted from Javascript... What could … -
Django serializer rest framework create nested data
Hello I have the following structure for my users: [ { "id": 3, "phone": "XXXXXX", "birth_date": "2017-06-29", "user": { "id": 1, "username": "xxxxx", "first_name": "XXXXX", "last_name": "XXXX", "email": "xxxxxxx@gmail.com", "last_login": "2017-06-29T15:16:11.438818Z", "date_joined": "2017-06-23T16:48:38Z", "is_active": true } } ] I want to be able to create new users and profiles for them, so I would need to create the user and then add it to its profile, my serializer is as follows: serializers.py class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username','first_name','last_name','email','last_login','date_joined','is_active') read_only_fields = ('last_login','date_joined') class ProfileSerializer(serializers.ModelSerializer): user = UserSerializer() class Meta: model = Profile fields = ('id','phone','birth_date','user') def update(self, instance, validated_data): profile_id = instance.id if profile_id != None: user = validated_data.get('user') phone = validated_data.get('phone') birth_date = validated_data.get('birth_date') if user != None: username = user.get('username') first_name = user.get('first_name') last_name = user.get('last_name') email = user.get('email') is_active = user.get('is_active') if username != None: instance.user.username = username if first_name != None: instance.user.first_name = first_name if last_name != None: instance.user.last_name = last_name if email != None: instance.user.email = email if is_active != None: instance.user.is_active = is_active if phone != None: instance.phone = phone if birth_date != None: instance.birth_date = birth_date instance.save() return instance def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create(**user_data) validated_data.user_id = …