Please see the code below. Basically, when the user creates an object of this class, they need to specify the value_type. If value_type==2 (percentage), then percentage_calculated_on (which is a CheckboxSelectMultiple on the form/template side needs to have one or more items checked. The model validation isn't allowing me to validate like I'm trying to -- it basically throws an exception that tells me that the instance needs to have a primary key value before a many-to-many relationship can be used. But I need to first validate the object before saving it. I have tried this validation on the form (modelform) side (using the form's clean method), but the same thing happens there too.
How do I go about achieving this validation?
INHERENT_TYPE_CHOICES = ((1, 'Payable'), (2, 'Deductible'))
VALUE_TYPE_CHOICES = ((1, 'Amount'), (2, 'Percentage'))
class Payable(models.Model):
name = models.CharField()
short_name = models.CharField()
inherent_type = models.PositiveSmallIntegerField(choices=INHERENT_TYPE_CHOICES)
value = models.DecimalField(max_digits=12,decimal_places=2)
value_type = models.PositiveSmallIntegerField(choices=VALUE_TYPE_CHOICES)
percentage_calculated_on = models.ManyToManyField('self', symmetrical=False)
def clean(self):
from django.core.exceptions import ValidationError
if self.value_type == 2 and not self.percentage_calculated_on:
raise ValidationError("If this is a percentage, please specify on what payables/deductibles this percentage should be calculated on.")
I tested out your code in one of my projects' admin app. I was able to perform the validation you required by using a custom ModelForm. See below.
# forms.py
class MyPayableForm(forms.ModelForm):
class Meta:
model = Payable
def clean(self):
super(MyPayableForm, self).clean() # Thanks, #chefsmart
value_type = self.cleaned_data.get('value_type', None)
percentage_calculated_on = self.cleaned_data.get(
'percentage_calculated_on', None)
if value_type == 2 and not percentage_calculated_on:
message = "Please specify on what payables/deductibles ..."
raise forms.ValidationError(message)
return self.cleaned_data
# admin.py
class PayableAdmin(admin.ModelAdmin):
form = MyPayableForm
admin.site.register(Payable, PayableAdmin)
The Admin app uses the SelectMultiple widget (rather than CheckboxSelectMultiple as you do) to represent many to many relationships. I believe this shouldn't matter though.
Related
I'm building models for a project in DJANGO 4, but I got stuck when it came to CONVERTING FIELD VALUES OF AN EXISTING MODEL INTO THE FIELD NAMES OF A NEW ONE (MODEL).
As may be seen from the image I do attach, I have MODEL A with 'fieldName_3'. I'd appreciate a help to convert the values of this field into the field names of the MODEL B.
Descriptive Image
My advancing thanks!
from django.db import models
CHOICES = (('option1','option1'),('option2','option2'))
class Model_A(models.Model):
fieldName_1 = models.CharField(max_length=50)
fieldName_2 = models.CharField(max_length=20)
fieldName_3 = models.CharField(max_length=3)
class Model_B(models.Model):
def values_from_fildName3():
values = Model_A.fieldName_3
for value in values:
value = models.CharField(max_length=4, choices=CHOICES)
yield value
With the code above I get the error "TypeError: 'DeferredAttribute' object is not iterable"
Try This correction in a more modern approach based on the code you showed above.
from django.core.exceptions import ValidationError
from django.db import models
CHOICES = (("option1", "Option 1"), ("option2", "Option 2"))
class Model_A(models.Model):
field_name_1 = models.CharField(max_length=50)
field_name_2 = models.CharField(max_length=20)
field_name_3 = models.CharField(max_length=3)
class Model_B(models.Model):
field_name_3_choices = models.CharField(max_length=4, validators=[])
def clean(self):
super().clean()
field_name_3_values = (
obj.field_name_3
for obj in Model_A.objects.only("field_name_3").distinct()
)
if self.field_name_3_choices not in field_name_3_values:
raise ValidationError(
f"{self.field_name_3_choices} is not a valid value for field_name_3_choices."
)
def save(self, *args, **kwargs):
self.full_clean()
super().save(*args, **kwargs)
In this code, the staticmethod decorator has been removed from values from field name 3() and replaced with an empty list as the initial value of the validators parameter for the field name 3 choices field in Model B. This instructs Django to use no validators by default for the field.
I've also defined a custom clean() method for Model B that calls the parent clean() method and then determines if the value of field name 3 choices is among the list of unique values for field name 3 in Model A. If the value is invalid, the ValidationError exception is thrown.
Lastly, I've overridden the save() method to call full clean() prior to calling the parent method save(). This ensures the custom validation is performed prior to saving the object.
This method should allow you to validate the field name 3 choices options using Model A's values without having to define a separate staticmethod.
I'm trying to learn Django and I've ran into some confusing points. I'm currently having trouble creating a movie using a form. The idea of the form is to give the user any field he'd like to fill out. Any field that the user fills out will be updated in its respective sql table (empty fields will be ignored). But, the form keeps giving me the error "Enter a list of values" when I submit the form. To address this, I thought stuffing the data from the form into a list and then returning that list would solve this.
The first idea was to override the clean() in my ModelForm. However, because the form fails the is_valid() check in my views, the cleaned_data variable in clean() doesn't contain anything. Next, I tried to override the to_python(). However, to_python() doesn't seem to be called.
If I put __metaclass__ = models.SubfieldBase in the respective model, I receive the runtime error
"TypeError: Error when calling the
metaclass bases
metaclass conflict: the metaclass of a derived class must be a
(non-strict) subclass of the
metaclasses of all its bases"
My approach doesn't seem to work. I'm not sure how to get around the 'Enter a list of values" error! Any advice?
Here is the relevant code (updated):
models.py
""" Idea:
A movie consists of many equipments, actors, and lighting techniques. It also has a rank for the particular movie, as well as a title.
A Theater consists of many movies.
A nation consists of many theaters.
"""
from django.db import models
from django.contrib.auth.models import User
class EquipmentModel(models.Model):
equip = models.CharField(max_length=20)
# user = models.ForeignKey(User)
class ActorModel(models.Model):
actor = models.CharField(max_length=20)
# user = models.ForeignKey(User)
class LightModel(models.Model):
light = models.CharField(max_length=20)
# user = models.ForeignKey(User)
class MovieModel(models.Model):
# __metaclass__ = models.SubfieldBase
rank = models.DecimalField(max_digits=5000, decimal_places=3)
title = models.CharField(max_length=20)
equipments = models.ManyToManyField(EquipmentModel, blank=True, null=True)
actors = models.ManyToManyField(ActorModel, blank=True, null=True)
lights = models.ManyToManyField(LightModel, blank=True, null=True)
class TheaterModel(models.Model):
movies = models.ForeignKey(MovieModel)
class NationModel(models.Model):
theaters = models.ForeignKey(TheaterModel)
=====================================
forms.py
"""
These Modelforms tie in the models from models.py
Users will be able to write to any of the fields in MovieModel when creating a movie.
Users may leave any field blank (empty fields should be ignored, ie: no updates to database).
"""
from django import forms
from models import MovieModel
from django.forms.widgets import Textarea
class MovieModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MovieModelForm, self).__init__(*args, **kwargs)
self.fields["actors"].widget = Textarea()
self.fields["equipments"].widget = Textarea()
self.fields["lights"].widget = Textarea()
def clean_actors(self):
data = self.cleaned_data.get('actors')
print 'cleaning actors'
return [data]
class Meta:
model = MovieModel
=============================================
views.py
""" This will display the form used to create a MovieModel """
from django.shortcuts import render_to_response
from django.template import RequestContext
from forms import MovieModelForm
def add_movie(request):
if request.method == "POST":
form = MovieModelForm(request.POST)
if form.is_valid():
new_moviemodel = form.save()
return HttpResponseRedirect('/data/')
else:
form = MovieModelForm()
return render_to_response('add_movie_form.html', {form:form,}, context_instance=RequestContext(request))
The probable problem is that the list of values provided in the text area can not be normalized into a list of Models.
See the ModelMultipleChoiceField documentation.
The field is expecting a list of valid IDs, but is probably receiving a list of text values, which django has no way of converting to the actual model instances. The to_python will be failing within the form field, not within the form itself. Therefore, the values never even reach the form.
Is there something wrong with using the built in ModelMultipleChoiceField? It will provide the easiest approach, but will require your users to scan a list of available actors (I'm using the actors field as the example here).
Before I show an example of how I'd attempt to do what you want, I must ask; how do you want to handle actors that have been entered that don't yet exist in your database? You can either create them if they exist, or you can fail. You need to make a decision on this.
# only showing the actor example, you can use something like this for other fields too
class MovieModelForm(forms.ModelForm):
actors_list = fields.CharField(required=False, widget=forms.Textarea())
class Meta:
model = MovieModel
exclude = ('actors',)
def clean_actors_list(self):
data = self.cleaned_data
actors_list = data.get('actors_list', None)
if actors_list is not None:
for actor_name in actors_list.split(','):
try:
actor = Actor.objects.get(actor=actor_name)
except Actor.DoesNotExist:
if FAIL_ON_NOT_EXIST: # decide if you want this behaviour or to create it
raise forms.ValidationError('Actor %s does not exist' % actor_name)
else: # create it if it doesnt exist
Actor(actor=actor_name).save()
return actors_list
def save(self, commit=True):
mminstance = super(MovieModelForm, self).save(commit=commit)
actors_list = self.cleaned_data.get('actors_list', None)
if actors_list is not None:
for actor_name in actors_list.split(","):
actor = Actor.objects.get(actor=actor_name)
mminstance.actors.add(actor)
mminstance.save()
return mminstance
The above is all untested code, but something approaching this should work if you really want to use a Textarea for a ModelMultipleChoiceField. If you do go down this route, and you discover errors in my code above, please either edit my answer, or provide a comment so I can. Good luck.
Edit:
The other option is to create a field that understands a comma separated list of values, but behaves in a similar way to ModelMultipleChoiceField. Looking at the source code for ModelMultipleChoiceField, it inhertis from ModelChoiceField, which DOES allow you to define which value on the model is used to normalize.
## removed code because it's no longer relevant. See Last Edit ##
Edit:
Wow, I really should have checked the django trac to see if this was already fixed. It is. See the following ticket for information. Essentially, they've done the same thing I have. They've made ModelMutipleChoiceField respect the to_field_name argument. This is only applicable for django 1.3!
The problem is, the regular ModelMultipleChoiceField will see the comma separated string, and fail because it isn't a List or Tuple. So, our job becomes a little more difficult, because we have to change the string to a list or tuple, before the regular clean method can run.
class ModelCommaSeparatedChoiceField(ModelMultipleChoiceField):
widget = Textarea
def clean(self, value):
if value is not None:
value = [item.strip() for item in value.split(",")] # remove padding
return super(ModelCommaSeparatedChoiceField, self).clean(value)
So, now your form should look like this:
class MovieModelForm(forms.ModelForm):
actors = ModelCommaSeparatedChoiceField(
required=False,
queryset=Actor.objects.filter(),
to_field_name='actor')
equipments = ModelCommaSeparatedChoiceField(
required=False,
queryset=Equipment.objects.filter(),
to_field_name='equip')
lights = ModelCommaSeparatedChoiceField(
required=False,
queryset=Light.objects.filter(),
to_field_name='light')
class Meta:
model = MovieModel
to_python AFAIK is a method for fields, not forms.
clean() occurs after individual field cleaning, so your ModelMultipleChoiceFields clean() methods are raising validation errors and thus cleaned_data does not contain anything.
You haven't provided examples for what kind of data is being input, but the answer lies in form field cleaning.
http://docs.djangoproject.com/en/dev/ref/forms/validation/#cleaning-a-specific-field-attribute
You need to write validation specific to that field that either returns the correct data in the format your field is expecting, or raises a ValidationError so your view can re-render the form with error messages.
update: You're probably missing the ModelForm __init__ -- see if that fixes it.
class MovieModelForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(MovieModelForm, self).__init__(*args, **kwargs)
self.fields["actors"].widget = Textarea()
def clean_actors(self):
data = self.cleaned_data.get('actors')
# validate incoming data. Convert the raw incoming string
# to a list of ids this field is expecting.
# if invalid, raise forms.ValidationError("Error MSG")
return data.split(',') # just an example if data was '1,3,4'
I have a complex django object, which has properties of other class types. This gets like this:
class Order:
contractor - type Person
some other fields....
In my form I'd like to be able to either choose existing Person object from the dropdown or add a new one with a form. I've managed to create forms and appropriate workflow, but the problem is with saving the Order itself, I simply can't get the id of a saved Person instance. I'm doing sth like this:
def make_order(request):
if request.method == 'POST':
parameters = copy.copy(request.POST)
contractor_form = ContractorForm(parameters)
if contractor_form.is_valid():
contractor_form.save()
parameters['contractor'] = ???
form = OrderForm(parameters)
if form.is_valid():
form.save()
return HttpResponseRedirect('/orders/')
else:
form = OrderForm()
contractor_form = ContractorForm()
return render_to_response('orders/make_order.html', {'order_form' : form, 'contractor_form' : contractor_form})
So, if POST request reaches this method I first check if ContractorForm have been filled - I assume that if the form is valid, it is meant to be used. If yes, than I save it and would like to assign the saved object's database id to appropriate field for OrderForm to find it.
All my forms are ModelForms.
The questions are:
Are there better ways to do this? (choose from dropdown or add in place) - better or more pythonic ;-)
How can I get saved objects id when using ModelForms?
Edited
My ContractorForm is:
class ContractorForm(ModelForm):
class Meta:
model = Contractor
Nothing fancy.
save() should return the newly created instance.
if contractor_form.is_valid():
instance = contractor_form.save()
parameters['contractor'] = instance
where id would be instance.id, or even better instance.pk.
pk vs. id:
Regardless of whether you define a
primary key field yourself, or let
Django supply one for you, each model
will have a property called pk. It
behaves like a normal attribute on the
model, but is actually an alias for
whichever attribute is the primary key
field for the model. You can read and
set this value, just as you would for
any other attribute, and it will
update the correct field in the model.
Follow-up on comment:
Well it does work by default, so there must be something else wrong.
models.py
class Category(models.Model):
name = models.CharField(max_length=70)
slug = models.SlugField()
forms.py
from django import forms
from models import Category
class MyModelForm(forms.ModelForm):
class Meta:
model = Category
Test in shell:
In [3]: from katalog.forms import MyModelForm
In [4]: data = {'name':'Test', 'slug':'test'}
In [5]: form = MyModelForm(data)
In [6]: instance = form.save()
In [7]: instance
Out[7]: <Category: Test>
In [8]: instance.id
Out[8]: 5L
I want to make a form used to filter searches without any field being required. For example given this code:
models.py:
class Message(models.Model):
happened = models.DateTimeField()
filename = models.CharField(max_length=512, blank=True, null=True)
message = models.TextField(blank=True, null=True)
dest = models.CharField(max_length=512, blank=True, null=True)
fromhost = models.ForeignKey(Hosts, related_name='to hosts', blank=True, null=True)
TYPE_CHOICES = ( (u'Info', u'Info'), (u'Error', u'Error'), (u'File', u'File'), (u'BPS', u'BPS'),)
type = models.CharField(max_length=7, choices=TYPE_CHOICES)
job = models.ForeignKey(Jobs)
views.py:
WHEN_CHOICES = ( (u'', ''), (1, u'Today'), (2, u'Two days'), (3, u'Three Days'), (7, u'Week'),(31, u'Month'),)
class MessageSearch(ModelForm): #Class that makes a form from a model that can be customized by placing info above the class Meta
message = forms.CharField(max_length=25, required=False)
job = forms.CharField(max_length=25, required=False)
happened = forms.CharField(max_length=14, widget=forms.Select(choices=WHEN_CHOICES), required=False)
class Meta:
model = Message
That's the code I have now. As you can see it makes a form based on a model. I redefined message in the form because I'm using an icontains filter so I didn't need a giant text box. I redefined the date mostly because I didn't want to have to mess around with dates (I hate working with dates! Who doesnt?) And I changed the jobs field because otherwise I was getting a drop down list of existing jobs and I really wanted to be able to search by common words. So I was able to mark all of those as not required
The problem is it's marking all my other fields as required because in the model they're not allowed to be blank.
Now in the model they can't be blank. If they're blank then the data is bad and I don't want it in the DB. However the form is only a filter form on a page to display the data. I'm never going to save from that form so I don't care if fields are blank or not. So is there an easy way to make all fields as required=false while still using the class Meta: model = Message format in the form? It's really handy that I can make a form directly from a model.
Also this is my first serious attempt at a django app so if something is absurdly wrong please be kind :)
You can create a custom ModelForm that suit your needs. This custom ModelForm will override the save method and set all fields to be non-required:
from django.forms import ModelForm
class SearchForm(ModelForm):
def __init__(self, *args, **kwargs):
super(SearchForm, self).__init__(*args, **kwargs)
for key, field in self.fields.iteritems():
self.fields[key].required = False
So you could declare your forms by simply calling instead of the ModelForm, e.g.:
class MessageForm(SearchForm):
class Meta:
model = Message
You could also pass empty_permitted=True when you instantiate the form, e.g.,
form = MessageSearch(empty_permitted=True)
that way you can still have normal validation rules for when someone does enter data into the form.
I would give a try to the django-filter module :
http://django-filter.readthedocs.io/en/develop/
fields are not required. these are filters actually. It would look like this :
import django_filters
class MessageSearch(django_filters.FilterSet):
class Meta:
model = Message
fields = ['happened', 'filename', 'message', '...', ]
# django-filter has its own default widgets corresponding to the field
# type of the model, but you can tweak and subclass in a django way :
happened = django_filters.DateFromToRangeFilter()
mandatory, hidden filters can be defined if you want to narrow a list of model depending on something like user rights etc.
also : setup a filter on a 'reverse' relationship (the foreignkey is not in the filtered model : the model is referenced elsewhere in another table), is easy, just name the table where the foreign key of the filtered model field is :
# the 'tags' model has a fk like message = models.ForeignKey(Message...)
tags= django_filters.<some filter>(name='tags')
quick extendable and clean to setup.
please note I didn't wrote this module, I'm just very happy with it :)
I need to add extra validation to my DateField in Admin to make sure the date given is in the future. I have no experience in such a thing, so here's what I've done.
1) I've created custom form field and added validation to it:
class PastDateField(forms.DateField):
def clean(self, value):
"""Validates if only date is in the past
"""
if not value:
raise forms.ValidationError('Plase enter the date')
if value > datetime.now():
raise forms.ValidationError('The date should be in the past, not in future')
return value
2) Then I've added custom model form:
class CustomNewsItemAdminForm(forms.ModelForm):
title = forms.CharField(max_length=100)
body = forms.CharField(widget=forms.Textarea)
date = PastDateField()
region = forms.ModelChoiceField(Region.objects)
3) And here's how I've registered admin:
class NewsItemAdmin(admin.ModelAdmin):
form = CustomNewsItemAdminForm
def queryset(self, request):
return NewsItem.objects.all()
admin.site.register(NewsItem, NewsItemAdmin)
The result of this is that my admin form
1) Shows field I haven't specified in custom admin form
2) Lacks JavaScript calendar for the datetime field
It's pretty obvious to me that I'm doing something wrong, but I've found no examples relevant to my needs as I am a noob. What is the better way to add custom validation to datetime field without messing things up?
EDIT: Thanks a lot to Brian Luft and Daniel Roseman for correct answers! To make this post helpful for someone facing the same problem here is the resulting code:
class CustomNewsItemAdminForm(forms.ModelForm):
class Meta:
model = NewsItem
def clean_date(self):
"""Validates if only date is in the past
"""
date = self.cleaned_data["date"]
if date is None:
raise forms.ValidationError('Plase enter the date')
if date > datetime.now().date():
raise forms.ValidationError('The date should be in the past, not in future')
return self.cleaned_data["date"]
class NewsItemAdmin(admin.ModelAdmin):
form = CustomNewsItemAdminForm
def queryset(self, request):
return NewsItem.objects.all()
admin.site.register(NewsItem, NewsItemAdmin)
Firstly, declaring fields explicitly on a ModelForm - whether in or out of the admin - does not mean that the other fields will not be displayed. You need to define the fields or exclude tuples in the form's inner Meta class. If the other fields are all the default, you can simply declare the one you are overriding.
Secondly, if you want your custom field to use the javascript, you'll need to use the right widget, which is django.contrib.admin.widgets.AdminDateWidget. However, there is a much easier way to do this, which is not define a custom field at all, but instead define a clean_date method on the form itself.