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

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

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

问题

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

模型:

  1. class Room(models.Model):
  2. class Meta:
  3. number = models.PositiveSmallIntegerField()
  4. CATEGORIES = (
  5. ('Regular', 'Regular'),
  6. ('Executive', 'Executive'),
  7. ('Deluxe', 'Deluxe'),
  8. )
  9. category = models.CharField(max_length=9, choices=CATEGORIES, default='Regular')
  10. CAPACITY = (
  11. (1, '1'),
  12. (2, '2'),
  13. (3, '3'),
  14. (4, '4'),
  15. )
  16. capacity = models.PositiveSmallIntegerField(choices=CAPACITY, default=2)
  17. advance = models.PositiveSmallIntegerField(default=10)
  18. manager = models.CharField(max_length=30)

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

表单:

  1. class AddRoomForm(forms.ModelForm):
  2. ROOM_CATEGORIES = (
  3. ('Regular', 'Regular'),
  4. ('Executive', 'Executive'),
  5. ('Deluxe', 'Deluxe'),
  6. )
  7. category = forms.CharField(
  8. max_length=9,
  9. widget=forms.RadioSelect(choices=ROOM_CATEGORIES),
  10. initial='Regular' # 设置默认选中的单选按钮
  11. )
  12. ROOM_CAPACITY = (
  13. (1, '1'),
  14. (2, '2'),
  15. (3, '3'),
  16. (4, '4'),
  17. )
  18. capacity = forms.CharField(
  19. max_length=9,
  20. widget=forms.RadioSelect(choices=ROOM_CAPACITY),
  21. initial=2 # 设置默认选中的单选按钮
  22. )
  23. class Meta:
  24. model = Room
  25. fields = ['number', 'category', 'capacity', 'advance']

这是视图:

  1. def add_room(request):
  2. if request.method == 'POST':
  3. form = AddRoomForm(request.POST)
  4. if form.is_valid():
  5. room = Room(
  6. number=request.POST['number'],
  7. category=request.POST['category'],
  8. capacity=request.POST['capacity'],
  9. advance=request.POST['advance'],
  10. manager=request.user.username
  11. )
  12. room.save()
  13. # 实现Post/Redirect/Get。
  14. return redirect('../rooms/')
  15. else:
  16. context = {
  17. 'form': form,
  18. 'username': request.user.username
  19. }
  20. return render(request, 'add_room.html', context)
  21. context = {
  22. 'form': AddRoomForm(),
  23. 'username': request.user.username
  24. }
  25. return render(request, 'add_room.html', context)

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

  1. <form method="POST">
  2. {% csrf_token %}
  3. {{ form.as_p }}
  4. <input type="submit" class="submit submit-right" value="Add" />
  5. </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:

  1. class Room(models.Model):
  2. class Meta:
  3. number = models.PositiveSmallIntegerField()
  4. CATEGORIES = (
  5. (&#39;Regular&#39;, &#39;Regular&#39;),
  6. (&#39;Executive&#39;, &#39;Executive&#39;),
  7. (&#39;Deluxe&#39;, &#39;Deluxe&#39;),
  8. )
  9. category = models.CharField(max_length=9, choices=CATEGORIES, default=&#39;Regular&#39;)
  10. CAPACITY = (
  11. (1, &#39;1&#39;),
  12. (2, &#39;2&#39;),
  13. (3, &#39;3&#39;),
  14. (4, &#39;4&#39;),
  15. )
  16. capacity = models.PositiveSmallIntegerField(
  17. choices=CAPACITY, default=2
  18. )
  19. advance = models.PositiveSmallIntegerField(default=10)
  20. manager = models.CharField(max_length=30)

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

Form:

  1. class AddRoomForm(forms.ModelForm):
  2. ROOM_CATEGORIES = (
  3. (&#39;Regular&#39;, &#39;Regular&#39;),
  4. (&#39;Executive&#39;, &#39;Executive&#39;),
  5. (&#39;Deluxe&#39;, &#39;Deluxe&#39;),
  6. )
  7. category = forms.CharField(
  8. max_length=9,
  9. widget=forms.RadioSelect(choices=ROOM_CATEGORIES),
  10. )
  11. ROOM_CAPACITY = (
  12. (1, &#39;1&#39;),
  13. (2, &#39;2&#39;),
  14. (3, &#39;3&#39;),
  15. (4, &#39;4&#39;),
  16. )
  17. capacity = forms.CharField(
  18. max_length=9,
  19. widget=forms.RadioSelect(choices=ROOM_CAPACITY),
  20. )
  21. class Meta:
  22. model = Room
  23. fields = [&#39;number&#39;, &#39;category&#39;, &#39;capacity&#39;, &#39;advance&#39;]

Here is the views:

  1. def add_room(request):
  2. if request. Method == &#39;POST&#39;:
  3. form = AddRoomForm(request.POST)
  4. if form.is_valid():
  5. room = Room(number=request.POST[&#39;number&#39;],
  6. category=request.POST[&#39;category&#39;],
  7. capacity=request.POST[&#39;capacity&#39;],
  8. advance=request.POST[&#39;advance&#39;],
  9. manager=request.user.username)
  10. room.save()
  11. # Implemented Post/Redirect/Get.
  12. return redirect(&#39;../rooms/&#39;)
  13. else:
  14. context = {
  15. &#39;form&#39;: form,
  16. &#39;username&#39;: request.user.username
  17. }
  18. return render(request, &#39;add_room.html&#39;, context)
  19. context = {
  20. &#39;form&#39;: AddRoomForm(),
  21. &#39;username&#39;: request.user.username
  22. }
  23. return render(request, &#39;add_room.html&#39;, context)

I rendered the form like this in my html file.

  1. &lt;form method=&quot;POST&quot;&gt;
  2. {% csrf_token %}
  3. {{ form.as_p }}
  4. &lt;input type=&quot;submit&quot; class= &quot;submit submit-right&quot; value=&quot;Add&quot; /&gt;
  5. &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

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

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

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

  1. from django.conf import settings
  2. class Room(models.Model):
  3. number = models.PositiveSmallIntegerField()
  4. CATEGORIES = (
  5. ('Regular', 'Regular'),
  6. ('Executive', 'Executive'),
  7. ('Deluxe', 'Deluxe'),
  8. )
  9. category = models.CharField(
  10. max_length=9, choices=CATEGORIES, default='Regular'
  11. )
  12. CAPACITY = (
  13. (1, '1'),
  14. (2, '2'),
  15. (3, '3'),
  16. (4, '4'),
  17. )
  18. capacity = models.PositiveSmallIntegerField(choices=CAPACITY, default=2)
  19. advance = models.PositiveSmallIntegerField(default=10)
  20. manager = models.ForeignKey(
  21. settings.AUTH_USER_MODEL, on_delete=models.CASCADE, editable=False
  22. )

ModelForm可以处理创建本身:

  1. from django.contrib.auth.decorators import login_required
  2. @login_required
  3. def add_room(request):
  4. if request.method == 'POST':
  5. form = AddRoomForm(request.POST, request.FILES)
  6. if form.is_valid():
  7. form.instance.manager = request.user
  8. form.save()
  9. return redirect('../rooms/')
  10. else:
  11. form = AddRoomForm()
  12. context = {'form': form, 'username': request.user.username}
  13. 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:

确定