0

当我阅读有关模型表单和小部件的文档时,看起来您可以在任何模型表单上使用任何小部件,但是某些默认小部件用于与模型表单字段对应的表单字段。我能够使用表单字段而不是模型表单字段来呈现无线电输入。

我尝试了很多不同的东西,但我似乎无法呈现来自模型字段的模型表单字段的 RadioSelect 小部件。这甚至可能吗?

顺便说一句,我的目标是让无线电输入的初始值与模型字段的当前值(布尔值)相对应。

尝试1:

# views.py
class SettingsView(FormView):
    template_name = 'settings.html'
    success_url = 'settings/saved/'
    form_class = NicknameForm

    def post(self, request, *args, **kwargs):
        profile = request.user.get_profile()
        if request.POST['show_nickname'] == 'False':
            profile.show_nickname = False
            profile.save()         
        elif request.POST['show_nickname'] == 'True':
            profile.show_nickname = True
            profile.save()

        return super(NicknameFormView, self).post(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        """
        To be able to use 'show_nickname_form' instead of plain 'form' in the template.
        """        
        context = super(NicknameFormView, self).get_context_data(**kwargs)
        context["show_nickname_form"] = context.get('form')
        return context


# models.py 
from django.db import models
from django.contrib.auth.models import User

class Profile(models.Model):
    user = models.OneToOneField(User,
                                unique=True,
                                verbose_name='user',
                                related_name='profile')
    show_nickname = models.BooleanField(default=True)


# forms.py
from django import forms
from models import Profile    

CHOICES = (('shows_nickname', 'Yes'), ('hides_nickname', 'No'))

class NicknameForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('show_nickname',)
        widgets = {
            'show_nickname': forms.RadioSelect(attrs={'choices': CHOICES}),
        }

我的模板的一部分:

        <form action='' method="post">
            {{ show_nickname_form.as_ul }} {% csrf_token %}
            <input type="submit" value="Save setttings">
        </form>

从 呈现的形式{{ show_nickname_form.as_ul }}

<li><label for="id_show_nickname_0">show nickname:</label> 
<ul></ul>
</li> 
<div style='display:none'><input type='hidden' name='csrfmiddlewaretoken' value='1BqD6HJbP5e01NVwLtmFBqhhu3Y1fiOw' /></div>`

尝试2: #forms.py from django import forms from models import Profile

class NicknameForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = ('show_nickname',)
        widgets = {
            'show_nickname': forms.RadioSelect(),
        }

尝试 3

# forms.py
CHOICES = ((True, 'On',),
  (False, 'Off',))

class NicknameForm(ModelForm):
    show_nickname = ChoiceField(widget=RadioSelect, choices=CHOICES, initial=True , label='')

    class Meta:
        model = Profile
        fields = ('show_nickname',)

这使得无线电输入很好,但我需要它采用相应模型字段的初始值show_nickname而不是常量True

我正在使用Django 1.4顺便说一句。

4

1 回答 1

1

您需要将其变为 aChoiceField而不是 aBooleanField并为每个选项和 a 进行选择,RadioWidget以便它显示单选按钮。 https://docs.djangoproject.com/en/dev/ref/forms/fields/#django.forms.ChoiceField

如果您想保留布尔字段,您很可能需要做一些黑客行为来创建自己的字段/小部件。


# views.py
class SettingsView(FormView):
    template_name = 'settings.html'
    success_url = 'settings/saved/'
    form_class = NicknameForm

    def get_form(self, form_class):
        """
        Returns an instance of the form to be used in this view.
        """
        form = super(SettingsView, self).get_form(form_class)

        if 'show_nickname' in form.fields:
            profile = self.request.user.get_profile()
            form.fields['show_nickname'].initial = profile.show_nickname

        return form

    def post(self, request, *args, **kwargs):
        profile = request.user.get_profile()
        if request.POST['show_nickname'] == 'False':
            profile.show_nickname = False
            profile.save()
        elif request.POST['show_nickname'] == 'True':
            profile.show_nickname = True
            profile.save()

        return super(NicknameFormView, self).post(request, *args, **kwargs)

    def get_context_data(self, **kwargs):
        """
        To be able to use 'show_nickname_form' instead of plain 'form' in the template.
        """
        context = super(NicknameFormView, self).get_context_data(**kwargs)
        context["show_nickname_form"] = context.get('form')
        return context
于 2013-03-27T14:50:16.427 回答