I want to make some fields of thwe form required based on the "is_seller" dropdown list . but seller = cleaned_data.get("is_seller") returns None !
these are my codes :
models.py
class UserProfileInfo(models.Model):
user=models.OneToOneField(User,related_name='profile')
companyname=models.CharField(blank=True,null=True, ],max_length=128,verbose_name=_('companyname'))
phone_regex = RegexValidator(regex=r'^\d{11,11}$', message=_(u"Phone number must be 11 digit."))
cellphone = models.CharField(validators=[phone_regex], max_length=17,verbose_name=_('cellphone'))
tel = models.CharField(blank=True,null=True,validators=[phone_regex], max_length=17,verbose_name=_('tel'))
state=models.CharField( max_length=128,verbose_name=_('state'))
city=models.CharField( max_length=128,verbose_name=_('city'))
address=models.CharField(blank=True,null=True, max_length=264,verbose_name=_('address'))
is_seller=models.CharField(blank=True,null=True, max_length=2,verbose_name=_('seller'))
def __str__ (self):
return self.user.username
class Meta:
verbose_name=_('UserProfileInfo')
verbose_name_plural=_('UserProfileInfos')
forms.py :
class UserProfileInfoForm(forms.ModelForm):
CHOICES = (('0','buyer'),
('1','seller'),
('2','both'))
is_seller = forms.CharField(widget=forms.Select(choices=CHOICES),label=_('title'))
companyname=forms.CharField(required=False,widget=forms.TextInput(attrs={'class':'form-control' ,'style': 'width:60%', 'white-space':'nowrap'}),label=_('companyname'))
cellphone = forms.CharField( widget=forms.TextInput(attrs={'class':'form-control' ,'style': 'width:60%'}),label=_('cellphone'))
tel = forms.CharField( widget=forms.TextInput(attrs={'class':'form-control' ,'style': 'width:60%'}),label=_('tel'))
state=forms.CharField(widget=forms.TextInput(attrs={'class':'form-control' ,'style': 'width:60%'}),label=_('state'))
city=forms.CharField( widget=forms.TextInput(attrs={'class':'form-control' ,'style': 'width:60%'}),label=_('city'))
address=forms.CharField(required=False, widget=forms.TextInput(attrs={'class':'form-control' ,'style': 'width:100%'}),label=_('address'))
class Meta():
model=UserProfileInfo
fields=('companyname','tel','cellphone','state','city','address','is_seller')
def clean_companyname(self):
cleaned_data = super(UserProfileInfoForm, self).clean()
seller = cleaned_data.get("is_seller")
print(">>>>>>>>>>>>>>>>>>"+ str(seller))
companyname = self.cleaned_data.get('companyname')
if seller!=0 and companyname=="":
raise forms.ValidationError(u"Required.")
return cleaned_data
This should be in the general clean() method, not clean_companyname().
Related
Models:
class CrewMember(models.Model):
DEPARTMENT_CHOICES = [
("deck", "Deck"),
("engineering", "Engineering"),
("interior", "Interior")
]
first_name = models.CharField(max_length=25)
last_name = models.CharField(max_length=25)
email = models.EmailField()
department = models.CharField(max_length=12, choices=DEPARTMENT_CHOICES)
date_of_birth = models.DateField()
join_date = models.DateField()
return_date = models.DateField(null=True, blank=True)
leave_date = models.DateField(null=True, blank=True)
avatar = models.ImageField(null=True, blank=True)
active = models.BooleanField(default=True)
def __str__(self):
return f"{self.first_name} {self.last_name}"
class RosterInstance(models.Model):
date = models.DateField(default=timezone.now)
deckhand_watchkeeper = models.ForeignKey(CrewMember, on_delete=models.PROTECT, null=True, related_name="deckhand_watches")
night_watchkeeper = models.ForeignKey(CrewMember, on_delete=models.PROTECT, null=True, related_name="night_watches")
def __str__(self):
return self.date.strftime("%d %b, %Y")
Views:
class CrewMemberViewSet(viewsets.ModelViewSet):
queryset = CrewMember.objects.all()
serializer_class = CrewMemberSerializer
filter_backends = [SearchFilter]
search_fields = ["department"]
def destroy(self, request, *args, **kwargs):
instance = self.get_object()
instance.active = False
instance.save()
return Response(status=status.HTTP_204_NO_CONTENT)
class RosterInstanceViewSet(viewsets.ModelViewSet):
queryset = RosterInstance.objects.all()
serializer_class = RosterInstanceSerializer
Serializers:
class CrewMemberSerializer(serializers.ModelSerializer):
class Meta:
model = CrewMember
fields = "__all__"
class RosterInstanceSerializer(serializers.ModelSerializer):
class Meta:
model = RosterInstance
fields = "__all__"
The resulting data looks like this:
{
"id": 2,
"date": "2020-12-09",
"deckhand_watchkeeper": 1,
"night_watchkeeper": 3
}
But I want it to look like this:
{
"id": 2,
"date": "2020-12-09",
"deckhand_watchkeeper": "Joe Soap",
"night_watchkeeper": "John Smith"
}
I can achieve the above output by using StringRelatedField in the RosterInstanceSerializer but then I can no longer add more instances to the RosterInstance model (I believe that is because StringRelatedField is read-only).
Because StringRelaredField is always read_only, you can use SlugRelatedField instead:
class RosterInstanceSerializer(serializers.ModelSerializer):
deckhand_watchkeeper = serializers.SlugRelatedField(
slug_field='deckhand_watchkeeper'
)
night_watchkeeper = serializers.SlugRelatedField(
slug_field='night_watchkeeper'
)
class Meta:
model = RosterInstance
fields = ['id', 'date', 'deckhand_watchkeeper', 'night_watchkeeper']
I was created a WritableStringRelatedField to do that.
class WritableStringRelatedField(serializers.SlugRelatedField):
def __init__(self, display_field=None, *args, **kwargs):
self.display_field = display_field
# Set what attribute to be represented.
# If `None`, use `Model.__str__()` .
super().__init__(*args, **kwargs)
def to_representation(self, obj):
# This function controls how to representation field.
if self.display_field:
return getattr(obj, self.display_field)
return str(obj)
def slug_representation(self, obj):
# It will be called by `get_choices()`.
return getattr(obj, self.slug_field)
def get_choices(self, cutoff=None):
queryset = self.get_queryset()
if queryset is None:
# Ensure that field.choices returns something sensible
# even when accessed with a read-only field.
return {}
if cutoff is not None:
queryset = queryset[:cutoff]
return OrderedDict([
(
self.slug_representation(item),
# Only this line has been overridden,
# the others are the same as `super().get_choices()`.
self.display_value(item)
)
for item in queryset
])
Serializers:
class RosterInstanceSerializer(serializers.ModelSerializer):
deckhand_watchkeeper = WritableStringRelatedField(
queryset=CrewMember.objects.all(),
slug_field='id',
label='Deckhand Watchkeeper',
)
night_watchkeeper = WritableStringRelatedField(
queryset=CrewMember.objects.all(),
slug_field='id',
label='Night Watchkeeper',
)
class Meta:
model = RosterInstance
fields = "__all__"
I'm trying to have my form check if the email field matches the verify_email field in my Django form but it is not working.
My forms.py file:
class SignupForm(ModelForm):
class Meta:
model = FormSubmission
fields ='__all__'
widgets = {'botcatcher': forms.HiddenInput()}
def clean(self):
cleaned_data = super().clean()
email = self.cleaned_data.get('email')
vmail = self.cleaned_data.get('verify_email')
if email != vmail:
raise forms.ValidationError(_("Emails must
match"), code="invalid")
return cleaned_data
My model.py file:
class FormSubmission(models.Model):
first_name = models.CharField(max_length = 30)
last_name = models.CharField(max_length = 30)
email = models.EmailField(unique= False)
verify_email = models.EmailField(unique = False)
text = models.CharField(max_length=250)
botcatcher = models.CharField(max_length= 1, blank=True,
validators=[validators.MaxLengthValidator(0)])
def __str__(self):
return "%s %s"% (self.first_name, self.last_name)
It was my indentation for the def clean function.
I asked a question and, as I have read a little, I now can better express what I need:
How to do model level custom field validation in django?
I have this model:
class StudentIelts(Model):
SCORE_CHOICES = [(i/2, i/2) for i in range(0, 19)]
student = OneToOneField(Student, on_delete=CASCADE)
has_ielts = BooleanField(default=False,)
ielts_listening = FloatField(choices=SCORE_CHOICES, null=True, blank=True, )
ielts_reading = FloatField(choices=SCORE_CHOICES, null=True, blank=True, )
ielts_writing = FloatField(choices=SCORE_CHOICES, null=True, blank=True, )
ielts_speaking = FloatField(choices=SCORE_CHOICES, null=True, blank=True, )
and have this model form:
class StudentIeltsForm(ModelForm):
class Meta:
model = StudentIelts
exclude = ('student')
def clean(self):
cleaned_data = super().clean()
has_ielts = cleaned_data.get("has_ielts")
if has_ielts:
msg = "Please enter your score."
for field in self.fields:
if not self.cleaned_data.get(str(field)):
self.add_error(str(field), msg)
else:
for field in self.fields:
self.cleaned_data[str(field)] = None
self.cleaned_data['has_ielts'] = False
return cleaned_data
What I am doing here is that checking if has_ielts is True, then all other fields should be filled. If has_ielts is True and even one field is not filled, I get an error. If has_ielts is False, an object with has_ielts=False and all other fields Null should be saved. I now want to do it on the model level:
class StudentIelts(Model):
SCORE_CHOICES = [(i/2, i/2) for i in range(0, 19)]
student = OneToOneField(Student, on_delete=CASCADE)
has_ielts = BooleanField(default=False,)
ielts_listening = FloatField(choices=SCORE_CHOICES, null=True, blank=True, )
ielts_reading = FloatField(choices=SCORE_CHOICES, null=True, blank=True, )
ielts_writing = FloatField(choices=SCORE_CHOICES, null=True, blank=True, )
ielts_speaking = FloatField(choices=SCORE_CHOICES, null=True, blank=True, )
def clean(self):
# I do not know what to write in here
and have this model form:
class StudentIeltsForm(ModelForm):
class Meta:
model = StudentIelts
exclude = ('student')
In the clean method of my model I want something with this logic(this is psedue code):
def clean(self):
msg = "Please enter your score."
if self.has_ielts:
my_dic = {}
for f in model_fields:
if f is None:
my_dic.update{str(field_name): msg}
raise ValidationError(my_dic)
How can I do this?
How can I get the same result as my modelform but at the model level?
You need to explicitly declare the fields that should be non-empty, otherwise you're cycling through fields that are not related to your clean method, like id and student. Someone might want to add a field later one that's not mandatory and wonder why it raises a validation error.
class StudentIelts(Model):
# fields
non_empty_fields = ['ielts_reading', ...]
def clean(self):
errors = {}
if self.has_ielts:
for field_name in self.non_empty_fields:
if not getattr(self, field_name):
errors[field_name] = msg
if errors:
raise ValidationError(errors)
Here are my models and admin classes:
---------------------Models-----------------------
from django.contrib.auth.models import User
class PurchaseOrder(models.Model):
buyer = models.ForeignKey(User)
is_debit = models.BooleanField(default = False)
delivery_address = models.ForeignKey('useraccounts.Address')
organisation = models.ForeignKey('useraccounts.AdminOrganisations')
date_time = models.DateTimeField(auto_now_add=True)
total_discount = models.IntegerField()
tds = models.IntegerField()
mode_of_payment = models.ForeignKey(ModeOfPayment)
is_active = models.BooleanField(default = True)
class Meta:
verbose_name_plural = "Purchase Orders"
def __unicode__(self):
return '%s' % (self.id)
----------------------------------Admin----------------------------------------
"""
This class is used to add, edit or delete the details of item purchased
"""
class PurchasedItemInline(admin.StackedInline):
form = ItemSelectForm
model = PurchasedItem
fields = ['parent_category', 'sub_category', 'item', 'qty', ]
extra = 10
class BuyerChoices(AutoModelSelect2Field):
queryset = User.objects.all()
search_fields = ['username__icontains', ]
class BuyerForm(ModelForm):
user_verbose_name = 'Buyer'
buyer = BuyerChoices(
label='Buyer',
widget=AutoHeavySelect2Widget(
select2_options={
'width': '220px',
'placeholder': 'Lookup %s ...' % user_verbose_name
}
)
)
class Meta:
model = PurchaseOrder
fields = '__all__'
"""
This class is used to add, edit or delete the details of items
purchased but buyer has not confirmed the items purchased, this class
inherits the fields of PurchaseOrder derscribing the delivery address of
buyer , is_debit , total discount , tds and mode of payment
"""
class PurchaseOrderAdmin(admin.ModelAdmin):
form = BuyerForm
#list_display = ['id','buyer','delivery_address','date_time','is_active']
inlines = [PurchasedItemInline]
# model = PurchaseOrder
#actions = [mark_active, mark_inactive]
#list_filter = ['date_time']
#search_fields = ['id']
list_per_page = 20
def response_add(self, request, obj, post_url_continue=None):
request.session['old_post'] = request.POST
request.session['purchase_order_id'] = obj.id
return HttpResponseRedirect('/suspense/add_distance/')
I am trying to implement django-select2, but when I use inlines in
PurchaseOrderAdmin it doesn't show the field where I have implemented
django-select2:
But when I remove inlines, it works fine:
Edit
Here is the ItemSelectForm
class ItemSelectForm(forms.ModelForm):
class Media:
js = (
'http://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js',
'js/ajax.js',
)
try:
parent_category = forms.ModelChoiceField(queryset=Category.objects.\
filter(parent__parent__isnull=True).filter(parent__isnull=False))
sub_category_id = Category.objects.values_list('id',flat=True)
sub_category_name = Category.objects.values_list('name',flat=True)
sub_category_choices = [('', '--------')] + [(id, name) for id, name in
itertools.izip(sub_category_id, sub_category_name)]
sub_category = forms.ChoiceField(sub_category_choices)
except:
pass
item = forms.ModelChoiceField(queryset = Product.objects.all())
def __init__(self, *args, **kwargs):
super(ItemSelectForm, self).__init__(*args, **kwargs)
self.fields['parent_category'].widget.attrs={'class': 'parent_category'}
self.fields['sub_category'].widget.attrs={'class': 'sub_category'}
self.fields['item'].widget.attrs={'class': 'item'}
It worked for me by adding the following line in the static/suit/js/suit.js
Add:
(function ($) {
Suit.after_inline.register('init_select2', function(inline_prefix, row){
$(row).find('select').select2();
});
I'm starting with Django. I have 3 models, a parent class "Cliente" and two child classes, "Persona" and "Empresa".
models.py
class Cliente(models.Model):
idcliente = models.AutoField(unique=True, primary_key=True)
direccion = models.CharField(max_length=45L, blank=True)
telefono = models.CharField(max_length=45L, blank=True)
email = models.CharField(max_length=45L, blank=True)
def __unicode__(self):
return u'Id: %s' % (self.idcliente)
class Meta:
db_table = 'cliente'
class Empresa(models.Model):
idcliente = models.ForeignKey('Cliente', db_column='idcliente', primary_key=True)
cuit = models.CharField(max_length=45L)
nombre = models.CharField(max_length=60L)
numero_ingresos_brutos = models.CharField(max_length=45L, blank=True)
razon_social = models.CharField(max_length=45L, blank=True)
def __unicode__(self):
return u'CUIT: %s - Nombre: %s' % (self.cuit, self.nombre)
class Meta:
db_table = 'empresa'
class Persona(models.Model):
idcliente = models.ForeignKey('Cliente', db_column='idcliente', primary_key=True)
representante_de = models.ForeignKey('Empresa', null=True, db_column='representante_de', blank=True, related_name='representa_a')
nombre = models.CharField(max_length=45L)
apellido = models.CharField(max_length=45L)
def __unicode__(self):
return u'Id: %s - Nombre completo: %s %s' % (self.idcliente, self.nombre, self.apellido)
class Meta:
db_table = 'persona'
I want to manage a class and its parent in the same view. I want to add, edit and delete "Cliente" and "Persona"/"Cliente" in the same form. Can you help me?
There is a good example in the Documentation Here.
I wrote this based on the documentation, so it is untested.
def manage_books(request, client_id):
client = Cliente.objects.get(pk=client_id)
EmpresaInlineFormSet = inlineformset_factory(Cliente, Empresa)
if request.method == "POST":
formset = EmpresaInlineFormSet(request.POST, request.FILES, instance=author)
if formset.is_valid():
formset.save()
# Do something. Should generally end with a redirect. For example:
return HttpResponseRedirect(client.get_absolute_url())
else:
formset = EmpresaInlineFormSet(instance=client)
return render_to_response("manage_empresa.html", {
"formset": formset,
})