construct attribute value of django form - django

How do I pass in a value to an attribute constructor in a django form?
In other words, I have a form like so, and I'd like to set SOMETHING when I instantiate the form.
class ImageUploadFileForm(forms.ModelForm):
class Meta:
model = Photo
fields = [ 'image' ]
image = cloudinary.forms.CloudinaryJsFileField({ 'public_id': SOMETHING })
i.e. in the view:
uploadform = ImageUploadFileForm(instance=whatever, something='BLAHBLAHBLAH')
I have the suspicion that I'm thinking about this wrongly...
Thx Shang Wang!
For all of you searching in CloudinaryJSFileField, don't forget to add 'options', like so:
class ImageUploadFileForm(ModelFormControlMixin):
class Meta:
model = Photo
fields = [ 'image' ]
def __init__(self, *args, **kwargs):
self.public_id = kwargs.pop('public_id')
super(ImageUploadFileForm, self).__init__(*args, **kwargs)
self.fields['image'] = cloudinary.forms.CloudinaryJsFileField(options={ 'public_id': str(self.public_id) })

class ImageUploadFileForm(forms.ModelForm):
class Meta:
model = Photo
fields = [ 'image' ]
def __init__(self, *args, **kwargs):
self.something = kwargs.pop('something')
super(ImageUploadFileForm, self).__init__(*args, **kwargs)
self.fields['image'] = cloudinary.forms.CloudinaryJsFileField({ 'public_id': self.something })
Then
uploadform = ImageUploadFileForm(instance=whatever, something='BLAHBLAHBLAH')
Pretty standard way of passing arguments to form constructor.

Related

How to delete label of a form in Django

How can I delete label of form in Django. I have something like this.
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['user_image']
widgets = {
'user_image': forms.FileInput(attrs={'class': 'image-upload', 'label': ''}),
}
image-upload class does not include label. I have a auto-generated label and is written 'user-image'
You can remove it via init:
class ProfileUpdateForm(forms.ModelForm):
class Meta:
model = Profile
fields = ['user_image']
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['user_image'].label = ''

Empty Django Form Select Field

I want empty job_users field before sending to the template. Because job_groups and job_users is dependent. I am calling ajax call when the group is select and users of that group will be displayed inside job_users. But now all users are displayed inside job_users select field.
class JobForm(forms.ModelForm):
job_description = forms.CharField(widget=forms.Textarea(attrs={'rows':4, 'cols':15}))
job_users = None
class Meta:
model = Jobs
fields = [
'job_name',
'job_group',
'job_users',
]
def __init__(self, *args, **kwargs):
self.user_company = kwargs.pop('user_company', None)
super().__init__(*args, **kwargs)
self.fields['job_group'].queryset = None
self.fields['job_group'].queryset = None i am using this but it is giving me error
Maybe you can do it like this:
class JobForm(forms.ModelForm):
job_description = forms.CharField(widget=forms.Textarea(attrs={'rows':4, 'cols':15}))
class Meta:
model = Jobs
fields = [
'job_name',
'job_group',
]
def __init__(self, *args, **kwargs):
self.user_company = kwargs.pop('user_company', None)
super().__init__(*args, **kwargs)
self.fields['job_group'].queryset = Jobgroup.objects.none()
But, it will throw error when you try to validate the form using form.is_valid(). So before doing that, update the queryset in the views like this:
def some_view_def(request):
form = JobForm(request.POST)
form.fields['job_group'].queryset = JobGroup.objects.filter(...) # <-- here
if form.is_valid():
# rest of the code

Django filter in ModelForm with specific models

class Report(models.Model):
# ....
product = models.ForeignKey(Product)
class Product(models.Model):
name = models.CharField(max_length=50)
class Item(models.Model):
box = models.ForeignKey(BoxInTransport)
product = models.ForeignKey(Product)
class BoxInTransport(models.Model):
transport = models.ForeignKey(Transport)
box = models.ForeignKey(Box)
This is - in short - the structure of models.
And I have a view which lets me create new report:
class ReportCreateView(CreateView):
model = Report
form_class = ReportForm
def get_form_kwargs(self):
# updating to get argument from url
kwargs = super(DifferenceCreateView, self).get_form_kwargs()
kwargs.update(self.kwargs)
return kwargs
and the form:
class ReportForm(ModelForm):
class Meta:
model = Report
fields = [
'product'
]
def __init__(self, box_nr=None, *args, **kwargs):
super(ReportForm, self).__init__(*args, **kwargs)
self.fields['product'].queryset = ???
How can I get only these products which belong to a specific box? To be more clear:
Only products which:
Item.objects.filter(box__box__box_code=box_nr)
Now I get all Items which I need, but I need to pass self.fields['products'] to only product form with this new Items queryset.
Can you help me?
EDIT
I've tried something like this:
def __init__(self, box_nr=None, *args, **kwargs):
super(ReportForm, self).__init__(*args, **kwargs)
queryset = Item.objects.filter(
box__box__box_code=boxno
)
none_queryset = Product.objects.none()
list_or_products = [p.product for p in queryset]
product_queryset = list(chain(none_queryset, list_or_products))
self.fields['product'].queryset = product_queryset
But, first - it looks little ugly :), second - it doesn't work:
AttributeError: 'list' object has no attribute 'all'
Your __init__ could look something like this:
def __init__(self, box_nr=None, *args, **kwargs):
super(ReportForm, self).__init__(*args, **kwargs)
qs = Product.objects.filter(item__box__box__box_code=box_nr)
self.fields['product'].queryset = qs
Basically, you need a reverse lookup on Product to Item. You can read the relevant documentation here
Note that: item__box__box__box_code=box_nr is based on my understanding of your models. item__box does the reverse lookup. Rest might need some tweaking based on your model definitions.

Passing widget attributes dictionary into Django Form

I am using forms in my Django project, and I want to specify some of the attributes of the widget that I use in my form but am having trouble figuring out how to pass in the attrs dictionary to the widget.
The view.py:
form_schedule_start = WINDOW_Schedule_Form(section_label=" Start",required=True,initial=scheduleStart,attributes={'class':"form-control",'placeholder':".col-md-4"})
The form:
class WINDOW_Schedule_Form(forms.Form):
def __init__(self,*args,**kwargs):
section_label = kwargs.pop('section_label')
initial_value = kwargs.pop('initial')
required_value = kwargs.pop('required')
attributes = kwargs.pop('attributes')
super(WINDOW_Schedule_Form,self).__init__(*args,**kwargs)
self.fields['WINDOW_Schedule'].label=mark_safe(section_label)
self.fields['WINDOW_Schedule'].initial=initial_value
self.fields['WINDOW_Schedule'].required=required_value
self.fields['WINDOW_Schedule'].attrs=attributes
WINDOW_Schedule = forms.CharField(widget=forms.TextInput())
Normally you would just do
WINDOW_Schedule = forms.CharField(widget=forms.TextInput(attrs={'class':"form-control text-center",'placeholder':".col-md-8"}))
but I want to be able to specify the 'class' and 'placeholder' attributes in my views.py.
I keep getting an error that attributes is not defined though. Can anyone tell me what I'm doing wrong?
This Code May Help You Out
class ContactForm(ModelForm):
class Meta:
model = Contact
created = MyDatePicker()
class Uniform(forms):
def __init__(self, *args, **kwargs):
attrs = kwargs.pop("attrs",{})
attrs["class"] = "span3"
kwargs["attrs"] = attrs
super(Uniform, self).__init__(*args, **kwargs)
class MyDatePicker(Uniform,forms.DateInput)
def __init__(self, *args, **kwargs):
attrs = kwargs.pop("attrs",{})
attrs["class"] = "datepick"
attrs["id"] =kwargs.get('datetag', '')
kwargs["attrs"] = attrs
super(MyDatePicker, self).__init__(*args, **kwargs)

How do I add a help_text to a ModelForm?

I know how to add a 'class' or other widget attribute to an automatically built ModelForm:
class ExampleSettingForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ExampleSettingForm, self).__init__(*args, **kwargs)
self.fields['example_field'].widget.attrs['class'] = 'css_class'
class Meta:
model = Example
How do I insert a help_text= into the example_field Field?
As of Django 1.6: You can edit it within the Meta class. Try:
class ExampleSettingForm(ModelForm):
def __init__(self, *args, **kwargs):
super(ExampleSettingForm, self).__init__(*args, **kwargs)
self.fields['example_field'].widget.attrs['class'] = 'css_class'
class Meta:
model = Example
help_texts = {
'example_field': ('Here is some help'),
}
Docs on this are at https://docs.djangoproject.com/en/dev/topics/forms/modelforms/#overriding-the-default-fields. See release notes at http://django.readthedocs.org/en/latest/releases/1.6.html . You can set your own label, help_text and error_messages.
This is what I did in Django 1.9:
class MyModelForm(forms.ModelForm):
class Meta:
model = MyModel
fields = ('__all__')
help_texts = {
"my_field": "This is case sensitive..."
}