Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeErrorat /blog/21- detail() got an unexpected keyword argument 'blog_id'
I'm making a tool for my project. My final object is this:When I type a title, body in new.html page, it works through create.html and finally, gets all of information from new.html in detail.html page. I created two apps, each good(writing works) and account(sign in works). But I faced with "detail() got an unexpected keyword argument 'blog_id'" problem and can't find any solutions. I run this in Visual studio code and I'm now trying to insert def detail(request): details = get_object(Good, pk= blog_id) return redner(request, 'detail.html', {'details':details}) what I have to do after this if it's right? home.html {% extends 'base.html' %} {% block contents %} <body> </body> {% endblock %} urls.py from django.contrib import admin from django.urls import path import good.views import account.views urlpatterns = [ path('admin/', admin.site.urls), path('', good.views.home, name="home"), path('login/', account.views.login, name="login"), path('signup/', account.views.signup, name="signup"), path('new/', good.views.new, name="new"), path('create/', good.views.create, name="create"), path('blog/<int:blog_id>', good.views.detail, name="detail"), ] models.py from django.db import models class Good(models.Model): title = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') body = models.TextField() def __str__(self): return self.title admin.py from django.contrib import admin from .models import Good admin.site.register(Good) views.py from django.shortcuts import render, get_object_or_404, redirect from .models import Good from django.utils import timezone def home(request): return render(request,'home.html') def new(request): … -
Form doesn't save but returns 200
I want to create an object of item and save it to the database through a form i wrote. Right now I'm able to update it from my form also admin panel works i can create item from there. However, create form not saving. When i click the button, it refreshes the page, returns 200 in terminal but doesn't save it. I'm putting every part of it, i checked a lot but not seeing any error. This is my model. class Item(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, null=True, related_name='items') name = models.CharField(max_length=50) description = models.TextField(max_length=250) price = models.FloatField() picture = models.ImageField(upload_to='item_pictures') is_available = models.BooleanField(default=True) created_at = models.DateField(auto_now_add=True) updated_at = models.DateField(auto_now=True) category = models.ForeignKey(Category, on_delete=models.DO_NOTHING, related_name='category') slug = models.SlugField(unique=True, null=True, blank=True) def save(self, *args, **kwargs): self.slug = slugify(self.name) return super(Item, self).save(*args, **kwargs) def __str__(self): return self.name My url path('item/create/', ItemCreateView.as_view(), name='item-create'), My view class ItemCreateView(LoginRequiredMixin, CreateView): model = Item fields = ['name', 'description', 'price', 'picture', 'is_available', 'category', 'slug' ] template_name = 'item/item_update.html' success_url = '/' Success url return home page, but form only refreshes And form class ItemCreateForm(forms.ModelForm): class Meta: model = Item fields = ['name', 'description', 'price', 'picture', 'is_available', 'category', 'slug'] Lastly template just in case {% extends "base.html" %} {% … -
How to override PasswordResetConfirmView? (django.contrib.auth.views)
I tried: class CustomPasswordResetConfirmView(PasswordResetConfirmView): form_class = CustomSetPasswordForm but it raises TypeError:__init__() takes 1 positional argument but 2 were given -
How to address to app url in django URL field?
I want to make a dynamic toolbar for a website, this toolbar can have custom websites urls and also should have links to same website's apps. for example there is a search app in django project. website url is not fixed, so like how django uses urls names in HTML file (like : {% url 'name' %}), I want to use same name in model field to access to the apps. This is my toolbar menu object class main_menu_item(models.Model): name = models.CharField(max_length=10,default=None) url = models.URLField(default=None) text_color = models.CharField(max_length=7,default=None) background_color = models.CharField(max_length=7,default=None) def first_letter(self): return self.name[0].upper() -
How can I redirect to use the new context not the origin context with django?
I use a decorator to check whether the user is logged in, and redirect to the login page and remind the user. I want to use context parametric rendering template. How can I write the code? def check_login(func): def wrapper(request, *args, **kwargs): if request.session.get("unique_id"): return func(request, *args, **kwargs) else: context = {'title': 'login', 'not_login': 1} return redirect(reverse('login'), context=context) return wrapper # view.py def login(request): context = {'title': 'login', 'not_login': 0} return render(request, 'login.html', context) The code like this. If user get the login page, templates use not_login=0, if the request is from redirect, templates use not_login=1. -
Cannot apply makemigrations to model after modifying
I implemented a model for my Django app in models.py. Everything worked fine. Then I tried adding a new property to the class. If I now run "makemigrations" I get the error "table movieapp_movie_class has no column named show_movie". I thought that running makemigrations was the command to add this column to the table. I've tried deleting db.sqlite3 and the migration-folder in the app-folder which did not work. from django.db import models # Create your models here. class movie_class(models.Model): show_movie = models.CharField(max_length=100) # this is the new property I wanted to add movie_id = models.CharField(max_length=100) title = models.CharField(max_length=100) rating = models.CharField(max_length=100) poster = models.CharField(max_length=100) -
Django Rest Framework - issue with DELETE - CSRF not found
I'm using Django Rest Framework with CSRF. POST and PUT methods work as expected, but DELETE is giving error 403 with - following message "{"detail":"CSRF Failed: CSRF token missing or incorrect."}. It appears that frontend application (Angular) is doing a proper POST and PUT requests. I'm not getting any issues with CSRF nor CORS. Example: DELETE Request: Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9,pl;q=0.8 Cache-Control: no-cache Connection: keep-alive Cookie: _ga=GA1.1.1418236812.1564012825; _gid=GA1.1.747517255.1564126213; sessionid=zho7t6c8vbot46uuwka8ufh53pkanein; _gat_gtag_UA_127399308_1=1; X-XSRF-TOKEN=hapGqQ09lXlVX7MORRsTfvkEkE79AddcSGI84RdYJEqqjFDF4wXsK4jdKPYpQzIp Host: 127.0.0.1:4200 http-x-csrftoken: hapGqQ09lXlVX7MORRsTfvkEkE79AddcSGI84RdYJEqqjFDF4wXsK4jdKPYpQzIp Origin: http://127.0.0.1:4200 Pragma: no-cache Referer: http://127.0.0.1:4200/cost_center/form/e503dbfd-8eae-49e4-becc-4aa60016b996 User-Agent: Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/75.0.3770.142 Safari/537.36 x-csrftoken: hapGqQ09lXlVX7MORRsTfvkEkE79AddcSGI84RdYJEqqjFDF4wXsK4jdKPYpQzIp DELETE Response headers: HTTP/1.1 403 Forbidden X-Powered-By: Express access-control-allow-origin: http://127.0.0.1:4200 date: Sun, 28 Jul 2019 14:36:12 GMT server: WSGIServer/0.2 CPython/3.7.3 content-type: application/json vary: Accept, Origin, Cookie allow: GET, PUT, DELETE, HEAD, OPTIONS x-frame-options: SAMEORIGIN content-length: 58 access-control-allow-credentials: true connection: keep-alive DELETE Response: Request URL: http://127.0.0.1:4200/api/cost_center/e503dbfd-8eae-49e4-becc-4aa60016b996 Request Method: DELETE Status Code: **403 Forbidden** Remote Address: 127.0.0.1:4200 {"detail":"CSRF Failed: CSRF token missing or incorrect."} Then, when I do for example "PUT" request, it is executed without any issue: PUT Request: Accept: application/json, text/plain, */* Accept-Encoding: gzip, deflate, br Accept-Language: en-US,en;q=0.9,pl;q=0.8 Cache-Control: no-cache Connection: keep-alive Content-Length: 82 Content-Type: application/json Cookie: _ga=GA1.1.1418236812.1564012825; … -
Aggregation of a related object does not output as expected
I have a related model to this one : class Node(MPTTModel): parent = TreeForeignKey('self', on_delete=models.CASCADE, blank=True, null=True, related_name='children') name = models.TextField(blank=True, null=True) Which is this one : class Views(models.Model): related_tree = models.ForeignKey(Node, on_delete=models.CASCADE, blank=True, null=True, related_name='related_views') views_count = models.PositiveIntegerField(null=True, blank=True, default=0) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.related_tree.name What i want to do is to filter the Node objects with a search keywords that the user will type, and within the result i want to show the number of the visits for each objects so this is the view that i have written so far, if search_text_imported != '': filter = Q() cases = {} get_result_list = [x for x in search_text_imported.split() if x != ''] for i, keyword in enumerate(get_result_list): filter |= Q(name__icontains=keyword) filter |= Q(Tags__icontains=keyword) cases['keyword_match_{}'.format(i)] = Case( When(name__icontains=keyword, then=1), default=Value(0), output_field=models.IntegerField(), ) result = Node.objects.filter( filter, tree_type='root', published=True ).annotate( **cases ).annotate( total_views=Sum('related_views__views_count'), num_bookmarks=Count('bookmarked_by'), keywords_matched=reduce(add, (F(name) for name in cases)) ).order_by('-keywords_matched', '-num_bookmarks').annotate( ) context = { 'tree_result': result } Within the template this what i have {% if tree_result %} {% for tree in tree_result|slice:":14" %} {{ tree.total_views }} {% endfor %} {% endif %} Everything seems to work perfectly except one thing is in … -
Invalid interpolation format for "environment" option in service "web": "SECRET_KEY=
I am working on online book store project. I am trying to setup environment variables in dockercompose.yml project_folder/settings.py SECRET_KEY = os.environ.get('SECRET_KEY') The code inside dockercompose.yml file version: '3.7' services: web: build: . command: python /code/manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - 8000:8000 depends_on: - db environment: - SECRET_KEY=my_secret_key - DEBUG=1 db: image: postgres:11 volumes: - postgres_data:/var/lib/postgresql/data/ volumes: postgres_data: I am getting the following error when I ran the command $docker-compose down ERROR: Invalid interpolation format for "environment" option in service "web": "SECRET_KEY=my_secret_key" -
Django: How to follow ForeignKey in unique_together constraint?
I have three Django Models: a Property Model, most importantly having a slug field; a Collection Model; and a PropertyCollectionRelationship Model. The last model models a ManyToMany relationship between the other two and is used as an explicit through of a ManyToManyField. from django.db import models class Property(models.Model): slug = models.SlugField() collections = models.ManyToManyField('Collection', blank=True, through='PropertyCollectionRelationship') # ... other unimportant stuff omitted ... class Collection(models.Model): pass # ... lots of stuff omitted ... class PropertyCollectionRelationship(models.Model): prop = models.ForeignKey(Property, on_delete=models.CASCADE) coll = models.ForeignKey(Collection, on_delete=models.CASCADE) I would like to add a uniqueness constraint which ensures that each collection has at most one property with any given slug. I tried to express this via a unique_together option in the Model Meta: class PropertyCollectionRelationship(models.Model): class Meta: unique_together = [['coll', 'prop__slug']] prop = models.ForeignKey(Property, on_delete=models.CASCADE) coll = models.ForeignKey(Collection, on_delete=models.CASCADE) This resulted in the following System Check Error: SystemCheckError: System check identified some issues: ERRORS: myapp.PropertyCollectionRelationship: (models.E012) 'unique_together' refers to the nonexistent field 'prop__slug'. How, if at all, can I achieve such a constraint? -
How do I query the database for all the points that are within a certain radius from a users location?
I am trying to get all the points from the database that are with a certain radius from the users location(e.g 10km). So basically I would like the user to input a location, which would then be converted to lat and lng using the google maps api and have the application search for and return all the stores in the database that are within a 10 km radius of the users location. I have tried Haversines formula but can't seem to get that to work since I do not have a strong understanding of how to filter search results from the database. Could anyone please explain to me how best to query the database for results within a 10km radius using Haversines formula? models.py: class Detail(models.Model): name = models.CharField(max_length=30, blank=True) location = models.CharField(max_length=300, blank=True) lat = models. DecimalField(max_digits=9, decimal_places=6) lng = models.DecimalField(max_digits=9, decimal_places=6) views.py: def feed(request): latitude = request.session['lat'] longitude = request.session['lng'] radius = 20000 unit = 6371 # Distance unit (kms) radius = float(radius) / 1000.0 # Distance radius convert m to km lat = float(latitude) # Central point latitude lng = float(longitude) # Central point longitude print(lat,lng,radius) limit = 1000 My views .py is returning to lng and … -
model() missing 1 required positional argument: 'request'
Error: model() missing 1 required positional argument: 'request' I want to do abstract api for all models in my app urls.py urlpatterns = [ path('api/object/', views.GeneralViewSet.as_view({'get': 'list'})) ] views.py class GeneralViewSet(viewsets.ModelViewSet): @property def model(self, request): return apps.get_model(app_label=self.request.data.get('app'), model_name=self.request.data.get('object')) def get_queryset(self, request): return self.model.objects.all() def get_serializer_class(self, request): GeneralSerializer.Meta.model = self.model return GeneralSerializer def post(self, request): queryset = self.model.objects.all() serializer = self.get_serializer(queryset, many=True) return Response(serializer.data) I expect the list of my data of models for example for post api of { "app": "leads", "object": "Lead" } expect all data from Lead object -
How to display image from temp folder to template in Django
I have just started working on django(But I have worked on python for about a year). For my MFA application, I have created .png file(qr code) in my admin.py file and I have stored this png in /tmp/ dir. Now I need to show this image to template. The reason I have stored this file in temp dir becouse the image created is one time. SO I want to show this image view for once and delete after that. So anyone can help me to get me out from this? Thanks for advance qr_url = "otpauth://totp/%s:%s?secret=%s&issuer=%s" % (label, user, secret, label) url = pyqrcode.create(qr_url) random_file_path = datetime.datetime.now().strftime("%Y%m%d%H%M%S") url.png('/tmp/'+str(random_file_path)+'.png', scale=4)` This is how I created png I have tried by directly providing temp dir path. Also If I have to store the file in static then please help me for storing and deleting file in static folder`` -
What is exactly Meta in Django
i want know simply what is Meta class in django and what they do from django.db import models Class Author(models.Model): first_name=models.CharField(max_length=20) last_name=models.CharField(max_length=20) class Meta: ordering=['last_name','first_name'] -
How to style certain tags when condition is met after extending 'base.html'?
I'd like to change the style of all 'select' in my DetailView, but only when certain condition is met (like {% if object.sth == 'sth' %} ). This html is extended from 'base.html' where I already have my css linked, and all 'select' styled. What would be the best approach? It seems I can not link new stylesheet while I'am already in (after extending base.html) -
Django rest fetch data from bridge model
I want to get all the user details and list of all the roles against the user details model My Models class UserDetail(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='userdetail_user', default='111') cn = models.CharField(max_length=200) sn = models.CharField(max_length=200) u_id = models.CharField(max_length=200) display_name_cn = models.CharField(max_length=200) display_name_en = models.CharField(max_length=200) given_name = models.CharField(max_length=200) employee_number = models.CharField(max_length=200) email = models.CharField(max_length=200) created_at = models.DateTimeField(default=datetime.now, blank=True) last_login = models.DateTimeField(default=datetime.now, blank=True) def __str__(self): return self.given_name class Role(models.Model): title = models.CharField(max_length=20) description = models.CharField(max_length=200) created_at = models.DateTimeField(default=datetime.now, blank=True) last_updated = models.DateTimeField(default=datetime.now, blank=True) status = models.BooleanField(default=True) def __str__(self): return self.title class UserRole(models.Model): userdetail = models.ForeignKey(UserDetail, on_delete=models.CASCADE, related_name='userrole_userdetail') role = models.ForeignKey(Role, on_delete=models.CASCADE) approver = models.ForeignKey(UserDetail, on_delete=models.SET_NULL, null=True, related_name='userrole_userdetail_approver') created_at = models.DateTimeField(default=datetime.now, blank=True) last_updated = models.DateTimeField(default=datetime.now, blank=True) status = models.BooleanField(default=True) My Serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'email') class UserRoleSerializer(serializers.ModelSerializer): class Meta: model = UserRole fields = ('id', 'userdetail', 'role', 'approver', 'last_updated', 'status') depth = 1 def to_representation(self, instance): representation = super(UserRoleSerializer, self).to_representation(instance) representation['userdetail'] = UserDetailSerializer(instance.userdetail).data representation['role'] = RoleSerializer(instance.role).data representation['approver'] = UserDetailSerializer(instance.approver).data return representation class RoleSerializer(serializers.ModelSerializer): class Meta: model = Role fields = ('id', 'title', 'description', 'last_updated', 'status') class UserDetailSerializer(serializers.ModelSerializer): user = UserSerializer() roles = serializers.SerializerMethodField(read_only=True) class Meta: model = UserDetail fields = ('id', 'roles', 'user', 'cn', 'sn', … -
Deploying my Django website to Heroku with DEBUG=False doesn't work
When deploying django onto either localhost or heroku with DEBUG=False, it throws an error saying C:\Users\krish\Envs\PRREMIA\lib\site-packages\whitenoise\base.py:105: UserWarning: No directory at: c:\Users\krish\Documents\python\PRREMIA\staticfiles\ warnings.warn(u'No directory at: {}'.format(root)) [28/Jul/2019 16:05:43] "GET / HTTP/1.1" 500 27 When DEBUG=True, it works fine. Why? And how do I stop and fix this? -
Use of `get` for a `select_for_update` query in order to reduce the number of rows getting locked
I would like to know if there is a good solution for this scenario. When a select_for_update is used in a query set, all matching results are locked until the particular block of code has not finished execution. This has become a little critical as simultaneous requests which could be served are being returned back by DatabaseErrors. Below is a sample query for which select_for_update has been implemented qs = Coupons.objects.select_for_update().filter(brand=brand).values('coupon').order_by('id') return qs[0] If we have 1000 coupons for a particular brand, then the entire 1000 rows are locked. I am unable to use get since we are returning the coupons on a FIFO basis and we would need to return coupons which were added first Is there any way I could use get, or minimize the number of rows being locked -
Aggregate related integer-field values in Django template
I have this model which is related to a Node model, class Views(models.Model): related_tree = models.ForeignKey(Node, on_delete=models.CASCADE, blank=True, null=True, related_name='related_views') views_count = models.PositiveIntegerField(null=True, blank=True, default=0) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.related_tree.name In the template when i query a list of the Node's objects i want to aggregate the value of the 'views_count' of each object. I have tried this in my template {% for tree in tree_result|slice:":14" %} {% for view in tree.related_views.all %} {{ view.views_count }} {% endfor %} {% endfor %} i have all the related count_view of the current tree but what i want to do is to aggregate the value of the related field and show it within the for loop of tree_result. Any suggestions please ? -
Django Blog Page not found (404) - No Post matches the given query
I'm coding a blog with Django,There was an error 404 when I click on address http://localhost:8000/blog/2019/7/28/prim-algorithm-path No Post matches the given query. Raised by: blog.views.blog_detail views.py def blog_detail(request,year,month,day,post): print(year,month,day,post) post = get_object_or_404(Post, slug=post, publish__year=year, publish__month=month,publish__day=day) return render(request,'post.html',locals()) blog/urls.py from django.urls import path from .views import index,blog_detail app_name = 'blog' urlpatterns = [ path('', index, name='index'), path('<int:year>/<int:month>/<int:day>/<slug:post>',blog_detail,name='post_detail'), ] mysite/urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('blog/',include('blog.urls',namespace='blog')), ] what should I do -
Python dateparser fails when timezone is in middle
I'm trying to parse a date string using the following code: from dateutil.parser import parse datestring = 'Thu Jul 25 15:13:16 GMT+06:00 2019' d = parse(datestring) print (d) The parsed date is: datetime.datetime(2019, 7, 25, 15, 13, 16, tzinfo=tzoffset(None, -21600)) As you can see, instead of adding 6 hours to GMT, it actually subtracted 6 hours. What's wrong I'm doing here? Any help on how can I parse datestring in this format? -
User api request via app online - api server gets user or app IP adress?
I would like to publish an Django app on Vultr hosting. App (on user request) should connect an api on another server and return data to user. Api has requests limits by IP. When user connect api server via my app, api server will get user IP or my app server IP? If API server will get my app server ip my app will be banned after few request. How to avoid ban and send user ip to API server? Thank you for any help! -
How to save MultipleChoiceField to db
I want to create a settings page where a user can select multiple values of skills they have. It will have a main category and then subcategories. I need to save those into my database, so I can query them and show their selected skillset again. I know how to create the MultipleChoiceField but not how to save them to the database. How would I go on about that? Forms.py from django import forms class skills(forms.Form): jobs = [ ('Håndværker', ( ('Gulv', 'Gulv'), ('Væg', 'Væg'), ) ), ('Murer', ( ('Mur', 'Mur'), ('blabla', 'blabla'), ) ), ] job = forms.MultipleChoiceField(widget=forms.CheckboxSelectMultiple, choices=jobs) Views.py from .forms import skills def index(request): if request.method == 'POST': form = skills(request.POST) if form.is_valid(): picked = form.cleaned_data.get('job') # do something with your results else: form = skills return render(request, 'settings/index.html', {"form":form}) It currently looks like this when the page loads which is good. Next step is just how I would save it to the database, so I can display this again with their previous chosen values. -
Error validating Django formset Modelform?
I am learning to implement Django formset using Modelform and I am getting this formset validation errors relating to my datefield. The error that I am getting is formset [{'from_date': ['Enter a valid date.'], 'to_date': ['Enter a valid date.']}] This is what I have tried so far.What could I be doing wrong ? models.py class WorkExperience(models.Model): company = models.ForeignKey(Company,on_delete=models.PROTECT) from_date = models.DateField() to_date = models.DateField() work = models.ForeignKey(Work,on_delete=models.PROTECT) date_last_modified = models.DateTimeField(auto_now=True) date_added = models.DateTimeField(auto_now_add=True) forms.py class WorkExperienceForm(ModelForm): class Meta: model = WorkExperience fields=('from_date','to_date') def __init__(self, *args, **kwargs): super(WorkExperienceForm, self).__init__(*args, **kwargs) self.fields['name']=forms.CharField( label='Company Name', widget=forms.TextInput(attrs={ 'id': 'company_name', 'class': 'form-control', 'required':True }), ) self.fields['street_address'] = forms.CharField( label='Company Address', widget=forms.TextInput(attrs={ 'id': 'company_address', 'class': 'form-control', 'required': True }), ) self.fields['from_date'] = forms.DateField( input_formats=['%y-%m-%d'], widget=forms.DateInput(format='%d %B, %Y',attrs={ 'id':'to_date', 'class':'form-control'}), required=True, ) self.fields['to_date'] = forms.DateField( input_formats=['%y-%m-%d'], widget=forms.DateInput(format='%d %B, %Y',attrs={ 'id':'to_date', 'class':'form-control'}), required=True, ) self.fields['country'] = forms.ChoiceField(choices=Country.objects.all().values_list('id', 'name')) self.fields['country'].widget.attrs.update({'class': 'btn btn-secondary dropdown-toggle','required':True}) self.fields['project_name'] = forms.CharField( label='Project Name', widget=forms.TextInput(attrs={ 'id': 'project_name', 'class': 'form-control', 'required': True }), required=True, ) self.fields['project_details'] = forms.CharField( label='Project Details', widget=forms.Textarea(attrs={ 'id': 'project_details', 'class': 'form-control', 'required': True }), ) from django.forms import modelformset_factory WorkExperienceFormSet = modelformset_factory( WorkExperience, WorkExperienceForm, extra=1, ) views.py def post(self,request,*args,**kwargs): try: print('fromdate',request.POST['form-0-from_date']) formset = WorkExperienceFormSet(request.POST) print('formset',formset.errors) for form in formset: print('form',form.is_valid()) if … -
How to save a model-instance using serializers in django?
I would like to save a class instance in my database using serializers, provided by DRF. Serializer: class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = '__all__' here I try to save an instance: p = Person(Name = "Test") _srlz = PersonSerializer(data = p) The real case is little bit more complicated, but sanse the same. Unfortunately the data - _srlz.data is empty. So if I try to save data via _srlz.save() method then nothing change. Otherwise if I request an existed object p = Person.objects.filter(id = 1) _srlz = PersonSerializer(data = p) Then my _srlz.data will not be empty. How should I save this object if datasource is not JSON-object, but model-class instance?Should I first serialize it and then deserialize again? I already tried to save instance calling a .save() method, provided by model's default Manager, but I would like to separate my model and service methods so all database operations performed by serializers. Or is it OK in this case, because I deal not with pure JSON, but with model instance? But how can I then validate data?