Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to upload a file in django and associate this file with the user who uploaded it
I'm building a site that the user login himself/herself and then, upload a file that will be stored to be used later by the user. My model.py is: class Ontology(models.Model): name = models.TextField(max_length=50) uploaded_at = models.DateTimeField(auto_now_add=True) user = models.ForeignKey(CustomUser, on_delete=models.CASCADE) file = models.FileField(default="", validators=[validate_file_extension]) my forms.py from django import forms from .models import Ontology class UploadOntologyForm(forms.ModelForm): class Meta: model = Ontology fields = ('file',) in views.py I have: from django.shortcuts import render from django.http import HttpResponseRedirect from .forms import UploadOntologyForm from django.views.generic import CreateView from .handle_upload_owl import * def index(request): if request.method == 'POST': form = UploadOntologyForm(request.POST, request.FILES) if form.is_valid(): if not handle_uploaded_file(request.FILES['file']): form.save() return HttpResponseRedirect('/ontology/') else: form = UploadOntologyForm() return render(request, 'index.html', {'form':form}) and latter handle_upload_owl.py def handle_uploaded_file(thisFile): if thisFile._size > 5242880: return False else: with open('media/' + str(thisFile), 'wb+') as destination: for chunk in thisFile.chunks(): destination.write(chunk) return True My app is loading and storing files correctly, but no entries in database is added, not even related to the logged user who uploaded it. I'm newbie with django and I'm not dealing well with this. What's wrong? -
Updating ModelForm Django 1.10
I'm fairly new to coding in general, so please forgive my ignorance. I have a ModelForm (Django 1.10 -just in case-) for a 'post' on a social network website: forms.py: class PostForm(forms.ModelForm): class Meta: model = Post fields = ['text', 'image', 'draft'] To update a post, this is its function: views.py: def edit_post(request, post_id): post = get_object_or_404(Post, pk=post_id) if not request.user.is_superuser and\ not request.user == post.user: raise PermissionDenied if request.method == 'POST': form = PostForm(request.POST, instance=post) if form.is_valid(): post = form.save(commit=False) post.user = request.user post.save() context = {'post': post, 'form': form} return HttpResponse(render(request, 'accounts/view_post.html', context)) elif request.method == 'GET': form = PostForm(request.GET, instance=post) context = {'post': post, 'form': form} return HttpResponse(render(request, 'accounts/edit_post.html', context)) in the template: <form action="" method="post" enctype="multipart/form-data"> {% csrf_token %} {% include 'accounts/form_template.html' %} <input class="btn btn-btn-success" type="submit" value="Save Post"> </form> My question is: when trying to update, why does the original field input not show up? The fields turn up empty as if I were creating a new post. The more detailed answer, the more I would appreciate it. Thank you in advance. -
why am I having unresolved reference in pycharm? django
Currently using Django 1.10 in PyCharm and somehow in the root urls when I try to import something it shows me a red underline in PyCharm saying unresolved reference I checked my folder structure and everything looks fine though and when I run python manage.py runserver server works well too. Does anyone know why PyCharm is giving me such error? my root url, as seen the from student.urls import student_urlpatterns has a red underline error and few others too but I am just using this as an example student url which can be seen that root url is directed to the right place student view as seen that the student url is directed to the right place -
Run Django script on Windows to create models on Linux
I'm running a data crawler on a Windows 7 machine. I'm inserting the results remotely to my Django 1.10 project on my CentOS 7 server. I have a copy of the Django project on both machines. This works fine for all fields in the model, except the ImageField. Here is the part of my script that does the saving. m = Object(strings=strings) m.save() image_content = ContentFile(requests.get(image_url).content, id + '.jpg') m.image_file.save("C:\\Users\\Me\\Documents\\mysite.com\\imgs\\" + id + ".jpg", image_content) m.save() The image field is declared as: image_file = models.ImageField(upload_to='avatars/', null=True, default=None) My settings.py file on the Windows machine has the line: MEDIA_ROOT = "/var/www/mysite.com/myproj/images/" On the first run, there are no errors but the image_feild on the server is set to "." On the second run, the error is: IOError: C:\var\www\mysite.com\myproj\images exists and is not a directory. So this is being created on the Windows machine, but I want the MEDIA_ROOT to be used as the destination directory on the server. -
Two urls with same structure
How to make two urls with same structure make work? I don't want to add any prefix before url I want all views to on example.com/slug Here is my urls: url(r'^(?P<slug>[-_\w]+)', views.CategoryArticlesView.as_view(), name='single_category'), url(r'^(?P<slug>[-_\w]+)', views.SingleArticleView.as_view(), name='single_article'), I can make it easily to work adding prefix before first url like: url(r'^category/(?P[-_\w]+)', views.CategoryArticlesView.as_view(), name='single_category'), but I want it without prefix. Now it matches only first url but not second. -
Postgres: Could not choose a best candidate function
Can someone explain how to fix this query? SELECT date_part('month', scheduler_scheduleevents.date), sum(price) FROM user_settings_userservices JOIN scheduler_scheduleevents ON scheduler_scheduleevents.service_type_id = user_settings_userservices.id WHERE user_settings_userservices.salonid_id = %s AND is_start_time = True and is_active = False AND ( date < %s or ( date = %s and time < %s ) ) AND date_part('year', scheduler_scheduleevents.date) = date_part('year', %s) GROUP BY date_part('month', scheduler_scheduleevents.date), (request.user.id, now_date, now_date, now_time, now_date, ) ) When I try execute this query in django app I get this warning: function date_part(unknown, unknown) is not unique LINE 9: ...ate_part('year', scheduler_scheduleevents.date) = date_part(... ^ HINT: Could not choose a best candidate function. You might need to add explicit type casts. -
Django: How to Handle High Frequent Requests?
I'm building a Django server for data collection. However, the program seems not capable when the sensing network expands. As time goes on, the program doesn't even enter the code piece and report broken pipe/connection reset by peer/too many open files errors: Exception happened during processing of request from ('172.58.139.243', 30713) Traceback (most recent call last): File "/usr/lib/python2.7/SocketServer.py", line 593, in process_request_thread File "/usr/lib/python2.7/SocketServer.py", line 334, in finish_request File "/usr/lib/python2.7/dist-packages/django/core/servers/basehttp.py", line 126, in __init__ File "/usr/lib/python2.7/SocketServer.py", line 651, in __init__ File "/usr/lib/python2.7/SocketServer.py", line 710, in finish File "/usr/lib/python2.7/socket.py", line 279, in close File "/usr/lib/python2.7/socket.py", line 303, in flush error: [Errno 32] Broken pipe [08/Dec/2016 17:46:47] "POST /Update_Data/ HTTP/1.1" 500 39484 Traceback (most recent call last): File "/usr/lib/python2.7/wsgiref/handlers.py", line 86, in run File "/usr/lib/python2.7/wsgiref/handlers.py", line 128, in finish_response File "/usr/lib/python2.7/wsgiref/handlers.py", line 217, in write File "/usr/lib/python2.7/socket.py", line 324, in write File "/usr/lib/python2.7/socket.py", line 303, in flush error: [Errno 104] Connection reset by peer File "/usr/lib/python2.7/random.py", line 810, in random OSError: [Errno 24] Too many open files I checked the open files and it seems like the socket files are never closed. The list is full of items like the followings: python 30404 30522 ubuntu 732u IPv4 2437194784 0t0 TCP 192.168.100.2:9003->172.58.137.113:18538 (ESTABLISHED) … -
Could not cast value of type '__NSCFNumber' (0x10e59f3c0) to 'NSString' (0x10dba7ad8) swift 3
I've been tying to figure out this one for a few days now... Here is my original code: if let ratingDic = dictionary["rating"] as? [String: Any], let ratingId = ratingDic["id"] { searchResult.ratingID = ratingId as! String } Here is my api: "amount" = "50.00"; "rating" = { "name" = "Platinum"; "id" = 5 I'm pretty sure I need to use "valueForKey" so here is my updated code: if let ratingDic = dictionary["rating"] as? [String: Any], //let ratingId = ratingDic["id"] { let ratingId = [ratingDic.valueForKey("id")!] { searchResult.ratingID = ratingId as! Number } However now I receive the "Value for type String:Any has no member "valueForKey" -
Getting different model name when running as a script and as a django app
I have a django project, structure is like: test-project -> my_app1 -> module1 -> models.py models.py class MyModel(models.Model): # some attriubutes INSTALLED_APPS has 'my_app1' added. Running migrate command its creating table with the table name as: my_app1_mymodel While running project using python manage.py runserver its able to find the table. Also, I have a script in the same project like: test-project -> my_app2 -> module2 -> script.py 'my_app2' is also added in INSTALLED_APPS script.py is trying to import and query 'Mymodel' like: from my_app1.module1.models import MyModel which I am running as python -m myapp2.module2.script The problem is now its throwing error (django.db.utils.OperationalError: no such table:) as it is trying to look the table with table name: module2_mymodel instead of my_app1_mymodel I read about the table naming convention in django and understands that its uses app_name as the prefix. But my question is: Why it's fetching different app_name in 2 cases? PS: I tried using and it worked: class Meta: db_table = my_app1_mymodel but that's not my objective, I want to know what I am doing wrong here. -
AWS S3 Base64 File Upload Not Working From iPad or Android, but Is Working From a Laptop Safari or Chrome
I have an ionic/angular js web app that uploads a file to django rest framework via base64 encoding. The file then gets saved to an AWS S3 bucket with the help of the django-storages(1.5.1) library. Accessing the webapp on Chrome (Windows) or Safari (Macbook) and uploading images and files works great. Accessing the webapp on Chrome (Android Phone) or Safari (iPad), fails with an error of: XMLHttpRequest cannot load [api url]. Origin [webapp url] is not allowed by Access-Control-Allow-Orign. Clearly, it's a CORS issue, right? But I can upload form input data just fine... it's the file upload (base64 content in a JSON Restful PUT) that seems to be the difference throwing the error. For completeness, my AWS S3 CORS configuration is: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <AllowedMethod>PUT</AllowedMethod> <AllowedMethod>POST</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>Authorization</AllowedHeader> </CORSRule> Any thoughts or nudges in a direction that might be the problem? -
How I can display one field as string from serializer?
I use rest framework, I have field in user emloyee.company which is has field name. I need display only name string, but I have dict. class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = ('name',) class UserSerializer(MySerializer): company = CompanySerializer(source='employee.company') class Meta: fields = (..., 'company') I've got: {...,"company":{"name":"My company"}} I need: {...,"company":"My company"} Thanks for any help. -
Can't access instancemethod attribute?
Is it possible to somehow access variable or attribute of a method? In Django (but problem isn't probably sticked to Django): class Product(models.Model): ... STATISTIC = ['get_last_average_price',] def statistic(self): """ returns a list of methods with names in list STATISTIC """ lst = [] for method_str in Product.STATISTIC: method = getattr(self, method_str) lst.append(method) return lst def get_last_average_price(self): self.get_last_average_price.label = 'Last AVG price' self.get_last_average_price.xml_tag = '<last_average_price>' self.get_last_average_price.xml_close_tag = '</last_average_price>' prices = [x.get_last_scan().price for x in self.get_occurences() if x.get_last_scan() and x.get_last_scan().price] return round(decimal.Decimal(sum(prices)/len(prices)),2) if prices else None Now I want to generate an XML where this (iteration where method is get_last_average_price: {{ method.xml_tag }}{{ method }}{{ method.xml_close_tag }} should produce: <last_average_price>1548.48</last_average_price> The price ( {{ method }} ) works correctly. The problem is with tags. It returns error: Exception Value: 'instancemethod' object has no attribute 'label' <products> {% for product in products %} <product> <code>{{ product.code }}</code> <name>{{ product.name }}</name> <statistics> {% for method in product.statistic %} {{ method.xml_tag }}{{ method }}{{ method.xml_close_tag }} {% endfor %} </statistics> </product> {% endfor %} </products> Do you know what to do to make it work? Or some workaround? -
How to make django all urls be to level slug?
How to make django all urls to be top level slug? Top level slug I mean that all urls has unique slug example: example.com/articles example.com/article-1 example.com/article-2 example.com/article-3 example.com/reviews example.com/reviews-1 example.com/reviews-2 but not: example.com/articles/article-1 example.com/articles/article-2 example.com/articles/article-3 example.com/reviews/reviews-1 example.com/reviews/reviews-2 I have a lot of apps like articles, reviews, and other custom pages. So, what you think about this aproach that I create app with model like this: class Link(models.Model): slug = models.SlugField(unique=True) and then I will use it in my articles model like this: from links.models import Link class Article(models.Model): title = models.CharField() slug = models.OneToOneField( Link, on_delete=models.CASCADE, primary_key=True, ) body = models.TextField() . from links.models import Link class Review(models.Model): title = models.CharField() slug = models.OneToOneField( Link, on_delete=models.CASCADE, primary_key=True, ) review = models.TextField() and then I will have only one url field in my mane urls.py file: url(r'^(?P<slug>[-_\w]+)', views.link, name='link'), And now how I should filter data where I want to return article or review? Like this or maybe there exists better solution? from django.http import HttpResponseRedirect from .models import Link from articles.models import Article from review.models import Review def link(request, link): link = Link.objects.get(link=link) if Article.objects.filter(slug=Link).exists(): link = link.slug return HttpResponseRedirect(link) if Review.objects.filter(slug=Link).exists(): link = link.slug return HttpResponseRedirect(link) return HttpResponseRedirect('/') -
Django - two form tags on single page with same action attribute
Ok, so I'm trying to make two form tags in single page separated by two different tabs within the page. I'm just wondering how I can process this. I know if I use different action urls I can process them fine easily. But when there's a validation error, it goes to the url that form is being submitted to and I don't want that. I want it to stay inside the page which is why I'm making action=''. In HTML <!-----------template.html-----------> <div class=" tab"> <!-- Nav tabs --> <div class="card"> <ul class="nav navbar-nav nav-tabs" role="tablist"> <li role="presentation" class="active"><a href="#home" aria-controls="home" role="tab" data-toggle="tab">Info 1</a></li> <li role="presentation"><a href="#groups" aria-controls="groups" role="tab" data-toggle="tab">Info 2</a></li> </ul> </div> </div> <div class="tab-content"> <!--Personal Info --> <div class="row tab-pane active" role="tabpanel" id="home"> <!-- edit form column --> <div class="info1"> {% include template1 %} </div> </div> <div role="tabpanel" class="tab-pane" id="groups"> <div class="info2"> {% include template2 %} </div> </div> </div> <!-----------template1-----------> <form method='post' action='' class="form-horizontal" role="form"> {%csrf_token%} <input value=something> <input type="submit" value="Save Changes" name="{{formA.prefix}}"> </form> <!-----------template2-----------> <form method='post' action='' class="form-horizontal" role="form"> {%csrf_token%} <input value=something> <input type="submit" value="Save Changes" name="{{formA.prefix}}"> </form> Here are the codes for an attempt at resolving this: VIEWS.PY def _get_form(request, form_class, prefix): data = request.POST if prefix … -
Django db session vars not being written to db
I'm writing a website for enrollment at a school, and I'm trying to get session variables to work. It only needs to remember the username of the currently logged in user, but the when I attempt to use request.session['username'] = 'some_username', it doesn't push the data to the database. I'm using a postgres sql database for the backend, and looking at the database shows there is a table called 'django_session'. Examining the data in between setting the request.session username reveals there is no change. However, there is an entry from about a month ago. When I attempted to clear this entry with python manage.py clearsessions -v 3, there is no response (which I can only assume means it thinks it connected to the database successfully). If I had to guess, it doesn't know which table to try to connect to for sessions, though I don't know where I would specify that. Any ideas? -
Cannot get model objects
My models.py : class Departement(models.Model): departNumber = models.PositiveSmallIntegerField(default=0, primary_key= True) departName = models.CharField(max_length=100) def __unicode__(self): return self.departNumber My admin.py: class DepartementAdmin(admin.ModelAdmin): list_display = ('departNumber', 'departName') admin.site.register(Departement, DepartementAdmin) The problem is, I cannot get any "Departement" object. I have tried .get(), .filter() or .all(). In both cases, it returns: <Departement: Departement object> What am I doing wrong ?? -
Wagtail Elasticsearch Highlighting
I've implemented a search input on my Wagtail site. It perfectly finds the entries matching my query. Model: class BasePage(Page): ... body = StreamField(...) search_fields = Page.search_fields + [ index.SearchField('body') ] View: if search_query: search_results = Page.objects.live().search(search_query) Query.get(search_query).add_hit() Template: {% for result in search_results %} <li> <h2><a href="{% pageurl result %}">{{ result }}</a></h2> {% if result.search_description %} {{ result.search_description|safe }} {% endif %} </li> {% endfor %} I don't know how to show a small preview of the matched text. I think that's what Elasticsearch highliting is for, but I can't find the way to implemented it using Wagtail. -
Django app not sending a response to my iOS client using Alamofire?
I want to post data to my database via my iOS app. However, when I run the app, I look over to Terminal and see if Django returned any response but nothing happens. I'm using the Alamofire framework. iOS Client: override func viewDidLoad() { super.viewDidLoad() main() } func main() { let BASE_URL = "http://127.0.0.1/session/1" let params = ["comment": "Hello World!", "sender": "RG"] Alamofire.request(BASE_URL, method: .post, parameters: params) } Django Server side (inside views.py): def CommentSection(request, session_id): sesh = Session.objects.get(pk=session_id) if "comment" in request.POST and "sender" in request.POST: comment_post = Comments(session=sesh, user=request.POST["sender"], text=request.POST["comment"]) comment_post.save() return HttpResponse("Returned") -
NoReverseMatch at /sitemap.xml Django with StaticViewSitemap from app.urls
I would like to show urls in my sitemap.xml file from my website.urls file From this url file I have no trouble to show terms privacy and other url from django.conf.urls import include, url from django.contrib import admin from django.contrib.staticfiles import views from django.contrib.staticfiles.urls import staticfiles_urlpatterns from django.conf import settings from django.conf.urls import * # NOQA from django.conf.urls.i18n import i18n_patterns from django.contrib.sitemaps.views import sitemap from .sitemaps import StaticViewSitemap from . import views sitemaps = { 'static': StaticViewSitemap, } urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^', include('website.urls')), url(r'^terms/$', views.terms, name='terms'), url(r'^privacy/$', views.privacy, name='privacy'), url(r'^cdg/$', views.cdg, name='cdg'), url(r'^about/$', views.about, name='about'), url(r'^icon/$', views.icon, name='icon'), url(r'^sitemap\.xml$', sitemap, {'sitemaps': sitemaps}, name='django.contrib.sitemaps.views.sitemap') ] # This is only needed when using runserver. if settings.DEBUG: urlpatterns = patterns('', url(r'^media/(?P<path>.*)$', 'django.views.static.serve', # NOQA {'document_root': settings.MEDIA_ROOT, 'show_indexes': True}), ) + staticfiles_urlpatterns() + urlpatterns # NOQA But when I want to get views from another url file (it's a app's url file locate inside a subfolder ) i have got an error. here is my sitemap.py file from django.contrib import sitemaps from django.core.urlresolvers import reverse class StaticViewSitemap(sitemaps.Sitemap): priority= 0.5 changefreq ='daily' def items(self): return ['terms','privacy', 'about', 'cdg','support'] def location(self, item): return reverse(item) here is website.url py file from django.conf.urls import patterns, url … -
Allow Users to Sell Products on Django Site
I'm looking to make a website where users can upload digital items and sell them for a profit. Is there any kind of plugin where users can set up a shop(similar to Etsy), and link bank info(Account Number/Routing Number) for direct deposits? I am already using Stripe to charge for a subscription service, so maybe incorporating that could be an option? Anything would really help. Thanks -
Editing django views methods at runtime and saving it
In my django views.py file I have several methods that are used. However say I want to change method "foo" so that its now the same as method "bar", but I want this change to be permanent, for the actual views.py file to reflect these changes, not like how in monkey patching where a sys restart would revert them. How would I go about this? I dont really care what scripting language it comes in, but all I want to be able to do is have the views file updated to reflect this change, at runtime -
Error during syncing database in django: TypeError: Required argument 'database' (pos 1) not found
I have been trying to create a database using TypeError: Required argument 'database' (pos 1) not found I am not getting where I have gone wrong. This is my settings.py file. I had written models in one of the applications and even tried commenting out everything but still no solution # Django settings for trust project. import os SETTINGS_DIR = os.path.dirname(__file__) PROJECT_PATH = SETTINGS_DIR PROJECT_PATH = os.path.abspath(PROJECT_PATH) TEMPLATE_PATH = os.path.join(PROJECT_PATH, 'templates') STATIC_PATH = os.path.join(PROJECT_PATH,'static') print STATIC_PATH DATABASE_PATH = os.path.join(PROJECT_PATH, 'trust.db') DEBUG = True TEMPLATE_DEBUG = DEBUG ADMINS = ( # ('Your Name', 'your_email@example.com'), ) MANAGERS = ADMINS DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': DATABASE_PATH, } } # Hosts/domain names that are valid for this site; required if DEBUG is False # See https://docs.djangoproject.com/en/1.5/ref/settings/#allowed-hosts ALLOWED_HOSTS = [] # Local time zone for this installation. Choices can be found here: # http://en.wikipedia.org/wiki/List_of_tz_zones_by_name # although not all choices may be available on all operating systems. # In a Windows environment this must be set to your system time zone. TIME_ZONE = 'America/Chicago' # Language code for this installation. All choices can be found here: # http://www.i18nguy.com/unicode/language-identifiers.html LANGUAGE_CODE = 'en-us' SITE_ID = 1 # If you set this to False, Django will … -
Django - is it possible to work with model methods in a for loop?
I'm working on a Web Application in Django which works with products, prices and statistics etc. To keep it simple - I have a model Product. Product has multiple attributes and methods. Some of those methods returns "statistics" data. class Product(models.Model): name = ... ... def save(... ... def get_all_colors(self): .... def get_historical_average_price(self): #statistic method price = <some calculation> return price def get_historical_minimal_price(self): #statistic method ... return price So there is a lot of methods like get_historical_average_price and get_historical_minimal_price. Now I have to write labels and call these methods one by one in the project. For example when I generate a table or creating an XML export. I would like to be able to somehow "mark" them that those are "statistic" methods, give them some name so I would be able to work with them using for loops etc. Is there some way to do that? Example on XML generator: <products> {% for product in products %} <product> <code>{{ product.code }}</code> <name>{{ product.name }}</name> <statistics> <historical_average>{{ product.get_historical_average_price}}</historical_average> <minimal_price>{{ product.get_historical_minimal_price}}</minimal_price> </statistics> </product> {% endfor %} </products> So I would do something like: <statistics> {% for statistic_method in product.statistics %} <{{ statistic_method.name }}>{{ statistic_method }}</{{ statistic_method.name }}> {% endfor %} </statistics> instead … -
ImportError: cannot import name views - Django App Template Addition
I'm attempting to develop my own project alongside the Codeschool program introducing Django. I've gotten to the point where I want to implement a template for my landing page in templates folder at: C:\Users\****\****\ph_main\templates I am able to return html via the views.py file without templates via: from django.shortcuts import render from django.http import HttpResponse def index(request): return HttpResponse('Hello!') As soon as I add my application to the settings.py file. I receive an error that returns: File "C:\Users\****\****\ph_main\migrations\urls.py", line 2, in <module> from . import views ImportError: cannot import name views urls.py contains from django.conf.urls import url from . import views urlpatterns = [ url(r'^$', views.index) ] -
Django 3.0 - one to one serializer Create function
I extended the default User model to ExtendedUser: from django.db import models from django.contrib.auth.models import User class ExtendedUser(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) shirt_size = models.CharField(max_length=2) User serializer: from django.contrib.auth.models import User from rest_framework import serializers class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('url', 'username', 'email', 'groups', 'is_staff') ExtendedUser serializer: from api.resources.users.models.extended_user import ExtendedUser from rest_framework import serializers from django.contrib.auth.models import User from api.resources.users.serializers.user import UserSerializer class ExtendedUserSerializer(serializers.HyperlinkedModelSerializer): user = UserSerializer(read_only=False) class Meta: model = ExtendedUser fields = ('url', 'shirt_size', 'user') def create(self, validated_data): user_data = validated_data.pop('user') user = User.objects.create(**user_data) return ExtendedUser.objects.create(user=user, **validated_data) The main result should be that on submitting new ExtendedUser it will create a user too with one to one realation. But I am getting this error: User: myusername needs to have a value for field "user" before this many-to-many relationship can be used.