Django form to indicate input type

2024/11/15 13:37:26

Another basic question I'm afraid which I'm struggling with. I've been through the various Django documentation pages and also search this site. The only thing I have found on here was back in 2013 which suggested setting up a custom filter template.

Anyhow, I'm trying to generate my own form instead of using Django's own way of generating it through {{ form }}. This is simply so I can control the way the form is presented.

I've worked out various ways to access the required information such as (within my for item in form loop);

  • item.help_text
  • item.label_tag
  • item.id_for_label

I'm trying to identify the item type so I can use the correct input type, however I'm struggling to workout what item.xxxx should be. Since this is correctly displayed through {{ form }} I am making an assumption that this information is available somewhere in the form, just struggling to find out how to access it so I can identify the correct input type. I'm doing this manually so I can use the correct Bootstrap styles to display the input fields.

Any assistance would be appreciated (or just pointing in the right direction). I'm very new to this so apologies for my very basic questions, its difficult without knowing someone I can just go an ask these questions to.

Regards

Wayne

Not sure if you need it but here is some code;

Form:

class NewsForm(ModelForm):class Meta:model = News_Articleexclude = ('news_datetime_submitted', 'news_yearmonth', )labels = {'news_title': _('Enter News Title'),}help_texts = {'news_title': _('Enter a title to give a short description of what the news is.'),}error_messages = {'news_title': {'max_length': _("News title is too long."),},}

View (not worked on the POST bit yet, this is just what's from the Django documentation, POST is my next thing to work out)

def create(request, dataset):if dataset not in ['news', 'announcement']:return HttpResponseRedirect(reverse('pages'))rDict = {}if request.method == 'POST':if dataset == "news":form = NewsForm(request.POST)elif dataset == "announcement":form = AnnouncementForm(request.POST)if form.is_valid():return HttpResponseRedirect('/home/')else:passelse:announcement = get_announcement()if not announcement == None:rDict['announcement'] = announcementif dataset == "news":rDict['form'] = NewsForm()rDict['branding'] = {'heading': 'Create News Item', 'breadcrumb': 'Create News', 'dataset': 'create/' + dataset + '/'}elif dataset == "announcement":rDict['form'] = AnnouncementForm()rDict['branding'] = {'heading': 'Create Announcement', 'breadcrumb': 'Create Announcement', 'dataset': 'create/' + dataset + '/'}rDict['sitenav'] = clean_url(request.path, ['"', "'"])rDict['menu'] = Menu.objects.all().order_by('menu_position')
#        pdb.set_trace()return render(request, 'en/public/admin/admin_create.html', rDict)

Template code

<form action="/siteadmin/{{ branding.dataset }}" method="post">{% csrf_token %}{% for item in form %}<div class="row"><div class="col-xs-2 col-md-2"></div><div class="col-xs-4 col-md-4"><div class="panel-title pull-right">{% if item.help_text %}<img src="/static/images/info.png" height="20" width="20" aria-hidden="true" data-toggle="popover" title="{{ item.help_text }}">&nbsp{% endif %}{{ item.label_tag }}</div></div><div class="col-xs-4 col-md-4"><div class="input-group">       <input type="{{ item.widget }}" class="form-control" placeholder="" aria-describedby="{{ item.id_for_label }}"></div></div><div class="col-xs-2 col-md-2">{% if forloop.last %}<input type="submit" value="Submit" />{% endif %}</div>          </div>{% endfor %}
</form>
Answer

Try this:

<input type="{{ item.field.widget.input_type }}" ...

No link to docs, found it by using debugger (not the best practice, I know...)

As per @Smurf's comment, this won't work for all widgets, like Select, CheckBox, any MultiWidget, etc... Seems to only work for text input and its variants (password, email...)


A better solution is to create custom widgets and render your form fields in template as usual. You can set any custom attributes there, see https://docs.djangoproject.com/en/1.8/ref/forms/widgets/#customizing-widget-instances


If you absolutely have to modify widgets in the template, then use django-widget-tweaks

This app provides a nice-looking form filters to alter widgets (i.e. their attributes). But be aware that it does so by way of string mongering with the already-rendered HTML ("rendered" as concernes the Widget instance).

https://en.xdnf.cn/q/71778.html

Related Q&A

run multi command in the same jupyter cells

Im trying to display 2 output of 2 lines in the same time, I use Panda library and it seems like it display only the output of second line:import pandas as pd data = {"state": ["Ohio&quo…

Pandas how to get rows with consecutive dates and sales more than 1000?

I have a data frame called df: Date Sales 01/01/2020 812 02/01/2020 981 03/01/2020 923 04/01/2020 1033 05/01/2020 988 ... ...How can I get the first occurrence of 7 conse…

Use Python alongside C# in Windows UWP app

I started writing an application in Python, but I now want to switch to C# and UWP. I know that you cannot write a UWP app in Python, but I am trying to see if I can write some code in Python and acces…

How do you go from a sip.voidptr (QImage.constBits()) to a ctypes void or char pointer?

Im using python and of course you cant loop through every pixel of a large image very quickly, so I defer to a C DLL.I want to do something like this:img = QImage("myimage.png").constBits() i…

Just returning the text of elements in xpath (python / lxml)

I have an XML structure like this:mytree = """ <path><to><nodes><info>1</info><info>2</info><info>3</info></nodes></to> …

Python function parameter: tuple/list

My function expects a list or a tuple as a parameter. It doesnt really care which it is, all it does is pass it to another function that accepts either a list or tuple:def func(arg): # arg is tuple or …

Python binding for C++ operator overloading

I have a class similar to the following:class A {vector<double> v;double& x(int i) { return v[2*i]; }double& y(int i) { return v[2*i+1]; }double x(int i) const { return v[2*i]; }double y(…

python script to pickle entire environment

Im working inside the Python REPL, and I want to save my work periodically. Does anybody have a script to dump all the variables I have defined? Im looking for something like this:for o in dir():f=ope…

django-endless with class based views example

Im using Class Based Views for the first time. Im having trouble understating how using class based views I would implement django-endless-pagination twitter styling paging.Could I have an example of h…

Converting adjectives and adverbs to their noun forms

I am experimenting with word sense disambiguation using wordnet for my project. As a part of the project, I would like to convert a derived adjective or an adverb form to its root noun form.For exampl…