Django custom form field layout without manually redoing the whole form - django

I like Django form render(‘form’: form) and template {{ form }}, but it doesn’t allow you to arrange fields. I was just wondering if there was an easier way to do it, without rendering the whole form manually.
What Django does:
First Name
Middle Name
Last Name
What I want to do:
First Name Middle Name
Last Name
What makes Django {{ form }} so great is that it puts field labels and help text and all that jazz in the right places. Where as manually, you have to put all that in. If there isn’t an easier way, I’m ok with that, but I thought I would at least ask.

You could try to render individual fields of the form, like this part of the docs shows.

Related

Delete rows set to be deleted in a formset and duplicates issues

I know this question has been asked before (e.g. Django modelformset_factory delete modelforms marked for deletion) but I've tried all the possible solutions, including doing what the official documentation says (https://docs.djangoproject.com/en/3.0/topics/forms/formsets/), and I still cannot delete the forms from my formset.
I have a form which correctly sends POST data with everything I need (including the DELETE instruction).
[print(form_links_event.cleaned_data) for form in form_links_event.deleted_forms]
[{'description': 'asdasd', 'link': 'http://www.test.com', 'id': <linksEvent: linksEvent object (25)>, 'DELETE': True}
Nevertheless, I need to process the formset before saving all the instances (I need to attach the id of a related model), so I need to call save(commit=False):
instances_links_event = form_links_event.save(commit=False)
for link in instances_links_event:
link.event = instance_event
link.save()
form_event.save()
form_links_event.save()
Doing so, though, strips the .deleted_forms list. In fact:
[print(instances_links_event.cleaned_data) for form in instances_links_event.deleted_forms]
AttributeError: 'list' object has no attribute 'deleted_forms'
Therefore I'm stuck in a loop: I cannot save my form directly because I need to attach more data to it first, and in its raw state it has the 'deleted_forms' list. Once I save it with commit=False and process with the processing, though, the 'deleted_forms' is not there any more so that I cannot delete those rows set for deletion. Ideally, I'd like to do this:
instances_links_event = form_links_event.save(commit=False)
for link in instances_links_event:
if (link.delete = True):
link.delete()
link.event = instance_event
link.save()
form_links_event.save()
I'm using Django 3.0.6 with Python 3.7.
Update
Even without the commit=False, saving the form with form_links_event.save(), I keep having issues: when I save the form in my 'edit page' (i.e. bound form) save() saves the existing records again, even if I didn't edit anything, which means I end up with a lot of duplicates. Is something wrong with Django formset or is it just me?
My form:
<tbody id='linksEvent_body'>
{% for formLink in form_links_event.forms %}
{{formLink.non_field_errors}}
{{formLink.errors}}
<trclass="formLink">
{{ formLink.id }}
<td>{{formLink.link}}</td>
<td>{{formLink.description}}{{formLink.DELETE}}</td>
</tr>
{% endfor %}
</tbody>
I've been battling with this and working for days on end, trying all sorts of possible parameters and code. I found out that the first time the form is loaded/bound after having saved it, it is not loading the form_management data correctly (i.e. the -INITIAL value is not correct and the extra blank form is not there) and also the bound data is not always updated. If I try to fix it via JavaScript, for example counting the number of forms displayed and put that number in the -CURRENT parameter and that number -1 in the -INITIAL or things like that, Django wouldn't like it (the documentation itself says that it is discouraged to tamper with the form management data anyway, which I understand). Once I'd manually refresh the page (by placing the cursor on the address bar and hit enter, not by hitting ctrl/cmd + R, which would ask me to send the POST data again), then the form loads correctly and any further edit would nicely save correctly. So, the only way I could find to solve this issue, which looks and sound like a Django inline forms bug to me, is by placing this code in the page containing the form:
<script type='text/javascript'>
(function()
{
if( window.localStorage )
{
if( !localStorage.getItem('firstLoad') )
{
localStorage['firstLoad'] = true;
window.location=window.location;;
}
else
localStorage.removeItem('firstLoad');
}
})();
</script>
With this code in place everything works like a charm. I hope this will help others who'll face this frustrating issue like myself.
PS: the issue is independent from the commit=False instruction. And yes, I declared #never_cache in my view.

How can one create a custom "as_table()" method for forms?

I have a relatively complicated form that's used in multiple places on my website (in fact, it's a form from which many other form classes inherit). In the templates, the inherited part of this form is always formatted identically—but that formatting is somehwat involved; each field is rendered and positioned manually in the template.
This means that every template which displays this form has a lot of identical HTML markup that renders the form appropriately.
I would like to create a custom output that can be called, similar to the as_table() methods. I'm aware that one can override the normal_row, error_row, etc. attributes—but the formatting of this form goes beyond that (for example, three of the form's five fields should be printed side-by-side, with a combined title). All of the tutorials/answered-questions I've seen either refer to overriding the above-mentioned attributes, or give instructions on how to manually render forms.
Originally, I was thinking something like this:
Class StrangeForm(form.Forms):
....
def as_table_custom():
html_string = "\
<tr><td>Title 1:</td><td>self.fields['field1']</td><tr>\
<tr><td>Title 2:</td><td>self.fields['field2']</td><tr>\
<tr><td>Titles 3, 4, 5:</td><td>self.fields['field3']\
</td><td>self.fields['field4']</td><td>self.fields['field5']</td></tr>\
"
return html_string
But, after reading through the _html_output() and as_table() methods of Django's forms.py file, it doesn't look like it'll be that easy. If I write this from scratch, have to somehow account for errors, help text, etc. I think.
Is there an easy way to override something such that the form's HTML output can be defined like above? Or do I have to re-write things from scratch. If the latter, how can I account for all of the things I need to account for?
I wouldn't take this approach. You're better off creating the form in an HTML template that you include in the various templates where you have a form you want to display that way.
So create a my_strange_form.html template where you assume a 'form' object is passed in the context with the right number of fields. In that template just create the HTML, using things like {{ field.label_tag }} and {{ field }}. You can loop through the fields with a {% for field in form %} and check the counter of your loop with {{ forloop.counter }}. I foresee a lot of {% if forloop.counter... %} statements to generate the combined row, and it will look ugly, but you'll only have to look at it once :-)
Then in your main templates {% include 'my_strange_form.html' with form=form %}.

Django: How to place a form in all subsites and process it on 1 url?

I need to place a form in all my subsites and home page. It's placed on right column. It's action is "/". If there are some errors I must display them.
I made Form class etc. I display it via {{ form.as_p }} and designed all.
The problem is - how to put it on all sites? I don't want to make form instance in all my views functions.
What is the best solution for that?
Looks like a work for a context processor. :-)
def my_form_processor(request):
return {'my_form': MyForm()}

django - post form on select

I made a simple django form, with a list of choices (in radio buttons):
class MyForm(forms.Form):
choices=forms.ChoiceField( widget=forms.RadioSelect(), choices=[(k,k) for k in ['one','two','three']],label="choose one")
I would like the form to submit automatically when a user selects one of the options. In straightforward HTML I would've done it as
<select name='myselect' onChange="FORM_NAME.submit();">
....
</select>
But I do not know how to integrate this into the form class without writing a template. Specifically, I would need to know FORM_NAME so I can call FORM_NAME.submit() in the above snippet.
Can it be done without using a template?
I think you do not need to know the form name. This should work as well:
<select name='myselect' onChange="this.form.submit();">
A quick solution to integrate this into your form would involve adding a attribute to your widget.
widget=forms.RadioSelect(attrs={'onchange': 'this.form.submit();'})
Now one could argue if this isn't better separated from your form definition (separating definition, style and behaviour), but that should do it.

Print a template variable on an overwritten admin form in Django

I have a Doctor-model which has a field called first_created. It is just a DateField that is auto_add_now, hence it is not displayed when editing a doctor in the admin interface.
I want to display this field on the admin interface, at the top of the site as say, a static or something. It is supposed to ease the process of typing in data in other fields, so a sentence like "three months from now" will make more sense.
Since the model should according to the documentation, should hold all model fields as template variables, I am trying to overwrite the change_form.html and outputting {{ doctor.first_created }}. But it is not working.
I've tried multiple things, even things like looping over opts.fields and printing out methods on these fields like value_to_string. Not working.
How can I print first_created as a template variable in change_form.html?
Regards
You haven't said what doctor is in the context of the edit page. Is it the object being edited? That's passed to the template as original, so you should be able to do {{ original.first_created }}.