Generating unique names for each of the form fields in Django templates
I have a forms something like this:
class PersonForm(forms.ModelForm):
name=forms.CharField(label = 'Name')
birth_date = forms.DateField(widge开发者_运维技巧t = SelectDateWidget(years=range(1985,2020) ),label = 'DOB')
place = forms.CharField(label='Place')
Suppose I am using to this form with birth_date(date field) repeated twice in the template as follows:
{% for field in form %}
<tr>
<th scope="row" class={% cycle "spec" "specalt" %}> </th>
<td {% cycle '' 'class="alt"' %}>
{% if field.field.datatype == 'Date' %}
**Range : {{field}} {{field}}**
{% else %}
{{ field}}
{% endif %}
As shown above I am repeating the date field twice. However I receive the form in POST request, I am unable to differenciate between the both the date fields. How can I rename one the date fields in the template, so that I could easily differenciate in my view function.
Note: Please do not suggest to add another field in "class PersonForm(forms.ModelForm)" as that is ruled out in the actual problem that I have. I have phrased the question according to my needs. Thanks in advance.
I guess the right solution for you is to create a widget that will render those two fields and will be able to retrieve values and do some cleaning operations on that values.
As I know there isn't detailed documentation on custom widget writing topic. You can code by examples which can be found in django code:
django.forms.widgets
A Form in Django is supposed to represent the fields that are to be displayed to the end user. If the visual representation of the form is supposed to contain more, or less, than the fields declared in the form, it's probably wrong.
If you need a 'begin date' and 'end date' field, then that should be represented within the form class that you're creating. If you need a form with just a single date as you have above, then have two different forms!
There is no easy way of hijacking a form, modifying it, displaying it, and then validating it once it reaches the server bound with data. You can do a dynamic subclass of the form, but I can't see how this is going to be a good thing in this situation. You know the fields you need at 'compile time'. Just put them in a form! Even if it's a brand-spanking-new-one.
One last thing, is there a reason that you're using forms.ModelForm
? It appears that you're creating a totally customized form. I think forms.Form
is what you're after.
精彩评论