英文:
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 = (
('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)
The following is my model form based on the above model.
Form:
class AddRoomForm(forms.ModelForm):
ROOM_CATEGORIES = (
('Regular', 'Regular'),
('Executive', 'Executive'),
('Deluxe', 'Deluxe'),
)
category = forms.CharField(
max_length=9,
widget=forms.RadioSelect(choices=ROOM_CATEGORIES),
)
ROOM_CAPACITY = (
(1, '1'),
(2, '2'),
(3, '3'),
(4, '4'),
)
capacity = forms.CharField(
max_length=9,
widget=forms.RadioSelect(choices=ROOM_CAPACITY),
)
class Meta:
model = Room
fields = ['number', 'category', 'capacity', 'advance']
Here is the views:
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()
# Implemented 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)
I rendered the form like this in my html file.
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" class= "submit submit-right" value="Add" />
</form>
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 <sup>[Django-doc]</sup>.
通过集体智慧和协作来改善编程学习和解决问题的方式。致力于成为全球开发者共同参与的知识库,让每个人都能够通过互相帮助和分享经验来进步。
评论