Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Allauth: Is it possible to pre-create users with social login before they login to the site for the first time?
I have a site that I want to pre-import a bunch of users, assign them to the right teams, roles, and other setup I have. I want to do this all before they login to the site for the first time. The catch is that the site only supports Social login, I don't want to have any local users. Is it possible to do something like this? My thoughts would be to add users via their email/username (email: test@gmail.com, username: test) and if they login with that email, auto assign them to that pre-created user. I'm not quite sure how to approach it (or if it's even possible), so I wanted to check before I try something and implement it incorrectly. Any thoughts on this are greatly appreciated. -
in python , How to load just one time a ML model in a rest service with django or flask?
I have a ML model saved in a pkl (pickel file), I have no problem loading this model and using it for prediction, even I have a rest service that expose it, the only problem is that I load the model in every request, something like this: https://www.analyticsvidhya.com/blog/2017/09/machine-learning-models-as-apis-using-flask/ I really want that my model just load one time like a global variable and every request useing this variable without the necessity of load the model every request is it possible? -
Need advice on adding model methods to a Django-Rest-Framework url?
I'm working on a DRF CRUD app in which the model takes some fields (a building characteristics) and calculates some parameters using methods defined inside models.py . I have used ModelViewSet and DefaultRouter to make endpoints for listing model objects and details of each one. It's something like this: models.py class Building(models.Model): height=models.FloatField(...) value=models.BigIntegerField(...) #some other fields here def foo(self): #some complicated operations simplified: result=self.value/self.height return result views.py class BuildingViewSet(ModelViewSet): queryset=Building.objects.all() serializer_class=BuildingSerializerList def get_serializer_class(self): if self.action in ['update','partial_update','retrieve']: return BuildingSerializerDetails else: return self.serializer_class urls.py router=DefaultRouter() router.register('Buildings', BuildingViewSet, base_name='building') serializers.py class BuildingSerializerList(serializers.ModelSerializer): class Meta: model=Building fields=['id','name','Value','NSt'] class BuildingSerializerDetails(serializers.ModelSerializer): RRR=serializers.SerializerMethodField() class Meta: model=Building fields='__all__' def get_RRR(self,obj): return obj.foo() Now I get a list of buildings on /buildings/ and get details of a building including calculated parameters on something like /buildings/6/ ,but this configuration has a problem; if an error occurs in calculations (which happens a lot), all the API goes down. So I'm thinking about excluding those parameters from detail-view and making a separate address like /buildings/6/results/ just for that purpose (and it must be a read-only view), but I don't know how to add dynamic address to DefaultRouter. I also tried adding some fields for those parameters, updating them on save() … -
Can a project use django and flask
I have a django project in which I need to implement a payment system, but both Braintree and Stripe only use Flask in their examples. Can I use Flask in this project? If you go to the code under "Dynamic statement descriptor" you will see the comment where they mention the code is using Flask: https://stripe.com/docs/charges -
OperationalError at /infos/ no such table Django while importing an sqlite3 database that works properly in python
I've searched on stackover and Django official website, and other forums, but didn't find the answer that I needed. I have this error while trying to make queries on an imported existing sqlite3 database, given that I don't want to generate a model, I just need to query the exisiting database and knowing that the same code works fine in python. Here is the code and a screenshoot of the OperationalError: Any help will be greatly appreciated! def get_classification_result(carcat): from sklearn.tree import DecisionTreeClassifier tree_object = DecisionTreeClassifier (criterion='entropy', max_depth=3, random_state=0) from sklearn.svm import SVC svm_object = SVC (probability=True) # from sklearn.naive_bayes import GaussianNB # bayes_object = GaussianNB() from sklearn.neural_network import MLPClassifier mlp = MLPClassifier (solver='lbfgs', alpha=1e-5, hidden_layer_sizes=(5, 2), random_state=1) from sklearn.model_selection import cross_val_score DP = np.zeros((3, 20, 2)) database_loc = '..\\Data\\compData.db' database = sqlite3.connect(database_loc) data = database.cursor() start_time = time.time() train_patients_count = 50 test_patients_count = 20 X_array = [] Y_array = [] patientIDs = data.execute('SELECT DISTINCT PatientGuid FROM training_patient').fetchall() # patientIDs is list of all patients # Error happens here!!! os.system("clear") -
Replace multiple variables in a django url tag using js variables
At this moment the way I am doing it is relatively ugly and it is as follow: view.py def some_plot(request, day, team, month, person): data = { "day": day, "team": team, "month": month, "person": person } return render(request, 'some_plot.html', data) and some_plot.html looks like this: let mapObj = { day : "{{ day }}", team : "{{ team }}", month : "{{ month }}", person : "{{ person }}" } d3.json("{% url "my_view_url" day team month person %}".replace(/day|team|month|person/gi, function(matched){ return mapObj[matched]; }), function(data){ # plot stuff Is there a more efficient way to end up with the same result, as this is slightly unreadable. -
What is the impact of adding unique=True to a model field without running a migration?
I made a pretty basic change to one of my django models, altering an existing field to use unique=True. When I run the migration for this, it fails because there is already existing duplicate data for this field. So my question is, what does this mean exactly? Does the column for this field enforce unique=True or does it not? Maybe another way to frame the question is what is the impact of adding unique=True on a field without running the migration? -
calling a view in django again and again
Suppose I have a list of buttons in my django template and I want to change a variable in my database on clicking that button. Here is the code of that template. {% for i in data %} <tr> <td>{{ i.rollno }}</td> <td>{{ i.name }}</td> <td> <a class='btn btn-danger' href='add/{{i.id}}/{{stri}}'> {{stri}} </a> </td> </tr> {% endfor %} Jquery code of this template: $(document).ready(function(){ $(".btn").click(function(){ $(this).toggleClass('btn-success'); $(this).toggleClass('btn-danger'); }); }); The button in above code is a toggle(on/off) button. Therefore, in jquery I wrote a code to switch it on/off. By default all the buttons are in off state. I have called a view every time a button is clicked and then returned this url. But this switches every button in default state ie off state. And because every time the same page is loaded, I am unable to get to the previous page on clicking back button but getting the same page the no of times I called the view. Every button belongs to an IntegerField() in database. I am new to Django. Please suggest me a better way to do this. Maybe I could save the changes in an array and then pass it to view at the time of … -
Count three (or more) many-to-many relations in template
I have three models: class Target(models.Model): fqdn = models.CharField(max_length=100) ports = models.ManyToManyField('Port') class Port(models.Model): status = models.CharField(max_length=20) services = models.ManyToManyField('Service') class Service(models.Model): name = models.CharField(max_length=200) vuls = models.ManyToManyField('Vul') class Vul(models.Model): code = models.CharField(max_length=100) name = models.CharField(max_length=200) and a Template, where I want to count the vuls for a specific Target: {% for t in targets %} Target: {{ t.fqdn }} Count Vuls: {{ t.ports.services.vuls.count() }} {% endfor %} If I count the ports: t.ports.count there is no problem ... But how counting "over" more than one many-to-many-relations? -
Django - How to take a value of a object in a foreignkey using a filter
First of all sorry for my bad english. I have a problem to access to an specific value to show in a template. Actually I can't figure the way to do it. I need to show information about products in a template, the problem is that the product full info is stored in 3 different models, Products, ProductStock, ProductPrice I can access to 2 of them ProductStock and from there i access to Product. But i need the values in ProductPrice too. This are the models The Product Model class Product(models.Model): # Relations supplier = models.ForeignKey( Supplier, verbose_name=_('supplier'), on_delete=CASCADE, ) manufacturer = models.ForeignKey( Manufacturer, verbose_name=_('manufacturer'), on_delete=CASCADE, ) family = models.ForeignKey( Family, verbose_name=_('family'), on_delete=CASCADE, ) category = ChainedForeignKey( Category, chained_field='family', chained_model_field='family', auto_choose=True, verbose_name=_('category'), ) subcategory = ChainedForeignKey( Subcategory, chained_field='category', chained_model_field='category', auto_choose=True, verbose_name=_('subcategory'), ) condition = models.ForeignKey( ProductCondition, default=1, verbose_name=_('condition'), on_delete=CASCADE, ) # Attributes - Mandatory name = models.CharField( max_length=63, unique=True, verbose_name=_('name'), ) slug = models.SlugField( max_length=63, unique=True, editable=False, verbose_name=_('slug'), ) product_code = models.CharField( max_length=20, verbose_name=_('product code'), unique=True, null=True, blank=True, ) ... ... The ProductStock Model class ProductStock(models.Model): # Relations product = models.ForeignKey( Product, related_name='product_stock', verbose_name=_('product'), on_delete=CASCADE, ) warehouse = models.ForeignKey( Warehouse, default=1, verbose_name=_('warehouse'), on_delete=CASCADE, ) # Attributes - Mandatory quantity = … -
Beanstalk doesn't run container_commands commands upon django app deployment
I'm running into a dead end and this is driving me crazy. Beanstalk is not running my the container_commands inside my config file, thus I'm unable to make migrations to my django project and update my models. Attached is the part inside my config file. The more frustrating thing is that it doesn't raise any error upon deployment or leave any trace in log, the container commands simple don't get called. container_commands: 01_migrate: command: 'source /opt/python/run/venv/bin/activate && django-admin.py makemigrations' command: 'source /opt/python/run/venv/bin/activate && django-admin.py migrate' leader_only: true If anyone can provide some insights into this it would be greatly appreciated -
Disable pylint warning E1101 when using enums
I recently came across this article by Anthony Fox which shows how to use enums to create the choice set in django CharFields, which I thought was pretty neat. Basically, you create a subclass of Enum: from enum import Enum class ChoiceEnum(Enum): @classmethod def choices(cls): return tuple((x.name, x.value) for x in cls) Which can then be used in your models like so: from .utils import ChoiceEnum class Car(models.Model): class Colors(ChoiceEnum): RED = 'red' WHITE = 'white' BLUE = 'blue' color = models.CharField(max_length=5, choices=Colors.choices(), default=Colors.RED.value) red_cars = Car.objects.filter(color=Car.Colors.RED.value) However, pylint throws a warning whenever you try to access the enum value (Colors.RED.value) E1101:Instance of 'str' has no 'value' member Is there a way to avoid / disable this warning for every instance of ChoiceEnum? This answer only works on the subclass of ChoiceEnum, not ChoiceEnum itself. -
Lock action vote after a deadline time, unlock when editing the instance voted in Django
As I say in the title, I want to allow a user to vote on an instance named, Course and lock the vote after 72 hours or 3 days (In my example, it will be 2 minutes). Where I get stuck is that I want to allow users to edit vote if the course has been edited by its owner. When a course being edited, all its votes must be unlocked. How bad today is, All the logic are gone, I can't think anymore, already tear off multiple sheets of paper! So far, I can lock a vote, I mean I think I lock it. ''' stuff ''' if vote: NOW = datetime.datetime.now() DEADLINE = 2 # minutes # if (vote.date_edited - course.date_edited).total_seconds() < (DEADLINE * 60): if (NOW - course.date_edited).total_seconds() < (DEADLINE * 60): vote.amount = amount vote.save() else: vote = Vote.objects.create( user = user, amount = amount, content_object = course, ) date_edited for the the 2 models are set to auto_now_add = True in db I think another approach is to edit the date for all the votes for a course when editing it, like: course.votes.all().update(date_voted=....) # I am not sure let me know how to do it. … -
Create search field to sort for each column data
I am new to Django, my index page shows all projects including project_number column, project_description column and so on. I would like to have search field in every column if I search for project description, it will display project description results along with theirs project_number in the same page and vice versa. Could someone give me just the way to go with, since I didnt know what path I should go. -
After brew update, virtualenvwrapper and mySQL got issues
yesterday I updated homebrew and today, when I open a terminal, I got this error: /usr/bin/python: No module named virtualenvwrapper virtualenvwrapper.sh: There was a problem running the initialization hooks. If Python could not import the module virtualenvwrapper.hook_loader, check that virtualenvwrapper has been installed for VIRTUALENVWRAPPER_PYTHON=/usr/bin/python and that PATH is set properly. The problem is that my virtualenvwrapper.sh file IS in the path specified (/usr/bin/python). Meanwhile, in ALL my Django project folders, I can source the virtualenv but if I run: python manage.py runserver I get: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Users/marta/work/job/qs4b/qs4bmg/.virtualenv/lib/python2.7/site-packages/_mysql.so, 2): Library not loaded: /usr/local/opt/mysql/lib/libmysqlclient.20.dylib Referenced from: /Users/marta/work/job/qs4b/qs4bmg/.virtualenv/lib/python2.7/site-packages/_mysql.so Reason: image not found Did you install mysqlclient or MySQL-python? The mysql library is listed when I do: pip freeze [..] MySQL-python==1.2.5 [..] What's going on? Thank you for any help you could provide -
Django get a queryset and filter by own queryset item
first of all, I cant find the way to explain what I'm intend to do properly so I'll try to do it the best way I can, hope it make sense to you. I'm trying to display on my index page a list of items that meet a certain criteria. I am creating an inventory app and I want to get a list of all items that need to be resupplied. views.py def index(request): template_name = 'inventario/index.html' model = Item # GETS ALL ALCTIVE ITEMS articulos = Item.objects.all().filter(activo=True) for i in articulos: # PRINTS THE VALUE OF 'cantidad_existente' AND 'cantidad_minima' ON EACH ITERATION print(F'--->>>>>>{i.cantidad_existente}<<<<<<<---CANTIDAD EXISTENTE') print(F'--->>>>>>{i.cantidad_minima}<<<<<<<---CANTIDAD MINIMA') # TRIES TO GET FILTERD VALUE FOR EACH ITEM articulo = Item.objects.filter(cantidad_existente__lte=i.cantidad_minima) print(F'--->>>>>>{articulo}<<<<<<<---') # print(F'--->>>>>>{articulo}<<<<<<<---') return render(request, template_name)#, {'items': items}) results in terminal --->>>>>>6<<<<<<<---CANTIDAD EXISTENTE --->>>>>>20<<<<<<<---CANTIDAD MINIMA --->>>>>><QuerySet [<Item: Rondana 1/8>, <Item: Cortador Carburo 1/8>]><<<<<<<--- --->>>>>>2<<<<<<<---CANTIDAD EXISTENTE --->>>>>>5<<<<<<<---CANTIDAD MINIMA --->>>>>><QuerySet [<Item: Cortador Carburo 1/8>]><<<<<<<--- So I can see that every iteration brings back cantidad_minima and cantidad_existente for each item in the queryset. My reasoning is that every iteration it would query my database bring back my result i wanted but its not. what am i doing wrong and how can i go about … -
How can I make some image processes on video stream from html page
I have a python project in which I get video stream from webcam and make some further image process on it, and I want to turn this project to a web application one, using Django. To do so, I can access my webcam video stream, thanks to such helpful link Accessing Your Webcam in HTML, but what I really need is to feed the video stream to my project and show the output stream in a HTML page. I would appreciate any advice and suggestions. -
django angular load static files - image in assets folder get 404
i have a assets/image folder in angular src folder and i left all of my image there, i have many component and child component that used that are using that images like <img src"../../../assets/image/test.png">, i build my angular app and place all files to static folder , in nginx i point it to load from static folder and in django in template i used index.html to load the static files like below: now my app will run but no file that have address like "../../../file" in angular load all get 404 like this : http://hello.com/bird.65c8b9bce67b6a965a9c.png (error 404) if i put a static keyword front of address it like http://hello.com/static/bird.65c8b9bce67b6a965a9c.png image will load .. how can i handle this issue? {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title> site </title> <base href="/"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="icon" type="image/x-icon" href="{% static 'favicon.png' %}"> <link rel="stylesheet" href="{% static 'styles.921a613cd46f44e0d5a0.css' %}"></head> <body> <app-root>Loading . . .</app-root> <script type="text/javascript" src="{% static 'runtime.6afe30102d8fe7337431.js' %}"></script> <script type="text/javascript" src="{% static 'polyfills.b0205464c9bd4e7fe3b3.js' %}"></script> <script type="text/javascript" src="{% static 'scripts.59ed76cc23ba77b0ec72.js' %}"></script> <script type="text/javascript" src="{% static 'main.08947dd689f13d4027ea.js' %}"></script> </body> </html> also i aleady added urlpatterns += static(base.STATIC_URL, document_root=base.STATIC_ROOT) + \ static(base.MEDIA_URL, document_root=base.MEDIA_ROOT) to end of my urls.py … -
DocuSign Python SDK - Retrieve newly generated document to sign?
this is my first post on Stackoverflow, so I'll do my best to stick with the community guidelines on this. I am attempting to integrate DocuSign's Python SDK into my Django project. I am generating a PDF form based on entries that are created by the user entering information using Weasyprint. Is it possible for me to take the newly generated PDF, containing the information that is entered by the user, and use that to send to the user to sign? Specifically, how do I use the newly generated document with the SDK? user_name = "myaccount@sample-email.com" #I'm assuming this is my account on Docusign? integrator_key = "my integrator key" base_url = "https://demo.docusign.net/restapi" oauth_base_url = "account-d.docusign.com" redirect_uri = "https://www.docusign.com/api" private_key_filename = "keys/docusign_private_key.txt" user_id = "" #Same as the username? template_id = "" #Can this file be from my local machine? api_client = docusign.ApiClient(base_url) oauth_login_url = api_client.get_jwt_uri(integrator_key, redirect_uri, oauth_base_url) print(oauth_login_url) api_client.configuire_jwt_authorization_flow(private_key_filename, oauth_base_url, integrator_key, user_id, 3600) docusign.configuration.api_client = api_client template_role_name = 'Needs to sign' #create an envelope to be signed envelope_definition = docusign.EnvelopeDefinition() envelope_definition.email_subject = 'Please sign the following document' envelope_definition.email_blurb = 'Thank you for filling out your information, please sign the following document to complete the process:' #assign template information including ID … -
OnetoOnefield in django form not working.
I have created UserForm that has OnetoOnefield of User built-in Form. UserForm has description,city,website,phone,image class UserForm(forms.ModelForm): description = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Description','default':"{{user.userprofile.description}}"}), required=False, max_length=100) city = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'City:'}), required=False, max_length=70) website = forms.URLField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Website:'}), required=False, max_length=100) phone = forms.CharField( widget=forms.TextInput(attrs={'class': 'form-control', 'placeholder': 'Phone:'}), required=False, max_length=10) image = forms.ImageField(label='Select a profile picture') class Meta(): model = UserProfile fields = ['description','city','website','phone','image'] views.py def edit_profile(request): if request.method == 'POST': form = UserForm(request.POST) if form.is_valid(): messages.success(request,"description added successfully") form.save() return HttpResponseRedirect('/profile/') else: messages.error(request,"") else: form = UserForm() return render(request, 'edit_profile.html', {'form': form}) models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) description = models.CharField(max_length=100, default='No description field') city = models.CharField(max_length=100, default='Location not added') website = models.URLField(default='', blank=True) phone = models.CharField(max_length=10, default='',blank= True) image = models.ImageField(upload_to='products/profile/%Y%/%m/%d', blank=True) def __str__(self): return self.user.username def create_profile(sender,**kwargs): if kwargs['created']: user_profile = UserProfile.objects.create(user = kwargs['instance']) post_save.connect(create_profile,sender=User) admin.py admin.site.register(UserProfile) The problem is, whenever i try to enter values in form and click submit it doesn't to anything it refreshes form and says the field is required at image field. any solution please? thanks P.S values can be stored through admin panel. -
How to log django requests in the same file as the other log messages when in production environment?
In development, I'm fine. Using development server provided by django (runserver), my django logs contain the actual request (e.g., GET /api/user/register) and my INFO and ERROR log messages. This is exactly what I want. When I go into production I use django with nginx. The requests are now separated into the nginx-access.log file, and my django logs no longer contain the request. So there is now no GET /api/user/register . How do I keep the requests in the django log in production just like the used to be during development? I want it all in one file. It's ok if nginx-access.log keeps an additional copy of the requests. I realize the convention is to keep the access records separate, but it's helpful to me when I know immediately what api call the user made. Any hints? Do I alter django settings.py or my nginx configuration? Thank you! -
D3 js Mixed Content warning
I tried changing the url to my json data and out of nowhere, I get the following warning: Mixed Content: The page at 'https://localhost/my-link' was loaded over a secure connection, but contains a form that targets an insecure endpoint 'http://dpaste.com/'. This endpoint should be made available over a secure connection. I am trying to access the url in my views.py, which looks as follow: url(r'json/(?P<data_type>full|half|third)/(?P<year>[0-9]{4})-(?P<month>[0-9]{1,2})', data, name='data'), url(r'plot/((?P<data_type>full|half|third)/(?P<year>[0-9]{4})-(?P<month>[0-9]{1,2})', plot, name='plot'), where data is a view, which returns a json file and plot is a view, which is for d3.js chart. The view for the d3.js chart is as follow: def plot(request, year, month, data_type): context = { "year": year, "month": month, "data_type": data_type } return render(request, 'plot.html', context=context) In the plot.html template, which includes d3.js and dimple.js, I access the json file as follow: var year = "{{ year }}"; var month = "{{ month }}"; var data_type = "{{ data_type }}"; d3.json("{% url "data" part %}".replace("part", data_type.toStrint()+"/"+year.toString()+"-"+month.toString()), function(data){ // chart code which works }; My question is, why is the endpoint http://dpaste.com when I haven't used this anywhere? -
Django test client get returns 404 however works in shell and web browser
Can you help me, please. I am going through the Django beginners course (https://github.com/sibtc/django-beginners-guide) and can't figure out why the test cases from the examples are always returning error 404, even though works perfectly in the shell or web browser. I'm running Python 3.5.3, Django version: 2.0.7 Code: url.py: from django.contrib import admin from django.urls import path from boards import views as boards_views urlpatterns = [ path('', boards_views.home, name='home'), path('boards/<int:pk>/', boards_views.board_topics, name='board_topics'), path('admin/', admin.site.urls), ] views.py: from django.shortcuts import render, get_object_or_404 from .models import Board # Create your views here. def home(request): boards = Board.objects.all() return render(request, 'home.html', {'boards': boards}) def board_topics(request, pk): board = get_object_or_404(Board, pk=pk) return render(request, 'topics.html', {'board': board}) Tests.py: from django.test import TestCase from django.urls import resolve, reverse from django.test.client import Client from .views import home, board_topics from .models import Board # Create your tests here. class BoardTopicsTests(TestCase): def setUp(self): Board.objects.create(name='Django', description='Django board.') def test_board_topics_view_success_status_code(self): url = reverse('board_topics', kwargs={'pk': 1}) print('url = ' + str(url)) response = self.client.get(url) self.assertEquals(response.status_code, 200) This test is always returning 404 error, even though i can see with print statements in this test, that DB entry exists and url is correct. Thanks! -
Is save() method of Model = apps.get_model('myapp', 'MyModel') and MyModel the same?
Django-simple-history writing history changes on instance.save() method. But when i wrote migration which change instance data, the changes did not appear. Is the save() method of Model = apps.get_model('myapp', 'MyModel') and MyModel the same? Is there a way to wrote this changes to history? -
Django - super(ModelForm, self).clean() without raising ValidationError
I am trying to implement a special trick in my validation. I want the program to raise a ValidationError only when two fields are both invalid. One is a field for email, thus being an emailField in the model. The other one is for phone number and is a CharField in the model. models.py ... email = models.EmailField(max_length=128, blank=True, null=True) telephone = models.CharField(max_length=32, blank=True, null=True) ... In forms.py I am using the built-in clean for email and building a custom one for phone numbers. forms.py def clean(self): cleaned_data=super(ContactInstructorForm, self).clean() try: email = self.cleaned_data['email'] except: email = False telephone = self.cleaned_data['telephone'] mobile_regex = r'^(\+46|0|\(\+46\)) *(7[0236])( |-|)(\d{4} \d{3}|\d{3} \d{4}|\d{3} \d{2} \d{2}|\d{2} \d{2} \d{3}|\d{7})$' home_phone_regex = r'^(\+46|0|\(\+46\)) *(8)( |-|)(\d{4} \d{2}|\d{2} \d{4}|\d{3} \d{3}|\d{2} \d{2} \d{2}|\d{6})$' if not re.match(mobile_regex, telephone) and not re.match(home_phone_regex, telephone): telephone = False if not email and not telephone: raise ValidationError() However, the problem is that the built-in clean() method not only returns a dictionary of all validated fields and their values. But upon failure also automatically raises an ValidationError. This causes my program to fail when only the inputted email is invalid (even though the phone number is fine) This behaviour is unwanted! So ultimately I am asking what the …