首页 文章

哪些模型字段可以与无线电窗口小部件一起使用(通过模型形式)?

提问于
浏览
0

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

我尝试了很多不同的东西,但我只是 can't seem to render a RadioSelect widget of a modelform field which comes from a model field. Is this even possible

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

Attempt 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>`

Attempt 2: #forms.py来自django导入表单来自模型导入配置文件

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

Attempt 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 顺便说一句 .

1 回答

  • 1

    您需要将其设置为 ChoiceField 而不是 BooleanField ,并为每个选项和 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
    

相关问题