Rectangle 27 82

To make a field in a ModelField a hidden field, use a HiddenInput widget. The ModelForm uses a sensible default widget for all the fields, you just need to override it when the object is constructed.

class TagStatusForm(forms.ModelForm):
    class Meta:
        model = TagStatus
        widgets = {'tag': forms.HiddenInput()}

python - Django ModelForm to have a hidden input - Stack Overflow

python django django-models django-forms
Rectangle 27 0

Unfortunately, this is less of a Django issue than an HTML question. The HTML specification (RFC1866) says:

At all times, exactly one of the radio buttons in a set is checked. If none of the <INPUT> elements of a set of radio buttons specifies `CHECKED', then the user agent must check the first radio button of the set initially.

However, browsers have historically ignored this and implemented radio buttons in different ways.

HTML also makes this difficult because the "checked" attribute of the <INPUT> tag doesn't take a parameter, so you can't use a customized Django widget that sets this attribute to False or No.

A possible workaround is to put in a little Javascript that runs as part of the document's onLoad event that finds all the radio buttons on the page and sets the 'checked' attribute to false (using JQuery, for example).

I like the workaround with the javascript to erase the checked values. My only fear is that Django won't complain about the empty radio button boxes and evaluate them to false. I'd rather it throw a validation error.

As Andrey mentions below, if a radio button isn't selected, then Django should throw a validation error, since 'required' defaults to True.

That's good to know. I wasn't sure how a BooleanField would impact the RadioSelect widget since it seems like a lot examples that I found use an IntegerField. Thanks for your input.

widget - Python/Django BooleanField model with RadioSelect form defaul...

django widget modelform radio-button
Rectangle 27 0

The issue is not with the saving, but with the validating of your form. Basically, you create a customized version of the model form for Book, with two fields, author and title. By default, the author field would display as a reference browsing widget for the Author type.

However, what you do with author = forms.CharField() is tell the form to display a simple text input field instead of an Author reference selector. When it tries to validate this.. well it can't.

What you need to do is process the author value before validating, you can do this in the clean() function, which you can add to your CustomForm

def clean(self):
    self.cleaned_data['author'] = Author.objects.get_or_create(name=self.cleaned_data['author'])
    return self.cleaned_data

thks @Martin for your reply. But I still get the same error after I have changed. This is actually some of my program. I have more fields but I just can't do the saving into db so thats why im giving a little fields to go thru and yes i'm sure there is something with the validation thing but just can't understand why it giving me this valueError all the time:(

Yea, I guess that wasn't the best idea on my part.. try the updated answer.

thks a million @Martin... my validation is fixed but i still have issue on saving..

Well, catherine's answer is pretty much exactly the same, just removed the extra save() code you had. Anyway, glad you got it fixed.

python - Django error: ValueError - Stack Overflow

python django django-models django-forms django-views
Rectangle 27 0

class KindEditor(forms.Textarea):
    class Media:
        css ={
            'all':(settings.STATIC_ROOT + 'editor/themes/default/default.css',)
        }
        js = (settings.STATIC_ROOT + 'editor/kindeditor-min.js',settings.STATIC_ROOT + 'editor/lang/zh_CN.js',)
    def __init__(self):
        attrs = {}
        attrs['rel'] = 'kind'
        super(KindEditor, self).__init__(attrs)


class NewsAdminForm(forms.ModelForm):
    pass

    class Meta:
        model = News
        widgets = {
            'body':KindEditor()
        }

class NewsAdmin(admin.ModelAdmin):
    form = NewsAdminForm


admin.site.register(News, NewsAdmin)

python - Replace textarea with rich text editor in Django Admin? - Sta...

python django admin
Rectangle 27 0

If the model field has choices set, then the form field's widget will be set to Select, with choices coming from the model field's choices. The choices will normally include the blank choice which is selected by default. If the field is required, this forces the user to make a selection. The blank choice will not be included if the model field has blank=False and an explicit default value (the default value will be initially selected instead).

python - How to remove the unselected item in a select and radio input...

python django forms model choice
Rectangle 27 0

class KindEditor(forms.Textarea):
    class Media:
        css ={
            'all':(settings.STATIC_ROOT + 'editor/themes/default/default.css',)
        }
        js = (settings.STATIC_ROOT + 'editor/kindeditor-min.js',settings.STATIC_ROOT + 'editor/lang/zh_CN.js',)
    def __init__(self):
        attrs = {}
        attrs['rel'] = 'kind'
        super(KindEditor, self).__init__(attrs)


class NewsAdminForm(forms.ModelForm):
    pass

    class Meta:
        model = News
        widgets = {
            'body':KindEditor()
        }

class NewsAdmin(admin.ModelAdmin):
    form = NewsAdminForm


admin.site.register(News, NewsAdmin)

python - Replace textarea with rich text editor in Django Admin? - Sta...

python django admin
Rectangle 27 0

You probably need to remove the ManyToMany field from your Client model, or else carefully exclude it from your form. Unfortunately, the default widget for the ManyToMany field cannot populate the ClientGroupe Model properly (even if the missing field, dt, had been set to autonow=True). This is something you'll either need to break out into another form, or handle in your view.

python - What are the steps to make a ModelForm work with a ManyToMany...

python django django-models django-templates django-forms
Rectangle 27 0

The ModelForm api is very similar to that of the regular Form. The advantage is that you now get model validation in addition to conveniences like default widgets, the instance kwarg, and the save method.

fields
attr
dict
super()
BaseModelForm.__init__
deepcopy
SortedDict
Form
ModelForm
BaseForm

Put the fields in the exclude and add them the way you are doing in the original __init__.

Clean them the same way.

Then, you can override the save method: you can call super() to get the object back and deal with the data in cleaned_data however you want.

class OrderDetailForm(forms.ModelForm):
    # regular fields, not based on bools
    # ...

    class Meta:
        model = Order
        exclude = ('work_type', 'vendor', 'note')
        # or fields = (...other fields )


    def __init__(
        self,
        user,
        can_edit_work_type=None,
        can_edit_vendor=None,
        can_edit_note=None,
        *args,
        **kwargs,
    ):
        super(OrderDetailForm, self).__init__(*args, **kwargs)

        if can_edit_work_type:
            self.fields['work_type'] = forms.ChoiceField(
                                       choices=Order.WORK_TYPE_CHOICES)
        if can_edit_vendor:
            self.fields['vendor'] = forms.ModelChoiceField(
                queryset=Vendor.objects.all(),
                empty_label="Choose a vendor",
            )
        if can_edit_note:
            self.fields['note'] = forms.CharField(widget=forms.Textarea)

    def clean(self):
        # I never call super() in clean .. do I? .. hmmm
        # maybe I should or is sth magic going on?
        # alternately,
        # data = self.cleaned_data
        # let's call super though
        data = super(OrderDetailForm, self).clean()

        if 'note' in data:
            if len(data['note']) < 50:
                # I raise a validation error so .is_valid() comes back False
                # form.errors happens magically ...
                raise forms.ValidationError("Not long enough ...")

        return data

    def save(self, *args, **kwargs):
        data = self.cleaned_data
        # maybe do some stuff here
        # ...

        # commit=True or commit=False could be important
        order = super(OrderDetailForm, self).save(*args, **kwargs)

        if 'note' in data:
            order.note = data['note']

        # ... do other stuff

        # probably ...
        order.save()

        # respect how model forms work.
        return order

So how do just I add a model field to fields under __init__? Can I just do something like self.fields.append('note')? It seems like fields is still a tuple, not a dictionary.

Can you show me an example with my code in your answer?

updated with code. Why do you think fields is a tuple?

In the regular Form, you aren't appending to the fields attr but rather assigning values to its keys.

python - How do I programmatically set fields in ModelForm in Django? ...

python django-forms
Rectangle 27 0

Your code actually does what you need. It renders the radio buttons with no options selected and generate the error message if nothing is selected.

A small note about your form code. I would do it like this:

class myModelForm(forms.ModelForm):

    myboolean = forms.BooleanField(widget=forms.RadioSelect(choices=YES_NO))

    class Meta:
        model = MyModel

Thank you Andrey. After seeing your solution, I reexamined my situation and found my simplified example cut out an important piece of information. A ModelField override that was in place was interfering with the default value. I learned from this problem that RadioSelect fields seem to by have default=None set. The override that I had in place was setting the default to False. (By the way, I was using the init function because I didn't want to trump any default values set by the model, such as label).

Thank you again for your help with this and sorry for the bad example. I was trying to strip the problem down to its core, but missed some information.

Sign up for our newsletter and get our top new questions delivered to your inbox (see an example).

widget - Python/Django BooleanField model with RadioSelect form defaul...

django widget modelform radio-button
Rectangle 27 0

If the model field has choices set, then the form field's widget will be set to Select, with choices coming from the model field's choices. The choices will normally include the blank choice which is selected by default. If the field is required, this forces the user to make a selection. The blank choice will not be included if the model field has blank=False and an explicit default value (the default value will be initially selected instead).

python - How to remove the unselected item in a select and radio input...

python django forms model choice
Rectangle 27 0

class Order(models.Model):
    ...
    # transport =  models.CharField(choices=transport.choices,max_length=25,null=True)
    transport = SelectField(choices=transport.choices,max_length=25,null=True)
    ...
from django.db import models
from django.forms import widgets

class SelectField(models.CharField):
    def formfield(self, **kwargs):
        if self._choices:
            defaults = {'widget': widgets.RadioSelect}
        defaults.update(kwargs)
        return super(SelectField, self).formfield(**defaults)

widget - Python/Django BooleanField model with RadioSelect form defaul...

django widget modelform radio-button