我有一个显示位置列表的模板:
list_of_locations.html
{% for loc in loc_list %}
<p>
Total desks: {{loc.total_desks}}
</p>
<p>
Free desks: {{loc.free_desks}}
</p>
<p>
<a href="{% url 'cowork:offices:add' %}" class="btn btn-primary">Rent desk</a>
</p>
我还有另一个显示表单的模板来添加办公室:
office_add.html:
<form class="form" method="POST" action="{% url 'cowork:offices:add' %}">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Add" class="btn btn-primary" />
</form>
型号:
class Location(models.Model):
city = models.CharField(max_length=200)
total_desks = models.IntegerField(verbose_name='Total desks')
reserved_desks = models.IntegerField(verbose_name='Reserved desks')
class Desk(models.Model):
location = models.OneToOneField(Location, related_name='desks')
rent_start_date = models.DateTimeField(null=True)
rent_end_date = models.DateTimeField(null=True)Forms:
class OfficeCreationForm(forms.ModelForm):
class Meta:
model = Desk
fields = ('location', 'rent_start_date', 'rent_end_date')
查看:
def search(request):
loc_list = Location.objects.all()
return render(request, 'list_of_locations.html', 'loc_list': loc_list)
class OfficeAddView(UserMixin, views.LoginRequiredMixin, generic.FormView):
form_class = forms.OfficeCreationForm
template_name = "cowork/offices/company/office_add.html"
success_url = reverse_lazy('cowork:offices:list')
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.company = self.user.companies.first()
self.object.owner = self.request.user
self.object.save()
return HttpResponseRedirect(self.get_success_url())
现在,无论用户在list_of_locations.html
中选择了哪个对象,系统都会要求用户选择office_add.html
中的桌面。我想更改它,以便在点击list_of_locations.html
中的特定对象时,用户被重定向到office_add.html
但已经选择了desk.location,当他/她保存表单时,desk.location将是用户在list_of_locations.html
中点击的那个。有人可以帮忙吗?
答案 0 :(得分:0)
只需将list_of_locations.html
的最后一行更改为:
<a href="{% url 'cowork:offices:add' %}?location={{ loc.id }}" class="btn btn-primary">Rent desk</ai>
另外我想如果您在location
中停用OfficeCreationForm
字段会很好,这样用户就无法更改它。