Reputation: 5578
When using Django Crispy Forms on a ModelForm I keep getting an Error:
Creating a ModelForm without either the 'fields' attribute or the 'exclude' attribute is prohibited;
According to this website I would have to make the form this way:
class HotelImageForm(ModelForm):
helper = FormHelper()
helper.form_tag = False
helper.layout = Layout(
"image",
"alt_name"
)
class Meta:
model = HotelImage
When I make it this way I get the error I mentioned.
However when I put the fields in there, crispy forms does not seem to do much.
class HotelImageForm(ModelForm):
helper = FormHelper()
helper.form_tag = False
helper.layout = Layout(
"image",
"alt_name"
)
class Meta:
model = HotelImage
fields = ('image', 'alt_name')
I have also added def __init__
but that did not work either
class HotelImageForm(ModelForm):
def __init__(self, *args, **kwargs):
super(HotelImageForm, self).__init__(*args, **kwargs)
helper = FormHelper()
helper.form_tag = False
helper.layout = Layout(
"image",
"alt_name"
)
class Meta:
model = HotelImage
This is the code from the view:
def hotel_registration(request):
if request.method == 'POST':
hotel_form = HotelForm(request.POST, instance=Hotel())
hotel_image_form = HotelImageForm(request.POST, instance=HotelImage())
if hotel_form.is_valid():
new_hotel = hotel_form.save()
hotel_image = hotel_image_form.save()
hotel_image.hotel = new_hotel
employee.save()
employee.hotel.add(new_hotel)
return HttpResponseRedirect(reverse(hotel_registered))
else:
hotel_form = HotelForm(instance=Hotel())
hotel_image_form = HotelImageForm(instance=HotelImage())
context = {
'hotel_form': hotel_form,
'hotel_image_form': hotel_image_form,
}
context.update(csrf(request))
return render_to_response('hotel/hotel-registration-form.html', context)
And the code from the template:
<div class="col-md-5">
{{ hotel_form|crispy }}
{% crispy hotel_image_form hotel_image_form.helper %}
<input type="submit" class="btn btn-primary btn-lg margin-bottom-20" value="Registreren">
</div>
hotel_form
does not use Crispy forms in the forms code at the moment.
I hope someone could tell me what I am missing here.
Thanks.
Upvotes: 0
Views: 2136