Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Framework : Attribute error 'Settings' object has no attribute 'TEMPLATE_DIRS'
I am a newbie in Django framework, unable to understand this issue. While running ./runtests.py command it gives attribute error message. Here is the error detail. ./runtests.py Testing against Django installed in '/usr/local/lib/python2.7/dist-packages/django' Traceback (most recent call last): File "./runtests.py", line 440, in <module> options.debug_sql) File "./runtests.py", line 239, in django_tests state = setup(verbosity, test_labels) File "./runtests.py", line 111, in setup 'TEMPLATE_DIRS': settings.TEMPLATE_DIRS, File "/usr/local/lib/python2.7/dist-packages/django/conf/__init__.py", line 57, in __getattr__ val = getattr(self._wrapped, name) AttributeError: 'Settings' object has no attribute 'TEMPLATE_DIRS' -
How to display form in django
I'am little confiused because my code in django does't work and I don't know why. I want to create a form displaying in html file. When I click on thh button, the url have to redirect me in the html file where I've put the form code. But the django return me a error 'User' object has no attribute 'nazwa_set' My models.py is: from django.db import models from django.contrib.auth.models import User class Firma(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Użytkownik") nazwa = models.CharField(max_length=250,verbose_name='Nazwa firmy', unique=False) class Meta: verbose_name = 'Firmę' verbose_name_plural = 'Firmy' def __str__(self): return self.nazwa class Cudzoziemiec(models.Model): OBYWATELSTWA = ( ('RU', 'Rosja'), ('UA', 'Ukraina'), ('BY', 'Białoruś'), ) TYTUL_POBYTOWY = ( ('WZ', 'Wiza'), ('KP', 'Karta pobytu') ) user = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Użytkownik") nazwa = models.ForeignKey(Firma, on_delete=models.CASCADE, verbose_name="Firma") obywatelstwo = models.CharField(max_length=250,choices=OBYWATELSTWA, verbose_name="Obywatelstwo") imie = models.CharField(max_length=80, verbose_name="Imię", unique=False) nazwisko = models.CharField(max_length=150, verbose_name="Nazwisko", unique=False) data_ur = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Data urodzenia") miejsce_ur = models.CharField(max_length=100, verbose_name="Miejsce urodzenia") paszport = models.CharField(max_length=30, verbose_name="Paszport") data_start_pasz = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Data wydania paszportu") data_koniec_pasz = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Data ważności paszportu") dok_pobytowy = models.CharField(max_length=250,choices=TYTUL_POBYTOWY, verbose_name="Tytuł pobytowy") data_start_pobyt = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Dokument pobytowy ważny od") data_koniec_pobyt = models.DateField(auto_now=False, auto_now_add=False, verbose_name="Dokument pobytowy ważny do") class Meta: verbose_name = 'Cudzoziemca' verbose_name_plural = 'Cudzoziemcy' def __str__(self): … -
Queryset: Compare a field with a substring of another field of the same model
I am trying to check if the first 3 characters of a Charfield (charfield_1) are similar to another Charfield (charfield_2) of the same model. Tried: User.objects.filter(charfield_2__startswith=Substr('charfield_1', 1, 3)) Tried using F and Func without any success. I keep getting: django.db.utils.DataError: invalid input syntax for integer: "1%" LINE 1: ...CE(REPLACE((SUBSTRING("model_name"."charfield_2", '1%', 3)),... Any idea how to make this work? -
How to escape single quote in django form widget
I am trying to set HTML <input> attribute through django ModelForm. with the following code. class ProductForm(ModelForm): class Meta: model = Product fields = '__all__' widgets = {'product_image' :FileInput(attrs={'data-form-data':'{"csrfmiddlewaretoken": "{{ csrf_token }}"}'}), } what i am trying to get, is like this (notice single-quote after data-form-data) <input type="file" name="product_name" data-form-data='{"csrfmiddlewaretoken": "{{ csrf_token }}"}'> But i got this instead (notice double-quotes after data-form-data) <input type="file" name="product_name" data-form-data="{"csrfmiddlewaretoken": "{{ csrf_token }}"}"> How can i prevent django to automatically convert single-quote to double-quotes ? thank you in advance. -
Get User's organization(s) in django-organizations
For the app django-organizations, how do you get a User's organization? From the doc's it says >>> from organizations.utils import create_organization >>> chris = User.objects.get(username="chris") >>> soundgarden = create_organization(chris, "Soundgarden", org_user_defaults={'is_admin': True}) >>> soundgarden.is_member(chris) True >>> soundgarden.is_admin(chris) True >>> soundgarden.owner.organization_user <OrganizationUser: Chris Cornell> >>> soundgarden.owner.organization_user.user >>> <User: chris> >>> audioslave = create_organization(chris, "Audioslave") >>> tom = User.objects.get(username="tom") >>> audioslave.add_user(tom, is_admin=True) <OrganizationUser: Tom Morello> and in my code I can easily do : @login_required def bandView(request, bandSlug): loggedInUser = get_object_or_404(User, username=request.user.get_username()) organization_requested = get_object_or_404(Organization, slug=bandSlug) if organization_requested.is_member(loggedInUser): #User is a member of the organization elze: # Not in this band but I am trying to work the other way now: @login_required def artistView(request): loggedInUser = get_object_or_404(User, username=request.user.get_username()) #something like.... loggedInUser.organizations #would print [<band1>,<band2>] #or add a function to the Organization[User] class Organizations.all().filter(member=loggedInuser) Organizations.getMembership(loggedInuser) Notes I have verified the user is a member of the organization as an OrganizationUser in both Admin and database print loggedInPerson.organizations_organizationuser -> organizations.OrganizationUser.None print loggedInPerson.organizations_organization -> organizations.Organization.None print loggedInPerson.organizations_organization_set -> errors print dir(loggedInPerson) -> ['DoesNotExist', 'EMAIL_FIELD', 'Meta', 'MultipleObjectsReturned', 'REQUIRED_FIELDS', 'USERNAME_FIELD', 'class', 'delattr', 'dict', 'doc', 'eq', 'format', 'getattribute', 'hash', 'init', u'module', 'ne', 'new', 'reduce', 'reduce_ex', 'repr', 'setattr', 'setstate', 'sizeof', 'str', 'subclasshook', 'unicode', 'weakref', '_check_column_name_clashes', '_check_field_name_clashes', '_check_fields', '_check_id_field', '_check_index_together', … -
python utcfromtimestamp for -144714 returns error
I have faced a bad error. I am using django and I am saving my datetime values as epoch time in database but when I want to convert them in python I face an error. if I use this code datetime.datetime.utcfromtimestamp(-14471).strftime('%Y-%m-%d') '1969-12-31' it works fine but if I use datetime.datetime.utcfromtimestamp(-144714).strftime('%Y-%m-%d') Traceback (most recent call last): File "<input>", line 1, in <module> OSError: [Errno 22] Invalid argument it does not work. well I can not convert my database values but why this error happens. what other options do I have to deal with this problem and why it shows such behavior ? I am using python 3.6.4 -
Django skip long migration history for new DB schema
Django using django-tenant-schemas My project requires runtime tenant creation (postgres schema creation), but due to long django migration history, migrations of a new schema take > 10 minutes which is far too long. So a method is required which skips the migrations, but brings the DB in the correct state. Reading What should I use instead of syncdb in Django 1.9? and https://docs.djangoproject.com/en/2.0/ref/django-admin/#cmdoption-migrate-run-syncdb ... it seems following could be a solution: python manage.py migrate auth # performs migrations for auth and contenttypes contrib apps python manage.py migrate --run-syncdb # creates the rest of the database But what are the consequences of this? Does it mean backwards migrations will not be possible for new schemas? (OK in this project as new schema doesn't have history anyway) Does it also mean future migrations cannot be applied since there is no correct migration history? That would obviously be a no-go. FYI version info: Django==1.11.7 django-tenant-schemas==1.8.0 -
trying to display render objects in django template in different places
I am using bootstrap in my template. I have 2 columns. In the first one, a list of my cars is displayed. I want that in second column if I click a car name from first column, only models specific to that car will be shown. How can I do that? <div class="row"> <div class="col-md-3"> {% for car in cars %} {{ car.name }} {% endfor %} </div> <div class="col-md-9"> {% for car in cars %} {% for model in models %} {% if model.car == car %} {{ model.name }} {% endif %} {% endfor %} {% endfor %} </div> </div> -
Filtering against query parameters Django REST Framework, Many to Many
I'm trying to build some kind of API, but I need to filtering request against query parameters in the URL (http:// ... / ?arg1=foo1&arg2=foo2&...). In my model scheme, I used a many to many relationships. Here is some of my code: my_app/models.py from django.contrib.postgres.fields import JSONField from django.db import models class MyData(models.Model): name = models.CharField(max_length=20) values = JSONField() class MyModel(models.Model): time = models.DateTimeField() country = models.CharField(max_length=50) data = models.ManyToManyField(MyData) my_app/serializers.py from rest_framework import serializers from my_app.models import MyModel, MyData class MyDataSerializer(serializers.ModelSerializer): class Meta: model = MyData fields = ('name', 'values',) class MyModelSerializer(serializers.ModelSerializer): data = MyDataSerializer(many=True, read_only=True) class Meta: model = MyModel fields = ('country', 'data',) my_app/views.py from rest_framework import generics from my_app.serializers import MySerializer from my_app.models import MyModel class MyView(generics.ListAPIView): serializer_class = MySerializer def get_queryset(self): queryset = MyModel.objects.all() names = self.request.query_params.get('Simon', None) if names: queryset = queryset.filter(data__name__in=names.split(',')) return queryset and here are the responses Response to http://127.0.0.1:8000/hello/ HTTP 200 OK Allow: GET, HEAD, OPTIONS Content-Type: application/json Vary: Accept [ { "country": "Spain", "data": [ { "name": "Mark", "values": {"A": "Hello, it's Wario"} }, { "name": "Simon", "values": {"A": "Hello, it's Mario"} }, ] }, { "country": "Italy", "data": [ { "name": "Jake", "values": {"A": "Hello, it's Luigi"} } ] } … -
Django multi table inheritance: move instance between child models
Assume I have in models.pysomething like: Class ModelA(models.Model): # many fields, including relatives = models.ManyToManyField(Person) ) # also, A is foreign key to other models: Class SomeOtherModel(models.Model): mya = models.ForeignKey(A) # now we produce two classes with multi-table inheritance # WITHOUT any additional fileds Class InhertA1(ModelA): pass Class InhertA2(ModelA): pass So as as I understand, this will create Tables for ModelA, InheritA1 and InheritA1; each instance of ModelA will get a row in the ModelA-table only, each instance of InheritA1 will have a row both in the ModelA-table (basically containing all the data) and another in the InheritA1-table (only containing a PK and a OneToOne key pointing to the ModelA-table row), etc. Django queries for ModelA-objects will give all objects, quries for InheritA1-objects only the InheritA1 ones etc. So now I have an InheritA1-object a1, and want to make it into a InheritA2-object, without changing the according ModelA-object. So previously the parent-IbeToOne Key of a1 points to the ModelA-row with key 3, say (and the ForeignKey of some SomeOtherModel-object is set to 3). In the end, I want a InheritA1-object a2 pointing to the same, unchanged ModelA-row (and the object a1removed). It seems that django doesn't offer any such move-Class-functionality? … -
How can I make search and pagination work for my filtered entries?
So I've set up pagination and search for all the courses names that can be listed from my Course model. Now, I want to set up pagination and search again, but this time only for some specific courses. By using a jQuery function, when a user presses on one of the faculty names listed on the left column, all the courses on the right column, from my Course model that have been previously listed, get replaced with the courses from that specific faculty. And here I don't know how exactly how I should add pagination and search again, mostly because I don't know exactly how this interacts with my jQuery and the proper way to do it. Here is a screenshot with what it should look like: https://i.imgur.com/RyyELnP.png def index(request): query_list = Course.objects.all() query = request.GET.get('q') if query: query_list = query_list.filter(Q(name__icontains=query)) paginator = Paginator(query_list, 1) page = request.GET.get('page') try: courses = paginator.page(page) except PageNotAnInteger: courses = paginator.page(1) except EmptyPage: courses = paginator.page(paginator.num_pages) context = { 'courses': courses, 'faculties': Faculty.objects.all(), 'departments': Department.objects.all(), 'studies': StudyProgramme.objects.all(), 'teachers': Teacher.objects.all() } return render(request, 'courses/index.html', context) <script> $(document).ready(function () { $('.btnClick').on('click', function () { var faculty_id = $(this).attr('id'); $('#' + faculty_id + '_tab').show().siblings('div').hide(); }); $('.btnClick0').on('click', function … -
What app should you put your index in in Django?
I'm unfamiliar with the organizational conventions of Django. What app should I put the index page in? I have a login and registration app so far. Should I use flatpages? Should I use flatpages for the index page and login and registration forms and only use the login and registration app views for accepting POST requests? -
setting up django setting.py with mysql database
Im using mysql in my windows7 for a yr and its working fine. i recently know about django and trying to catch up the tuturial. Im having a problem to set up the setting.py and i think its on 'NAME' path. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': os.path.join('C:/ProgramData/MySQL/MySQL Server 5.7/Data/mysql', 'db.frm'), 'USER': '***', 'PASSWORD':'***' } } -
Django: django.core.exceptions.ImproperlyConfigured: WSGI application 'wsgi.application' could not be loaded; Error importing module
I used to check every answer to this question< but NOTHING helped me. Here's a error: edjango.core.exceptions.ImproperlyConfigured: WSGI application 'wsgi.application' could not be loaded; Error importing module. In settings file is: WSGI_APPLICATION = 'wsgi.application' and WSGI file is: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "MyLittleTest.settings") application = get_wsgi_application() Can you help me with this issue plz? -
Django&REST-framework architecture
Hello I am tasked with translating a current Excel tool to a web application. I decided to use Python and Django. Lately I studied the Django REST framework. I have the following related questions. Is it for such an application a good idea to first write a web REST API so that I firstly only need to focus on the backbone of the web application. I.e. implement the PUT, POST, GET and DELETE methods and the Django models. The second step would be to implement the user interface... But if this is a valid method how can I reuse the REST views??? I followed the REST tutorials, but they don't show how to build a nice slick user-interface on top of the REST API. Since REST views inherit from Django, I think it's maybe not such a good idea to write a Django view which inherits from a REST Apiview? Or can I directly use an API endpoint in a template. If so where can I get some nice examples? -
Django: Graphviz generation with model names only?
I'm using Graphviz in Django (via django-extensions) to generate graph models. I'd like to generate graphs in two distinct ways: App by app in details (1 app per graph) -> no problem, it's done. All my models from all my apps, but without attributes (only model names) -> is it possible? I didn't find a way to do it in the documentation. If there is no way, I guess I could take a look to the source code, but not sure about the difficulty to do this. Thanks. -
Images are not displayed on web-page (Django)
the problem is this, using Bootstrap 3, created the "Carousel" from the images, then in Views wrote a loop that adds all the images with paths to the dictionary, then through the loop, output all the images in HTML-views. HTML <div id="myCarousel" class="carousel slide" data-ride="carousel"> <!-- Indicators --> <ol class="carousel-indicators"> <li data-target="#myCarousel" data-slide-to="0" class="active"></li> <li data-target="#myCarousel" data-slide-to="1"></li> <li data-target="#myCarousel" data-slide-to="2"></li> </ol> <!-- Wrapper for slides --> <div class="carousel-inner"> {% for picture in picture_list %} <div class="item active"><img src="{{ picture }}" style="width:100%;"> </div> {% endfor %} </div> <!-- Left and right controls --> <a class="left carousel-control" href="#myCarousel" data-slide="prev"> <span class="glyphicon glyphicon-chevron-left"></span> <span class="sr-only">Previous</span> </a> <a class="right carousel-control" href="#myCarousel" data-slide="next"> <span class="glyphicon glyphicon-chevron-right"></span> <span class="sr-only">Next</span> </a> Views def recipes_list(request): recipes = Recipe.objects.filter(created_date__lte=timezone.now()).order_by('created_date') pictures = os.listdir(os.path.join(settings.STATIC_PATH, 'images/carousel')) picture_list = [] for picture in pictures: path = str(os.path.join(settings.STATIC_PATH, 'images\carousel').replace('\\', '/')) picture_list.append('%s/%s' % (path, picture)) return render(request, 'Recipes/recipes_list.html', {'recipes': recipes, 'sub_form': sub_form, 'picture_list': picture_list}) In browser <img src="C:/Users/%username%/PycharmProjects/Django/CookBook/Recipes/static/images/carousel/FRIED SAGE1.jpg" style="width:100%;"> -
save polygon wkt in HEX mode in database
I want to have a fixture (in django) to have some regions' polygon. In my database a long string is saved (type geometry and HEX), however I have a wkt (starting with SRID=4326;MULTIPOLYGON(((45.09 ...... ) for the regions. how can I do that? tnx -
Query different field than defined in return for a ManyToMany field option
I am new to Django and have a problem that I am trying to fix. In my application I have a model Asset which has multiple choice answer from AFF. Here is the code: class Rtype(models.Model): rtype_name = models.CharField(max_length=10, verbose_name="Type", default = "") rtype_score = models.CharField(max_length=10, verbose_name="Score", default = "") def __str__(self): return self.rtype_name class AFF(models.Model): ff = models.CharField(max_length=100, verbose_name="FF", default = "") ff_score = models.ForeignKey(Rtype, on_delete=models.CASCADE, blank=True, null=True, verbose_name="Score", default = "") def __str__(self): return self.ff class Asset(models.Model): fjam = models.ManyToManyField(AFF, verbose_name="Fjam", default = "", blank=True) def __str__(self): return self.fjam Let's say there are following entries in the database: rtype_name = Critical rtype_score = 5 rtype_name = Medium rtype_score = 3 ff = Direct ff_score = Critical ff = Indirect ff_score = Medium If user chooses in Asset form, both Direct and Indirect, how can I save 3 + 5 in the database when they submit the form instead of rtype_names by keeping return self.rtype_name in Rtype (useful for showing user a name rather then a score). -
DJongo adding Custom user field error in DJango 2
I used DJongo for using mongodb with Django2. When I adding custom fields for user, I get following erorr: "jomploy_user"."first_name", "jomploy_user"."last_name", "jomploy_user"."email", "jomploy_user"."is_staff", "jomploy_user"."is_active", "jomploy_user"."date_joined", "jomploy_user"."telephone" FROM "jomploy_user" WHERE "jomploy_user"."id" = %(0)s Version: 1.2.20 Request Method: GET Request URL: http://127.0.0.1:8000/admin/jomploy/user/1/change/ Django Version: 2.0.2 Exception Type: SQLDecodeError Exception Value: FAILED SQL: SELECT "jomploy_user"."id", "jomploy_user"."password", "jomploy_user"."last_login", "jomploy_user"."is_superuser", "jomploy_user"."username", "jomploy_user"."first_name", "jomploy_user"."last_name", "jomploy_user"."email", "jomploy_user"."is_staff", "jomploy_user"."is_active", "jomploy_user"."date_joined", "jomploy_user"."telephone" FROM "jomploy_user" WHERE "jomploy_user"."id" = %(0)s Version: 1.2.20 Exception Location: E:\Django\lib\site-packages\djongo\sql2mongo\query.py in __iter__, line 451 Python Executable: E:\Django\Scripts\python.exe Python Version: 3.6.2 Python Path: ['E:\\Project\\fuck6', 'E:\\Django\\Scripts\\python36.zip', 'E:\\Django\\DLLs', 'E:\\Django\\lib', 'E:\\Django\\Scripts', 'C:\\Program Files\\Python36\\Lib', 'C:\\Program Files\\Python36\\DLLs', 'E:\\Django', 'E:\\Django\\lib\\site-packages', 'C:\\Program Files\\Python36', 'C:\\Program Files\\Python36\\lib\\site-packages'] Server time: Sun, 18 Feb 2018 09:45:25 +0000 And here is my code: class User(AbstractUser): telephone = models.CharField(max_length=15,blank=True,null=True) -
How to return a list foreign key fields in a raw form using SerializerMethodField in Django Rest Framework?
Models: class Author(models.Model): name = models.CharField() class Book(models.Model): author = models.ForeignKey("Author") title = models.CharField() subtitle = models.CharField() def get_full_title(self): return "{title}: {subtitle}.".format(title=self.title, subtitle=self.subtitle) Queryset: queryset = Author.prefetch_related("book_set").all() Desired Responce: [ { "id": 1, "name": "J. R. R. Tolkien", "books": [ "The Hobbit: or There and Back Again", "The Fellowship of the Ring: being the first part of The Lord of the Rings.", "The Two Towers: being the second part of The Lord of the Rings.", "The Return of the King: being the third part of The Lord of the Rings." ] }, { "id": 2, "name": "Peter Thiel", "books": [ "The Diversity Myth: Multiculturalism and Political Intolerance on Campus.", "Zero to One: Notes on Startups, or How to Build the Future." ] } ] The problem here is that if you use serializers.ListSerializer() on Authors.book_set list, I will get an entire model in that list with all it's fields. If you try to use serializers.SerializerMethodField, DRF would not let you use it on multiple results. SerializerMethodField doesn't support an option many AKA serializers.SerializerMethodField(many=True) I should note here that one could write a method that cycles through the results and accumulates them into a string, but that limits you from further … -
Django, User can have more than one role in the application, 3 types of User
As title, I have 3 types of User and each User can have more than one role. from django.contrib.auth.models import AbstractUser, User from django.db import models from django.db.models import CASCADE from hospital.models import Hospital class Role(models.Model): ''' The Role entries are managed by the system, automatically created via a Django data migration. ''' DOCTOR = 1 DIRECTOR = 2 PATIENT = 3 ROLE_CHOICES = ( (DOCTOR, 'doctor'), (DIRECTOR, 'director'), (PATIENT, 'patient'), ) id = models.PositiveSmallIntegerField(choices=ROLE_CHOICES, primary_key=True) def __str__(self): return self.get_id_display() class User(AbstractUser): roles = models.ManyToManyField(Role) def __str__(self): return self.roles class Doctor(models.Model): # role = models.OneToOneField(User, on_delete=CASCADE) career = models.TextField(blank=True, max_length = 1000) class Director(models.Model): # role = models.OneToOneField(User, on_delete=CASCADE) members = models.ManyToManyField(Doctor) class Patient(models.Model): # personal information like above. https://simpleisbetterthancomplex.com/tutorial/2018/01/18/how-to-implement-multiple-user-types-with-django.html I'm creating a model, but I do not know how to set the key. I made it by referring to the above site. The director owns the doctor and can authorize it. But I do not know how to give a key to a doctor or director. If you I to comment, I get an error. I hope you can help me. -
how to add post to django user model using foreignkey
i created a model class ThisUser(models.Model): created = models.DateTimeField(auto_now=True) message = models.CharField(max_length=120) user = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.user I want to store message specifically for the user who is authenticated. right now this will give me all user who is available in my user model. Please help -
ImportError in django
I am learning django. I am doing exactly what had said in tutorial book. I am getting this error no matter what I do. please help me to fix this. please don't mind of grammatical error in my description. 1st step:django-admin startproject project 2nd step:cd project 3rd step:django-admin startapp myapp 4th step:cd to myproject 5th step:nano settings.py 6th step:add myapp in install app list 7th step:edit urls.py file add the below code for url mapping from django.conf.urls import include, url from django.contrib import admin admin.autodiscover() urlpatterns = [ # Examples: # url(r'^$', 'project.views.home', name='home'), # url(r'^blog/', include('blog.urls')), url(r'^admin/', include(admin.site.urls)), url(r'^chirag/','myapp.views.chirag',name='chirag'),] 8th step:move back to myapp and edit views.py file as below: from django.shortcuts import render from djanog.http import HttpResponse # Create your views here. def chirag(request): t="""<h1>hello chirag<h1>""" return HttpResponse(t) 9th step:move back to project folder then run a code python manage.py syncdb 10th step:create a super user 11nth step:python manage.py migrate 12th step:python manage.py runserver: Performing system checks... System check identified no issues (0 silenced). February 18, 2018 - 08:18:29 Django version 1.8, using settings 'project.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. 13th step:open a web-browser then type:http://127.0.0.1:8000/chirag then i am getting this error ImportError … -
Cannot assign "''": "User.country" must be a "Country" instance
I am using a custom register serializer in django-rest-auth to add new fields on registration. I have a country model and a country field in the user model that is an FK to countries. user.models @python_2_unicode_compatible class User(AbstractUser): phone = models.CharField(max_length=15, null=True) verified_phone = models.BooleanField(default=False) country = models.ForeignKey(Country, related_name='country') level = models.ForeignKey(UserLevel, related_name='user_level') user.serializers class UserModelSerializer(HyperlinkedModelSerializer): class Meta: model = User country = serializers.ReadOnlyField(source='country.name') fields = [ 'url', 'id', 'username', 'country', 'email', 'phone', ] read_only_fields = ( 'id', 'password', ) custom register serializer class CustomRegisterSerializer(RegisterSerializer): country = serializers.PrimaryKeyRelatedField(read_only=True) def get_cleaned_data(self): return { 'country': self.validated_data.get('country', ''), 'password1': self.validated_data.get('password1', ''), 'email': self.validated_data.get('email', ''), 'username': self.validated_data.get('username', ''), } def save(self, request): print(self.get_cleaned_data()) adapter = get_adapter() user = adapter.new_user(request) user.country = self.validated_data.get('country', '') self.cleaned_data = self.get_cleaned_data() adapter.save_user(request, user, self) setup_user_email(request, user, []) user.save() return user Sample data that is sent from the client with the country as an object {username: "bernie", email: "bernie@d.com", country: {…}, password1: "password", password2: "password"} but this error keeps coming, Cannot assign "''": "User.country" must be a "Country" instance. when I printed the request on the console this is what I got {'country': '', 'password1': 'password', 'email': 'bernie@d.com', 'username': 'bernie'} which means that somewhere along the line, the country data …