0
我有一個顯示的位置列表中的一個模板:使用不同的模板相同的對象
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
。誰能幫忙?
好的,我做到了,但是當我通過'add_office.html'中的表單添加辦公室的location_id沒有保存 - 它是空的 – dominik791