在Django中如何默认’选中’单选按钮中的值?

huangapple go评论78阅读模式
英文:

How to 'check' a value in a radio button by default in Django?

问题

我编写了一个模型表单。我使用了小部件来创建单选按钮,我希望在呈现表单时默认选中特定的单选按钮,以在我的HTML文件中呈现表单。

模型:

class Room(models.Model):
    class Meta:
        number = models.PositiveSmallIntegerField()
    CATEGORIES = (
        ('Regular', 'Regular'),
        ('Executive', 'Executive'),
        ('Deluxe', 'Deluxe'),
    )
    category = models.CharField(max_length=9, choices=CATEGORIES, default='Regular')
    CAPACITY = (
        (1, '1'),
        (2, '2'),
        (3, '3'),
        (4, '4'),
    )
    capacity = models.PositiveSmallIntegerField(choices=CAPACITY, default=2)
    advance = models.PositiveSmallIntegerField(default=10)
    manager = models.CharField(max_length=30)

以下是基于上述模型的模型表单。

表单:

class AddRoomForm(forms.ModelForm):
    ROOM_CATEGORIES = (
        ('Regular', 'Regular'),
        ('Executive', 'Executive'),
        ('Deluxe', 'Deluxe'),
    )

    category = forms.CharField(
        max_length=9,
        widget=forms.RadioSelect(choices=ROOM_CATEGORIES),
        initial='Regular'  # 设置默认选中的单选按钮
    )

    ROOM_CAPACITY = (
        (1, '1'),
        (2, '2'),
        (3, '3'),
        (4, '4'),
    )

    capacity = forms.CharField(
        max_length=9,
        widget=forms.RadioSelect(choices=ROOM_CAPACITY),
        initial=2  # 设置默认选中的单选按钮
    )

    class Meta:
        model = Room
        fields = ['number', 'category', 'capacity', 'advance']

这是视图:

def add_room(request):
    if request.method == 'POST':
        form = AddRoomForm(request.POST)
        if form.is_valid():
            room = Room(
                number=request.POST['number'],
                category=request.POST['category'],
                capacity=request.POST['capacity'],
                advance=request.POST['advance'],
                manager=request.user.username
            )
            room.save()
            # 实现Post/Redirect/Get。
            return redirect('../rooms/')
        else:
            context = {
                'form': form,
                'username': request.user.username
            }
            return render(request, 'add_room.html', context)
    context = {
        'form': AddRoomForm(),
        'username': request.user.username
    }
    return render(request, 'add_room.html', context)

我在HTML文件中这样呈现表单:

<form method="POST">
  {% csrf_token %}
  {{ form.as_p }}
  <input type="submit" class="submit submit-right" value="Add" />
</form>

我在views.py文件中使用'initial'关键字来设置默认选中的单选按钮。上面的代码中,我已经为“category”和“capacity”字段设置了默认值,以便在呈现表单时默认选中这些选项。

英文:

I wrote a model form. I used widgets to make radio buttons and I want a particular radio button to be checked by default while rendering the form in my html file.

Model:

class Room(models.Model):
    class Meta:
    number =  models.PositiveSmallIntegerField()
    CATEGORIES = (
        (&#39;Regular&#39;, &#39;Regular&#39;),
        (&#39;Executive&#39;, &#39;Executive&#39;),
        (&#39;Deluxe&#39;, &#39;Deluxe&#39;),
    )
    category = models.CharField(max_length=9, choices=CATEGORIES, default=&#39;Regular&#39;)
    CAPACITY = (
        (1, &#39;1&#39;),
        (2, &#39;2&#39;),
        (3, &#39;3&#39;),
        (4, &#39;4&#39;),
    )
    capacity = models.PositiveSmallIntegerField(
        choices=CAPACITY, default=2
        )
    advance = models.PositiveSmallIntegerField(default=10)
    manager = models.CharField(max_length=30)

The following is my model form based on the above model.

Form:

class AddRoomForm(forms.ModelForm):
    ROOM_CATEGORIES = (
        (&#39;Regular&#39;, &#39;Regular&#39;),
        (&#39;Executive&#39;, &#39;Executive&#39;),
        (&#39;Deluxe&#39;, &#39;Deluxe&#39;),
    )

    category = forms.CharField(
        max_length=9,
        widget=forms.RadioSelect(choices=ROOM_CATEGORIES),
    )

    ROOM_CAPACITY = (
        (1, &#39;1&#39;),
        (2, &#39;2&#39;),
        (3, &#39;3&#39;),
        (4, &#39;4&#39;),
    )

    capacity = forms.CharField(
        max_length=9,
        widget=forms.RadioSelect(choices=ROOM_CAPACITY),
    )
    class Meta:
        model = Room
        fields = [&#39;number&#39;, &#39;category&#39;, &#39;capacity&#39;, &#39;advance&#39;]

Here is the views:

def add_room(request):
    if request. Method == &#39;POST&#39;:
        form = AddRoomForm(request.POST)
        if form.is_valid():
            room = Room(number=request.POST[&#39;number&#39;],
                    category=request.POST[&#39;category&#39;],
                    capacity=request.POST[&#39;capacity&#39;],
                    advance=request.POST[&#39;advance&#39;],
                    manager=request.user.username)
            room.save()
            # Implemented Post/Redirect/Get.
            return redirect(&#39;../rooms/&#39;)
        else:
            context = {
                &#39;form&#39;: form,
                &#39;username&#39;: request.user.username
                }
            return render(request, &#39;add_room.html&#39;, context)
    context = {
            &#39;form&#39;: AddRoomForm(),
            &#39;username&#39;: request.user.username
            }
    return render(request, &#39;add_room.html&#39;, context)

I rendered the form like this in my html file.

&lt;form method=&quot;POST&quot;&gt;
  {% csrf_token %}
  {{ form.as_p }}
  &lt;input type=&quot;submit&quot; class= &quot;submit submit-right&quot; value=&quot;Add&quot; /&gt;
&lt;/form&gt;

I read somewhere that I can use 'initial' keyword in my views.py file but I don't understand how can I use it. Can someone please help me with it?

答案1

得分: 0

通过覆盖字段,您会失去与底层模型字段的绑定。只需指定小部件:

class AddRoomForm(forms.ModelForm):
    class Meta:
        model = Room
        fields = ['number', 'category', 'capacity', 'advance']
        widgets = {'category': forms.RadioSelect, 'capacity': forms.RadioSelect}

对于经理,最好使用ForeignKey与用户模型一起工作:

from django.conf import settings

class Room(models.Model):
    number = models.PositiveSmallIntegerField()
    CATEGORIES = (
        ('Regular', 'Regular'),
        ('Executive', 'Executive'),
        ('Deluxe', 'Deluxe'),
    )
    category = models.CharField(
        max_length=9, choices=CATEGORIES, default='Regular'
    )
    CAPACITY = (
        (1, '1'),
        (2, '2'),
        (3, '3'),
        (4, '4'),
    )
    capacity = models.PositiveSmallIntegerField(choices=CAPACITY, default=2)
    advance = models.PositiveSmallIntegerField(default=10)
    manager = models.ForeignKey(
        settings.AUTH_USER_MODEL, on_delete=models.CASCADE, editable=False
    )

ModelForm可以处理创建本身:

from django.contrib.auth.decorators import login_required

@login_required
def add_room(request):
    if request.method == 'POST':
        form = AddRoomForm(request.POST, request.FILES)
        if form.is_valid():
            form.instance.manager = request.user
            form.save()
            return redirect('../rooms/')
    else:
        form = AddRoomForm()
    context = {'form': form, 'username': request.user.username}
    return render(request, 'add_room.html', context)

注意:您可以使用**@login_required**装饰器将视图限制为经过身份验证的用户。

英文:

By overriding the field, you lose the binding with the underlying model field. Just specify the widget:

<pre><code>class AddRoomForm(forms.ModelForm):
class Meta:
model = Room
fields = ['number', 'category', 'capacity', 'advance']
<b>widgets</b> = {'category': forms.RadioSelect, 'capacity': forms.RadioSelect}</code></pre>

It is probably also better to work with a ForeignKey to the user model for the manager:

<pre><code>from django.conf import settings

class Room(models.Model):
number = models.PositiveSmallIntegerField()
CATEGORIES = (
('Regular', 'Regular'),
('Executive', 'Executive'),
('Deluxe', 'Deluxe'),
)
category = models.CharField(
max_length=9, choices=CATEGORIES, default='Regular'
)
CAPACITY = (
(1, '1'),
(2, '2'),
(3, '3'),
(4, '4'),
)
capacity = models.PositiveSmallIntegerField(choices=CAPACITY, default=2)
advance = models.PositiveSmallIntegerField(default=10)
<b>manager</b> = models.ForeignKey(
settings.AUTH_USER_MODEL, on_delete=models.CASCADE, editable=False
)</code></pre>

and the ModelForm can handle the creation itself:

<pre><code>from django.contrib.auth.decorators import login_required

@login_required
def add_room(request):
if request.method == 'POST':
form = AddRoomForm(request.POST, request.FILES)
if form.is_valid():
form.instance.manager = request.user
<b>form.save()</b>
return redirect('../rooms/')
else:
form = AddRoomForm()
context = {'form': form, 'username': request.user.username}
return render(request, 'add_room.html', context)</code></pre>


> Note: You can limit views to a view to authenticated users with the
> @login_required decorator&nbsp;<sup>[Django-doc]</sup>.

huangapple
  • 本文由 发表于 2023年1月9日 05:24:55
  • 转载请务必保留本文链接:https://go.coder-hub.com/75051422.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定