How to map HTML form data to Django model - django

I have a (quite complex) HTML form full of logic that triggers based on different choices in the selectpickers with fields that don't have quite the same names as the corresponding fields in the Django model, and sometimes I fear that I will need to add some logic when it comes to going from the data sent from the HTML form and to the Django model. I realise that I can probably not use a ModelForm in Django to handle this and have been looking for some examples of using the standard django.forms.Form to map the HTML form into my model but I haven't really found much. Can someone give me some hints?

It sounds as though your html form already exists and somehow you want to read in the POST data from that form. Without making any further assumptions as to how you ended up with an html form without a django ModelForm or forms.Form output via a view - as long as the form action location is mapped via a route to a view - the view can then process the request.POST data. Again all form validation goodness of django is out the door if you did not use django forms (model or forms based) and you have to do your own validations in the view then. Once the form data has been validated, initialize your model object like this: my_obj = ModelName(field_name1=form_input_data1, field_name2=form_input_data2, ...) and that's it. Then you can do my_obj.save().
Now let's say, it's not so bad. You actually are using the forms.Form inheritance to create your django-istic form class which has no direct relationship with the model. Now you can use the form related validation clean_field and clean steps etc... as well as all the built-in field types internal validation django automatically does. Then when you read in the POST data - do whatever it takes to map the form fields (via any transformation as necessary) to the django model object you are trying to construct, keeping in mind the default values and any model save custom assignments that may happen.

You can not just map a html form into your django model. You need to create a model form first and then render it in html.
If you want to somehow map your html form to model. First render your ModelForm in html. Create the exact copy of the html format of your django form and use it in html. Catch that in your view and process it like model form. But anyway you have to create the ModelForm.

Related

Django database inputs not being validated

I have this class:
class Object(models.Model):
value=models.IntegerFiled(validators=[MaxValueValidator(100)])
I get user input for the value attribute, create an object according to the user input and save it to the database. The problem is that the user can enter e.g. 120 in the form that is used to get the input from the template/html-page to the view's method. Then an invalid object is saved to the database.
How exactly does the MaxValueValidator work? When does it do anything? What purpose do validators serve?( I really couldn't find any answer to my questions in the documentation)
I do check if the input form is valid in the view, but this doesn't seem to prevent saving invalid objects by just changing the HTML attributes in the form via developer tools in the browser
You should use a ModelForm to generate your form from the model if you want your validators to be run automatically. As per docs:
Note that validators will not be run automatically when you save a model, but if you are using a ModelForm, it will run your validators on any fields that are included in your form.
Validators work with Forms
You can make a form, such as
class ObjectForm(forms.Form):
value = forms.IntegerField(validators=[MaxValueValidator(100)])
Then validate the form based on user input
if ObjectForm(request.POST).is_valid():
# save model object here
Hope this helps.

FormView - Specify which fields are sent in the POST

Given a FormView associated to a Form, once the form is submitted some fields are sent to the FormView (those the user has filled).
Question: How can I send to the FormView other fields even if the user didn't fill them (because the fields were already prepopulated)? I need more data than the user provides in order to be used in form_valid
If the data is not sensitive you might want to add them to your form as hidden fields. In django you can achieve this with a FormWidget. There are a few related questions here on SO:
Change a django form field to a hidden field
Django ModelForm to have a hidden input
Be aware that this just hides your data in the user interface, not in the browser - if you are in trouble if someone will change this data in an evil matter, you might consider writing the data in the session.

Specifying specific form format in Django

I am using materializecss to give my django site some material elements. I have put together a form (the 'old' way using html) but now realised I need to use a django form instead. The problem is, these forms don't play well with materialises built in column system (they use classes to determine rows and column spacing). Here is an example of the layout I set up so far. However when defining the form through form.py, it spits out one input per layer.
My question is: what can I do to either a) get django to work with the html-defined form or b) make a 'form template' to give the input fields the appropriate classes?
If you want to see the code I can post some but I'm quite a new coder so it's messy.
Thanks!
There are three ways I can think of off the top of my head.
If you want full control over the HTML form, in a Django template or HTML form, simply map the names of your fields to match the underlying field names in the Django form. This way, when POSTed back to your view, Django will automatically link up the POSTed fields with the Django form fields.
For example, if you have a field username in your Django form (or Django model if using ModelForm), you could have an element <input type="text" name="username" maxlength="40"> (that you can style any way you need) on your HTML form that Django will happily parse into your Django form field, assuming your view is plumbed correctly. There is an example of this method in the Django documentation.
Another way is to customize the Django form field widgets in your Django form definition. The Django documentation talks a little bit about how to do this. This is great for one offs, but is probably not the best approach if you expect to reuse widgets.
The final approach would be to subclass Django form field widgets to automatically provide whatever attributes you need. For example, we use Bootstrap and have subclassed nearly all of the widgets we use to take advantage of Bootstrap classes.
class BootstrapTextInput(forms.TextInput):
def __init__(self, attrs=None):
final_attrs = {'class': 'form-control'}
if attrs is not None:
final_attrs.update(attrs)
super().__init__(attrs=final_attrs)
Then it's simply a matter of letting the Django form know which widget to use for your form field.
class UsernameForm(forms.ModelForm):
class Meta:
model = auth.get_user_model()
fields = ['username']
widgets = {'username': BootstrapTextInput()}
Hope this helps. Cheers!

Django: Sanitize form data?

I have a django project and the forms are constructed in HTML rather than as a django object. I retrieve the values via a post class function in the view. Because I'm not constructing forms through django, do I need to sanitize the form data? If I need to sanitize the data, what django method can I use?
Thanks for your help!
There's no reason why you can't construct a Form class that respects the parameters of the HTML form. There's not really any magic to it. Django offers tools to generate the HTML pragmatically, but you don't have to use it.
You can leverage all the power of Django's form validation--just make sure the Form class fields align with the field names in your HTML and bind it to the POST data. If your Form's parameters change, you'll have to update the markup.

django generic view update/create: update works but create raises IntegrityError

I'm using CreateView and UpdateView directely into urls.py of my application whose name is dydict. In the file forms.py I'm using ModelForm and I'm exluding a couple of fields from being shown, some of which should be set when either creating or updating. So, as mentioned in the title, update part works but create part doesn't which is obvious because required fields that I have exluded are sent empty which is not allowed in my case. So the question here is, how should I do to fill exluded fields into the file forms.py so that I don't have to override CreateView?
Thanks in advance.
Well, you have to set your required fields somewhere. If you don't want them to be shown or editable in the form, your options are to set them in the view (by using a custom subclass of CreateView) or if appropriate to your design in the save method of the model class. Or declare an appropriate default value on the field in the model.
It would also work to allow the fields into the form, but set them to use HiddenInput widgets. That's not safe against malicious input, so I wouldn't do that for purely automated fields.
You cannot exclude fields, which are set as required in the model definition. You need to define blank=True/null=True for each of these model fields.
If this doesn't solve your issue, then please show us the model and form definitions, so we know exactly what the code looks like.