在ModelChoiceField的只读InputField中是否有任何更改数据显示的内容,但是保留了提交表单的对象的主键?
views.py
class BookingCreateView(LoginRequiredMixin, CreateView):
login_url = 'login'
form_class = BookingForm
template_name = 'booking_add.html'
success_url = reverse_lazy('booking_list')
def get_initial(self):
initial = super(BookingCreateView, self).get_initial()
initial['date'] = datetime.datetime.strptime(self.request.GET.get('date'), '%d-%m-%Y')
initial['room'] = get_object_or_404(Room, id=self.request.GET.get('room'))
initial['start'] = get_object_or_404(Period, number=self.request.GET.get('start'))
return initial
def form_valid(self, form):
form.instance.user = self.request.user
return super().form_valid(form)
forms.py
class BookingForm(forms.ModelForm):
class Meta:
model = Booking
fields= ['room', 'date', 'start', 'end']
def __init__(self, *args, **kwargs):
initial_args = kwargs.get('initial', None)
if initial_args:
super(BookingForm, self).__init__(*args, **kwargs)
self.fields['room'].widget = forms.TextInput()
self.fields['start'].widget = forms.TextInput()
self.fields['room'].widget.attrs['readonly'] = True
self.fields['date'].widget.attrs['readonly'] = True
self.fields['start'].widget.attrs['readonly'] = True
self.fields['end'].queryset = Period.objects.get_available_periods(
initial_args['room'], initial_args['date'], initial_args['start'])
def clean(self):
cleaned_data = super(BookingForm, self).clean()
now = timezone.localtime(timezone.now())
bookings = Booking.objects.filter(room=cleaned_data['room'], date=cleaned_data['date'])
booking_start_time = datetime.datetime.combine(cleaned_data['date'], cleaned_data['start'].start, timezone.get_current_timezone())
booking_end_time = datetime.datetime.combine(cleaned_data['date'], cleaned_data['end'].end, timezone.get_current_timezone())
for booking in bookings:
if booking.check_overlap(booking_start_time, booking_end_time):
raise forms.ValidationError
if now > datetime.datetime.combine(cleaned_data['date'],
cleaned_data['start'].end, timezone.get_current_timezone()):
raise forms.ValidationError
return cleaned_data
booking_add.html
{% block content %}
<main>
<div class="reg-form">
<form class="form" method="post" action="">
{% csrf_token %}
<label for="room">Phòng</label>
{{ form.room }}
<label for="date">Ngày</label>
{{ form.date }}
<label for="start">Ca bắt đầu</label>
{{ form.start }}
<label for="end">Ca kết thúc</label>
{{ form.end }}
<button type="submit">Đăng ký</button>
</form>
</div>
</main>
{% endblock %}
我想要的是在标签'Phòng'下的输入,该输入表示Room,使用room对象方法 str ()填充,而不是Room对象的主键,并且提交过程仍会发送主键。有什么方法可以实现?注意:前三个字段必须是只读的,并且它们的数据是通过GET请求给出的。
答案 0 :(得分:0)
我知道,但是我希望现场空间是只读的,并且select小部件不具有该属性。