how to customize ModelForm filled data - python

I have this model:
class Gallery(models.Model):
HeadImage = models.ImageField(upload_to="gallery")
With this form:
class GalleryForm(ModelForm):
class Meta:
model = Gallery
And this view:
gform = GalleryForm(request.POST, request.FILES, instance=galleryInstance)
In template a filled form is shown. For the HeadImage field it shows a link to an image related to the HeadImage field, and a fileinput with a change label:
{{ gform.HeadImage }}
Now instead of a link to the picture, I want to put the image into an img tag. I do this in the template as follows:
<img src={{ gform.HeadImage.value }}/>
What should I do so that the link doesn't show in the form?

To prevent it from showing, use any of these three options:
Set editable=False on the model field;
Use the fields attribute of the ModelForm's inner Meta class.
Use the exclude attribute of the ModelForm's inner Meta class.
Which one to use depends on how often you want the field to show (never, or in select cases). See the Django docs for more information on this.

Related

django form custom attrs widget imagefield

I have a model Prova:
class Prova(models.Model):
id = models.AutoField(primary_key=True)
codice= models.TextField(blank=True, null=True)
foto = models.ImageField(upload_to='stati/uploads/', blank=True)
and this is the form:
class ProvaForm(forms.ModelForm):
class Meta:
model = models.Prova
fields = ('codice','foto',)
widgets = {
'codice': forms.Textarea(attrs={'rows':1, 'cols':15,
'autofocus':'autofocus',
}),
'foto': forms.ClearableFileInput(attrs={'type': 'camera'}),
}
the customization of the codice field is working, but not the foto.
I want to change the type of html input from 'file' to specific image from 'camera'.
Tried also ImageField and
'foto': forms.FileInput(attrs={'capture': 'camera'}),
What am I missing to get it like the pure html:
<input type="file" capture="camera" accept="image/*">
camera is not valid HTML for the value of the type attribute of an input element.
If you do change it to <input type="camera" name="a-name-here" value="some-value">, then Chrome and FF will render it as a text input, while your ProvaForm expects a file (an ImageField), resulting in a failed validation. Of course you can override the validation part, by writting you own one, but what's the point of using an ImageField from the start if instead this field is going to be rendered as a text?
Check here for the possible values of the type attribute of an input element.

django admin panel numbering every form in formset

how can i add numeration to every form in formset in django admin panel. I need next number for every new added form
class QuestionAnswerInline(admin.TabularInline):
model = QuestionAnswer
formset = SetTestQuestionAnswerFormSet
fields = ('question_answer_text','right_mark')
class QuestionAdmin(admin.ModelAdmin):
fieldsets = [
...
]
inlines = [QuestionAnswerInline]
A couple of ways to do that:
Override edit view template for this specific admin class and add enumeration within template with {{ forloop.counter }}. This is probably easyest way of doing this
Override formset class in your admin to provide counter for all the inline forms. You need to do quite abit of magic to achieve that, but that is also possible. Basically you extend the inline admin class get_formset method to create the forms, provide the counter data and then non-editable field to display that data.

Readonly fields in django formset

I'm using modelformset factory to generate formset from model fields. Here i want to make only the queryset objects as readonly and other (extra forms) as non readonly fields
How can i achieve this?
AuthotFormSet = modelformset_factory(Author, extra=2,)
formset = AuthorFormSet(queryset=Author.objects.all())
In Above formset i wanted to display all the queryset objects as readonly, and remaining extra forms as non readonly fields. How can i achive this?
if i used,
for form in formset.forms:
form.fields['weight'].widget.attrs['readonly'] = True
This will convert all the forms (including extra) fields to readonly which i dont want.
And also i'm using jquery plugin to add form dynamically to the formset
I'd recommend specifying a form to use for the model, and in that form you can set whatever attributes you want to read only.
#forms.py
class AuthorForm(forms.ModelForm):
class Meta:
model = Author
def __init__(self, *args, **kwargs):
super(AuthorForm, self).__init__(*args, **kwargs)
if self.instance.id:
self.fields['weight'].widget.attrs['readonly'] = True
#views.py
AuthorFormSet = modelformset_factory(Author, extra=2, form=AuthorForm)
You can also put in your template :
{{form.management_form}}
{% for i in form %}
<p>{{ i.instance.readonly_field }}</p>
{{i.as_p}}
{% endfor %}
and not put the readonly_field in ModelForm.Meta.fields.
just need to check if the instance has id, like this:
if self.instance.id
before setting it as read-only
I used python long back. Hope this helps . But if you wish to control fields display using jquery
$('.class').attr('readonly', true);
or
$('#id').attr('readonly', true);

Change a Django form field to a hidden field

I have a Django form with a RegexField, which is very similar to a normal text input field.
In my view, under certain conditions I want to hide it from the user, and trying to keep the form as similar as possible. What's the best way to turn this field into a HiddenInput field?
I know I can set attributes on the field with:
form['fieldname'].field.widget.attr['readonly'] = 'readonly'
And I can set the desired initial value with:
form.initial['fieldname'] = 'mydesiredvalue'
However, that won't change the form of the widget.
What's the best / most "django-y" / least "hacky" way to make this field a <input type="hidden"> field?
This may also be useful: {{ form.field.as_hidden }}
If you have a custom template and view you may exclude the field and use {{ modelform.instance.field }} to get the value.
also you may prefer to use in the view:
field = form.fields['field_name']
field.widget = field.hidden_widget()
but I'm not sure it will protect save method on post.
edit: field with multiple values don't supports HiddenInput as input type, so use default hidden input widget for this field instead.
an option that worked for me, define the field in the original form as:
forms.CharField(widget = forms.HiddenInput(), required = False)
then when you override it in the new Class it will keep it's place.
Firstly, if you don't want the user to modify the data, then it seems cleaner to simply exclude the field. Including it as a hidden field just adds more data to send over the wire and invites a malicious user to modify it when you don't want them to. If you do have a good reason to include the field but hide it, you can pass a keyword arg to the modelform's constructor. Something like this perhaps:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
def __init__(self, *args, **kwargs):
from django.forms.widgets import HiddenInput
hide_condition = kwargs.pop('hide_condition',None)
super(MyModelForm, self).__init__(*args, **kwargs)
if hide_condition:
self.fields['fieldname'].widget = HiddenInput()
# or alternately: del self.fields['fieldname'] to remove it from the form altogether.
Then in your view:
form = MyModelForm(hide_condition=True)
I prefer this approach to modifying the modelform's internals in the view, but it's a matter of taste.
For normal form you can do
class MyModelForm(forms.ModelForm):
slug = forms.CharField(widget=forms.HiddenInput())
If you have model form you can do the following
class MyModelForm(forms.ModelForm):
class Meta:
model = TagStatus
fields = ('slug', 'ext')
widgets = {'slug': forms.HiddenInput()}
You can also override __init__ method
class Myform(forms.Form):
def __init__(self, *args, **kwargs):
super(Myform, self).__init__(*args, **kwargs)
self.fields['slug'].widget = forms.HiddenInput()
If you want the field to always be hidden, use the following:
class MyForm(forms.Form):
hidden_input = forms.CharField(widget=forms.HiddenInput(), initial="value")
If you want the field to be conditionally hidden, you can do the following:
form = MyForm()
if condition:
form.fields["field_name"].widget = forms.HiddenInput()
form.fields["field_name"].initial = "value"
Example of a model:
models.py
from django.db import models
class YourModel(models.Model):
fieldname = models.CharField(max_length=255, default="default")
In your form, you can add widgets with ModelForm. To make it hidden add 'type': 'hidden' as shown below👇
forms.py
from .models import YourModel
from django import forms
class YourForm(forms.ModelForm):
class Meta:
model = YourModel
fields = ('fieldname',)
widgets = {
'fieldname': forms.TextInput(attrs={'type': 'hidden'}),
}
If you don't know how to add it to your views.py file, here is some videos about it.
If you use Function Based View:
https://www.youtube.com/watch?v=6oOHlcHkX2U
If you use Class Based View:
https://www.youtube.com/watch?v=KB_wDXBwhUA
{{ form.field}}
{{ form.field.as_hidden }}
with this jinja format we can have both visible form fields and hidden ones too.
if you want to hide and disable the field to protect the data inside. as others mentioned use the hiddenInput widget and make it disable
in your form init
example:
if not current_user.is_staff:
self.base_fields['pictureValid'].disabled = True
self.base_fields['pictureValid'].widget = forms.HiddenInput()
With render_field is easy
{% render_field form.field hidden=True %}
You can just use css :
#id_fieldname, label[for="id_fieldname"] {
position: absolute;
display: none
}
This will make the field and its label invisible.

how can I make a Django model form with a field name in the form different from the model field name?

I have a model and a form like this:
class Content(models.Model):
title = models.CharField(_("title"), max_length=16)
category = models.ForeignKey(Category, verbose_name = _('category'))
class ContentForm(forms.ModelForm):
class Meta:
model=Content
fields = ('title', 'category', )
I would like to have the name of the field in the form to be f_category (of course the name of the field in the model is to stay category). Is it possible to do that, without having to construct the whole form manually (which is difficult because the field is a ForeignKey and has to be a select field with a list of options)?
To clarify: by name I mean the name as in the HTML form code: <input type="select" name="f_category" />
Your comment reveals what you actually need to do - this is why you should always describe your actual problem, not your proposed solution. Naturally, there is a proper way to deal with two identical forms on the same page in Django - use the prefix parameter when instantiating the field.
form1 = MyForm(prefix='form1')
form2 = MyForm(prefix='form2')
Now when you output form1 and form2, all the fields will automatically get the relevant prefix, so they are properly separated.
I'm not sure what you mean by "the name of the field in the form". Do you mean the label? Or the id? Or something else? Configuring the label is pretty easy:
class ContentForm(forms.ModelForm):
category = forms.ModelChoice(queryset=Category.objects.all(), label='f_category')
class Meta:
model=Content
fields = ('title', 'category', )

Categories

Resources