Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Field-level validation in Django REST - checking that field value is actually valid
I have a Django 1.10 project and a model like this: class Student(models.Model): #... university = models.ForeignKey(University, ...) ...and a serializer in which I want to perform a check like this (I provide a pseudo-code because I've got no idea how to write native Django code): class StudentSerializer(serializers.ModelSerializer): class Meta: model = Student fields = '__all__' def validate_student(self, value): if invalid_value_is_provided_for_student: value = 666 return value One way to do this that occurred to me is: def validate_student(self, value): if value not in University.objects.values('id'): value = 666 return value ...which seems to be a bit dirty. I have a feeling that Django has a native more elegant way to implement this using exception handling. Any ideas? -
Django - request.user.username inside an @api_view(['GET,'POST']) request function
So I have an @api_view which is based on a post request, which has some parameters sent from the front end. I want to get the username of the loggedin user to perfrom some other actions. But request.user.username always returns "Anonymous User". If I call request.user.username outside of this request function I get the logged in user returned correctly. What is going wrong here? @api_view(['GET,'POST']) def function(request) if request.method == 'POST' data = request.data ** perform some function ** username = request.user.username ** perform some other actions with username** -
How can I combine 2 django query into one with object limit
I have multiple type of obj_type in database What i am currently doing is a = Search_model.objects.filter(obj_type="mall", city=city)[:2] b = Search_model.objects.filter(obj_type="store", city=city)[:2] and then combine a and b so it gives me:- [{"name":"a","obj_type":"mall"}, {"name":"b","obj_type":"mall"}{"name":"c","obj_type":"store"}, {"name":"d","obj_type":"store"}] what i want is something like this if not search_in == None: search_in_queries = [q for q in re.split(",", search_in) if q] for query in search_in_queries: search_in_dict.append(('obj_type__contains', query)) search_in_query = [Q(x) for x in search_in_dict] else: search_in_query = None such that value of search_in is "mall,store" a = Search_model.objects.filter(reduce(operator.or_, search_in_query), city=city)[:4] but it gives me all mall type obj [{"name":"a","obj_type":"mall"}, {"name":"b","obj_type":"mall"}{"name":"c","obj_type":"mall"}, {"name":"d","obj_type":"mall"}] so my query is how can i achieve the above result in one query -
Django : 'unicode' object has no attribute 'get'
I had a problem with my Django program. I'm a beginner in Django, I was looking for an answer with different posts with the same error than mine but no success ... Here's my traceback : Environment: Request Method: POST Request URL: http://127.0.0.1:8000/pod Django Version: 1.11.2 Python Version: 2.7.13 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'labinit', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Python27\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 187. response = self.process_exception_by_middleware(e, request) File "C:\Python27\lib\site-packages\django\core\handlers\base.py" in _get_response 185. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\admin\Desktop\django_learneo3\Learneo\labinit\views.py" in groupe_pod 121. if form.is_valid(): File "C:\Python27\lib\site-packages\django\forms\forms.py" in is_valid 183. return self.is_bound and not self.errors File "C:\Python27\lib\site-packages\django\forms\forms.py" in errors 175. self.full_clean() File "C:\Python27\lib\site-packages\django\forms\forms.py" in full_clean 384. self._clean_fields() File "C:\Python27\lib\site-packages\django\forms\forms.py" in _clean_fields 396. value = field.widget.value_from_datadict(self.data, self.files, self.add_prefix(name)) File "C:\Python27\lib\site-packages\django\forms\widgets.py" in value_from_datadict 639. getter = data.get Exception Type: AttributeError at /pod Exception Value: 'unicode' object has no attribute 'get' This issue appears since I have changed my init fonction, for the form that I use in my view : Forms: class Groupe_Form(forms.ModelForm) : def __init__(self, nom_groupe, *args, **kwargs): super(Groupe_Form,self).__init__(*args, **kwargs) self.fields['pod'].widget = forms.Select() pod1 = Groupe.objects.filter(nom_groupe = nom_groupe).values_list('pod', flat = True) pods = list(pod1) … -
Django sqlite content in easy-pdf
Django version: 1.11.3 I have stored data in a sqlite database as I want to have displayed in a pdf. I use easy-pdf. I don't know how to parse the data without using render(). How do I do it with get_context_data(). Any suggestions? This works: def test(request): all_organizations = Organization.objects.all() all_tickets = Ticket.objects.all() context = {'all_organizations': all_organizations, 'all_tickets': all_tickets} return render(request, 'test/docs/examples/theme/test.html', context) Don't know how to parse all_organizations and all_tickets for use in the easy-pdf: class HelloPDFView(PDFTemplateView): all_organizations = Organization.objects.all() all_tickets = Ticket.objects.all() context = {'all_organizations': all_organizations, 'all_tickets': all_tickets} template_name = "test/docs/examples/theme/hello.html" def get_context_data(self, **kwargs): return super(HelloPDFView, self).get_context_data( pagesize="A4", title="Test", **kwargs ) -
Django run def index(reuqest) in other def without duplication of code
in my view.py I have a def index(request): and def other(request): In def other(request): I want to run the exact same code like def index(request): if request.method == 'POST': and else do something different Copy the code from def index(request): to def other(request): after if request.method == 'POST': works but duplicate code is bad. If I do index(request) after the if statement, def other(request): return nothing. What is the right method to achieve this? -
Django CMS get_next_sibling not returning the next page
Anyone come up with this issue before with Django CMS, the current and next requests return the same result (current page). All the others behave as expected: First: {{ request.current_page.get_first_sibling.get_page_title }}</br> Prev: {{ request.current_page.get_prev_sibling.get_page_title }}</br> Current: {{ request.current_page.get_page_title }}</br> Next: {{ request.current_page.get_next_sibling.get_page_title }}</br> Last: {{ request.current_page.get_last_sibling.get_page_title }} -
Django template loop dictionary and check if value is None
I have following code in Django template: 1. {% for key, value in dict.items %} 2. <div> 3. <lable>{{key}}:</lable> 4. {% if value == None %} 5. <input></input> 6. {% elif %} 7. <input value={{value}}></input> 8. {% endif %} 9. </div> 10. {% endfor %} but at the line 4 there is error. It cannot check if the value is none. How can it be checked? -
test case for form validation not running in django
I started learning django framework in that I have created form which verifies interdependent fields. now I have written a testCase for it but my console is showing 0 test cases ran.I am not getting why it is not running below is my forms.py class SearchForm(forms.ModelForm): fromDate=forms.DateField() toDate=forms.DateField(required=False) fromLocation=forms.CharField() toLocation=forms.CharField() def clean(self): """verify from and to date and location""" cleanedData=super().clean() fLocation=cleanedData.get('fromLocation') tLocation=cleanedData.get('toLocation') self.validateLocation(fLocation,tLocation) self.validateDates(self.fromDate,self.toDate) def validateLocation(self,fLocation,tLocation): if fLocation==tLocation: raise forms.ValidationError(_("from and to location can not be same"),code="invalid location") def validateDates(self,fromDate,toDate): if toDate is not None: if toDate <= fromDate: raise forms.ValidationError(_("from date should be less than to date"),code="invalid date") and my tests.py from django.test import TestCase from booking.forms import SearchForm # Create your tests here. class SearchTestCase(TestCase): def fromToLocationSameTestCase(self): form_data={'fromLocation':'bangalore','toLocation':'bangalore','fromDate':'2017-06-07'} form=SearchForm(data=form_data) self.assertFlase(form.is_valid()) please let me know where I went wrong. FYI I tried by overriding clean method of forms but no luck -
Django Debug Toolbar shows 404 on panel
My Django-Debug-Toolbar results in a Http404 as soon as I click on a Panel like "Requests". I checked my config multiple times but can't find whats wrong. Versions: django-debug-toolbar == 1.8 django == 1.11.1 settings.py # DEBUG TOOLBAR if DEBUG: def custom_show_toolbar(request): """ Only show the debug toolbar to users with the superuser flag. """ #return request.user.is_superuser if request.is_ajax(): return False return True MIDDLEWARE += ( 'debug_toolbar.middleware.DebugToolbarMiddleware', ) INSTALLED_APPS += ( 'debug_toolbar', ) INTERNAL_IPS = ('127.0.0.1', ) DEBUG_TOOLBAR_CONFIG = { 'INTERCEPT_REDIRECTS': False, 'SHOW_TOOLBAR_CALLBACK': 'core.settings.custom_show_toolbar', 'HIDE_DJANGO_SQL': True, 'TAG': 'body', 'SHOW_TEMPLATE_CONTEXT': True, 'ENABLE_STACKTRACES': True, } urls.py urlpatterns = [ url(r'^$', core_views.home, name='home'), #url(r'^login/$', auth_views.login, name='login'), #url(r'^logout/$', auth_views.logout, name='logout'), #url(r'^oauth/', include('social_django.urls', namespace='social')), url(r'^admin/', admin.site.urls), ] if settings.DEBUG: import debug_toolbar urlpatterns = [ url(r'^__debug__/', include(debug_toolbar.urls)), ] + urlpatterns -
Display a list only when a checkbox is checked
I'm having some trouble with HTML and Javascript (which I'm still new to). I use the Django Framework to display a list in a table case : for each element of my database, I display a list, and in this first list, a new list of corresponding elements in the database. I made a JSFiddle. The situation : <tr> <td>Foo</td> <td>Fighters<td> <td>Bar</td> <td>Baz</td> <td> <ul> {% for domain,terms in django_database %} <li> <input type="checkbox" class="listcheck"><label for="listcheck"> - {{ domain }}</label> <!-- When checkbox is checked, the following list displays --> <ul> {% for object in database %} <li>{{ object }}</li> {% endfor %} </ul> </li> {% endfor %} </ul> </td> </tr> This is the Javascript that I tried, shamelessly stolen from a related question. for (var i = 0; i < checkboxes.length; i++) { var box = checkboxes[i]; box.onclick = function() { var currentList = this.parentNode; var secondColumn = currentRow.getElementsByTagName("ul")[1]; alert("My text is: " + secondColumn.textContent ); }; } Now, I can display the two HTML lists without any trouble, it works fine. But I can't manage to get a checkbox that works. Hmm. -
django - how to restrict number of pages an unauthenticated user can view
I am building a website using django (1.10). I want to restrict the number of pages that an unauthorised person (i.e. a user that is not logged in), can view. The desired behaviour is that after visiting N different pages, the user is directed to a specific page. In other web platforms I have used (Symfony), there is a way of doing this by writing custom "filters" and session variables - I think django provides similar affordances via it's concept of midleware - however, not sure if this is the way to go, to implement this requirement. How best may I implement this requirement (unauthorised user directed to a custom page after viewing N different pages), using the django framework? -
Dockerization and deploying on Heroku project with Angular 4 frontend with Django backend and postgresql database
I would like to dockerize Angular 4 frontend with Django backend and postgresql database. Besides, I am going to deploy it on Heroku. At this moment my situation looks as shown below. I am note sure if this is done properly? Unfortunately it doesn't work. When i try docker-compose up I get: MacBook-Pro:~ myUser$ docker-compose up Building angular Step 1/7 : FROM node:8.1.2-onbuild as builder # Executing 5 build triggers... Step 1/1 : ARG NODE_ENV ---> Using cache Step 1/1 : ENV NODE_ENV $NODE_ENV ---> Using cache Step 1/1 : COPY package.json /usr/src/app/ ---> Using cache Step 1/1 : RUN npm install && npm cache clean --force ---> Using cache Step 1/1 : COPY . /usr/src/app ---> Using cache ---> 4ba35205484c Step 2/7 : ARG TARGET=production ---> Using cache ---> 20f3f25f3d45 Step 3/7 : RUN npm install @angular/cli ---> Using cache ---> 005a5afcef88 Step 4/7 : RUN node_modules/.bin/ng build -aot --target ${TARGET} ---> Running in 09e5752964f6 Hash: 0c91b5245d9f2f1b899d Time: 12174ms chunk {0} polyfills.51d1b984c6d09b6245cd.bundle.js (polyfills) 232 kB {4} [initial] [rendered] chunk {1} main.466ececd219a11fbf397.bundle.js (main) 1.04 kB {3} [initial] [rendered] chunk {2} styles.4d1993091a9939c0785a.bundle.css (styles) 69 bytes {4} [initial] [rendered] chunk {3} vendor.927d5207264169ec1f8c.bundle.js (vendor) 836 kB [initial] [rendered] chunk {4} inline.e6088d403421d3b3ae62.bundle.js (inline) 0 … -
Django, Ajax url not found in js file
I'm making the website using django, python and javascript. I get an error 'Not found: /schedule/{% url 'schedule_delete' %}' when I use the ajax in js file fullcalendar.js function eventElementHandlers(event, eventElement) { eventElement .click(function(ev) { var start = event.start; var id = event.id; var title = event.title; var allData = {'csrfmiddlewaretoken': '{{ csrf_token }}', "id":id, "start":start, "title":title}; $.ajax({ url: "{% url 'schedule_delete' %}", type: "POST", data: allData, dataType: "json", success: function(response){ alert("success!"); $('#used_session'+id).html(response.used_session); }, error:function(error){ alert("fail!"); } }); } urls.py from django.conf.urls import url from . import views urlpatterns= [ url(r'^$', views.home, name='home'), url(r'^schedule_delete/$', views.schedule_delete, name='schedule_delete'), ] I also made schedule_delete in views.py. Why url is wrong?? The same url format was okay in the other template. Is url foramt different depending on the django template or js file?? Any help will be very helpful to me, thanks! -
Shell script called from PHP does not work, but it works in command line
I want to copy a file by shell script called from PHP. However cp command does not work properly. My system is as follows: Linux: Ubuntu MATE 16.01, Apache2 (port 80), django (port 8000), php (port 80) Shell script is like this: #!/bin/sh cp /var/www/html/aaa.html /home/user/test/aaa.html aaa.html is a web page on django and is saved under /var/www/html/ by php. I call php on aaa.html, and I upload aaa.html. After that I execute shell script above on php. When I input 'cp /var/www/html/aaa.html /home/user/test/aaa.html' in command line (SSH connect), it works and aaa.html is updated even the django's runserver is under run. However when I do the command in shell script, aaa.html is not updated. How can I update aaa.html by shell script called by PHP? I think if I could kill runserver, aaa.html would be updated. Though command kill called from shell script does not work too. Are there anyway to do it? Thank you. -
Django Media not showing with Debug False
I'm a beginner at Python, my settings.py: STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') MEDIA_ROOT = os.path.join(BASE_DIR, 'media') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'theme', 'static'), ] If I turn DEBUG to False,the staticfiles and mediafiles don't work, when i run devserver in insecure mode: python manage.py runserver --insecure The staticfiles works,but mediafiles(avatars) still doens't work. my app installed way: pip install misago start path: /home/project/ Can someone help me? thanks. -
access a value of a column of an n-uplet in django
I need help, please. I've got an SQL database and my model name is: "Image" which has an integer model field "size" I want to select the value of the size of the last image on my database, I tried this on SQL and it works: select size from app_image where id = (select max(id) as maxenreg from app_image); But when i use this on my view : var = Image.objects.raw('select size from app_image where id = (select max(id) as maxenreg from app_image)') it didn't give the same result. Is there any query set of Django equivalent to that or any other solution to get this value? -
How will i know if celery backround process is succesful inside django code. If it is succesful i want render a html page.
I am not able to do because i dont have the status of the currently running background process in the django code. Request: i need to know the status of the celery background task and render the html page from there @task_success.connect def task_sent_handler3(sender=None,result=None,**kwargs): # information about task are located in headers for task messages # using the task protocol version 2. #info = headers if 'task' in headers else body tester() #print('after_task_publish for task id {info[id]}'.format(info="hhhi",)) I tried the above celery annotation but i did not return anything. If it return also will i be able to access the local variables and return the render function render(request,'page.html') from that success decoration function please tell me how i can tackle this -
Error - ImportError raised loading rest_framework.templatetags.rest_framework
I am making an application with django and mongodb .Previously my application run ohk with sql but now i want to coonect it with mongo but i am getting this error again and again.I am using python2.7 plz help me resolve this error - 'rest_framework' is not a valid tag library: ImportError raised loading rest_framework.templatetags.rest_framework: No module named app my setting.py file is - import os import admin_app from django.utils import timezone import django_mongodb_engine.base from mongoengine import connect connect('pom') BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'uj8$6(ol=!w)b3-luqzb=#6(j19gkbrnp2asq6=xt%5*s2ylz(' DEBUG = True ALLOWED_HOSTS = [] SPATIALITE_LIBRARY_PATH = 'mod_spatialite' # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'rest_framework', 'djangotoolbox', 'admin_app', 'celery', ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', #'django.middleware.security.SecurityMiddleware', 'djangoflash.middleware.FlashMiddleware', 'django.middleware.cache.CacheMiddleware', ) ROOT_URLCONF = 'admin_python.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates'), os.path.join(BASE_DIR, 'media')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'admin_app.context_processors.init_menu', 'admin_app.context_processors.server_urls', 'djangoflash.context_processors.flash', ], }, }, ] STATICFILES_FINDERS = ( 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) STATIC_ROOT = os.path.join(BASE_DIR, "static/") MEDIA_URL = '/media/' HOST_URL='http://127.0.0.1:8001/media/' MEDIA_ROOT = os.path.join(BASE_DIR, "media/") WSGI_APPLICATION = 'admin_python.wsgi.application' STATIC_URL = '/static/' SERVER_URL = 'http://localhost:8001/' WEBAPP_URL = 'http://localhost/webapp_angular/' USERAPI_URL = 'http://localhost:8000/' … -
Multiple urls in one tag in Django form action
I want to implement global search in Django admin. Here's my html code: <div class="search-box"> <form method="get" action= "{% url 'admin:accounts_user_changelist' %}"> <div> <div class="input-box-search"> <input size="40" name="q" value="" id="searchbar" autofocus="" type="text"></div> </div> </form> </div> Here I have given the form action of only one view i.e. 'admin:accounts_user_changelist' I want to give the url of views of all the changelists as I want to search a keyword in all the tables. How can I give multiple changelist views in action url? like I want to implement the functionality similar to : {% url 'admin:accounts_user_changelist', 'admin:league_sport_changelist' %} -
Can't use CKEDITOR in django template
I am using a form without a model class. class ClubWallForm(forms.Form): title = forms.CharField(label='Post title', max_length=100) description = RichTextField() imgURL = forms.CharField(label='Post image url', max_length=100) filefield = forms.FileField( label='Select a file',validators=[validate_file_extension] ) In my template I used ` {% for field in form %} <div class="fieldWrapper"> {{ field.errors }} {{ field.label_tag }}: {{ field }} </div> {% endfor %}` CKEDITOR is not geting displayed in my template. This is what I am getting. Inside my views it tried to use ipdb and found that the form has only fields title imgurl and filefield . class ClubWallPostCreateView(LoginRequiredMixin, FormView): """It creates categories.""" template_name = 'club_wall_form.html' form_class = ClubWallForm def dispatch(self, *args, **kwargs): return super(ClubWallPostCreateView, self).dispatch(*args, **kwargs) def get_success_url(self): """URL to redirect after successfull creation of the category.""" return '/home' # + self.kwargs[''] + '/' def get_context_data(self, **kwargs): """It overrides the default context data of FormView. """ context = super(ClubWallPostCreateView, self).get_context_data(**kwargs) return context def form_valid(self, form): """It is called when valid form data has been POSTed. It should return an HttpResponse. It saves category for the given id. """ user = self.request.user firebase = pyrebase.initialize_app(config) auth = firebase.auth() db = firebase.database() storage = firebase.storage() firebaseuser = auth.refresh(user.userprofile.refresh_token) #auth.sign_in_with_custom_token(user.userprofile.access_token) # userdata = auth.get_account_info(firebaseuser['idToken']) import … -
Large Video upload on Dropbox using Angular 2
I need to upload large video files on Dropbox using Angular 2/4. Dropbox api has a limit of 150 MB for Video files. For anything larger then this require splitting the video in chunks and then uploading it using upload session API's. 1: First part of this question is that how should i split the video in chunks using JavaScript or Typescript? 2: Is it a good idea to upload it from the front-end? Or should i move the logic to backend (Django)? -
Django Url unknown space
My urls.py is urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^chat/', include('chat.urls')) ] And My chat/urls.py is urlpatterns = [ #url(r'^$', views.index, name="index"), url(r'input/$', views.input , name='input'), ] Now when I try to hit the link http://127.0.0.1:8000/chat/input/ i got the error page not found 404. It seems like there is an unknown space are after chat/ input. The Question why these spaces are there and how to remove them Screen shot of error message is here -
Sequence data base with Django?
I am learning Django and creating a Biological Sequence database, contains hundreds of sequences using a model as given bellow, model has two fields, "Seq_ID" and "sequence". I am trying to write a view so that it can render IDs of all the sequences on home page and clicking on a particular IDs it will shows the associated sequence. Model: from __future__ import unicode_literals from django.db import models # Create your models here. class FastaSeq(models.Model): Seq_ID = models.CharField(max_length=20) Sequense = models.TextField() def __unicode__(self): return self.Seq_ID View: from django.shortcuts import render from django.conf import settings def home(request): context = {} template = 'home.html' return render(request, template, context) urls: from django.conf.urls import url from django.contrib import admin from new_app import views as new_app_view urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^home/', new_app_view.home, name='home'), ] Example_Data: Seq_ID: >01_sequence Sequence: LARALLLCAAVVCGAANPCCSHPCQNRGVCMSVGFDQYKCDCTRTGFYGENCTTPEFLTRIKLLLKPTP DTVHYILTHFKGVWNIVNKISFLRNMIMRYVLTSRSHLIESPPTYNVHYSYKSWEAFSNLSYYTRALPPV PDDCPTPMGVKGRKELPDSKEVVKKVLLRRKFIPDPQGTNLMFAFFAQHFTHQFFKTDIERGPAFTKGKN HGVDLSHVYGESLERQHNRRLFKDGKMKYQMINGEMYPPTVKDTQVEMIYPPHIPEHLKFAVGQEVFGLV -
Django TypeError in forms.py
I am deploying my Django app on pythonanywhere.com and get this error while doing signup of user TypeError at /registration/ argument 1 must be str, not list. I am checking if the user already presents in the database then throw validation error in forms.py. The error is suspected due to this code. forms.py class SignUpForm(forms.Form): email = forms.EmailField(max_length=254, help_text='Required. Inform a valid email address.') name = forms.CharField(max_length=100, required=False, help_text='Required.') password = forms.CharField(max_length=1000, required=False, help_text='Required.') role = forms.CharField() def clean(self): cleaned_data = super(SignUpForm, self).clean() name = cleaned_data.get("name") email = cleaned_data.get("email") password = cleaned_data.get("password") role = cleaned_data.get("role") # validate email if role == 'Author': user = UserSignup.objects.filter(email=email) #error suspected here-- if user.first() is not None: raise forms.ValidationError( "Email already registered. Try again.") elif role == 'Publisher': user = PubSignup.objects.filter(email=email) if user.first() is not None: raise forms.ValidationError( "Email already registered. Try again.") class Meta: model = UserSignup fields = ('email', 'name', 'password') views.py if form.is_valid(): if form.role == "Author": p = UserSignup( name=form.cleaned_data.get('name'), email=form.cleaned_data.get('email'), password=form.cleaned_data.get('password') ) p.save() success = True elif form.role == "Publisher": p = PubSignup( name=form.cleaned_data.get('name'), email=form.cleaned_data.get('email'), password=form.cleaned_data.get('password') ) p.save() success = True