222๐
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.
- [Django]-Class has no objects member
- [Django]-VueJS + Django Channels
- [Django]-Django-allauth social account connect to existing account on login
90๐
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.
- [Django]-Multiple Database Config in Django 1.2
- [Django]-Django self-referential foreign key
- [Django]-Django py.test does not find settings module
54๐
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.
- [Django]-Filtering using viewsets in django rest framework
- [Django]-Retrieving parameters from a URL
- [Django]-Django โ how to visualize signals and save overrides?
41๐
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()
- [Django]-Django proxy model and ForeignKey
- [Django]-Aggregate() vs annotate() in Django
- [Django]-Handling race condition in model.save()
9๐
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"
- [Django]-Getting Values of QuerySet in Django
- [Django]-Check if celery beat is up and running
- [Django]-How to go from django image field to PIL image and back?
3๐
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:
- [Django]-Django: how save bytes object to models.FileField?
- [Django]-Django: sqlite for dev, mysql for prod?
- [Django]-Copy a database column into another in Django
2๐
{{ form.field}}
{{ form.field.as_hidden }}
with this jinja format we can have both visible form fields and hidden ones too.
- [Django]-Django CSRF check failing with an Ajax POST request
- [Django]-How do I run tests against a Django data migration?
- [Django]-The QuerySet value for an exact lookup must be limited to one result using slicing. Filter error
2๐
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()
- [Django]-No module named pkg_resources
- [Django]-Pylint "unresolved import" error in Visual Studio Code
- [Django]-FileUploadParser doesn't get the file name
- [Django]-Django CMS fails to synch db or migrate
- [Django]-Django 2.0 โ Not a valid view function or pattern name (Customizing Auth views)
- [Django]-How can i test for an empty queryset in Django?
1๐
Disclaimer: I am a junior in Django. This answer is a working solutions; however, it may contain some sub-optimal practices. If that is the case, please let me know in the comments, and I will adjust it.
To expand on Rybakโs and Zagsโs answers, if you want to use the HiddenInput
field in multiple places, you could create a custom hidden field class.
class MyHiddenCharField(forms.CharField):
def __init__(self, *, required=False, **kwargs):
self.required = required
self.widget = forms.HiddenInput()
super().__init__(required=False, **kwargs)
- [Django]-Data Mining in a Django/Postgres application
- [Django]-'pip' is not recognized as an internal or external command
- [Django]-Uninstall Django completely
-4๐
You can just use css :
#id_fieldname, label[for="id_fieldname"] {
position: absolute;
display: none
}
This will make the field and its label invisible.
- [Django]-Django โ iterate number in for loop of a template
- [Django]-Adding css class to field on validation error in django
- [Django]-Sending an SMS to a Cellphone using Django