接下来是问题:我正在为我的网站使用现有模板。我有一个order
页面。我想将自己的模板用于表单
我知道我可以使用{% for field in form %}
来实现它。但我需要展示的不是所有领域。例如,这是我的Order
模型:
class Order(models.Model):
state_choices = ('ACTIVE', 'COMPLETED', 'FROZEN')
order_date = models.DateTimeField(auto_now_add=True)
delivery_time = models.CharField(max_length=100)
address_city = models.CharField(max_length=40)
address_street = models.CharField(max_length=40)
address_building = models.CharField(max_length=40)
state = models.CharField(max_length=200, default='ACTIVE')
client = models.ForeignKey(CustomUser)
我只需要展示:address_city
,address_street
,address_building
和delivery_time
。因为在视图中我只返回当前用户并将其设置为客户端。以下是我保存Order
:
def submit(request):
args = {}
args['form'] = OrderForm
if request.POST:
order_form = OrderForm(request.POST)
if order_form.is_valid():
order_form.save()
user = request.user
address_country = order_form.cleaned_data['address_country']
address_city = order_form.cleaned_data['address_city']
address_building = order_form.cleaned_data['address_building']
delivery_time = order_form.cleaned_data['delivery_time']
new_order = Order(address_country=address_country,
address_city=address_city,
address_building=address_building,
delivery_date=delivery_time, client=user)
new_order.save()
Basket.objects.filter(client=user).delete()
return redirect('/order/')
else:
return render(request, 'order_page.html', args)
我猜new_order
很奇怪,因为order_form.save()
会保存它。但是如何将当前会话的用户设置为Order
到form
?
要理解这一切,请参阅我的OrderForm
代码:
class OrderForm(forms.ModelForm):
class Meta():
model = Order
fields = ['address_city', 'address_street', 'address_building', 'delivery_time']
答案 0 :(得分:0)
我在形式的 init 方法中处理这种逻辑,当在视图中创建表单时,我将请求对象作为kwarg传递给表单以获取其数据来自,然后隐藏适当的字段:
在forms.py ...
中class YourForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
request = kwargs.pop('request', None)
super(YourForm, self).__init__(*args, **kwargs)
if request:
self.fields['field'].initial = process_request_to_get_value(request)
self.fields['field'].widget = forms.HiddenInput()
# More logic here if needed
class Meta:
model = Order
在views.py ...
中def your_view(request):
if request.method == 'POST':
form = YourForm(request.POST, request = request)
if form.is_valid():
form.save()
return HttpResponseRedirect('somewhere')
else:
form = YourForm(request = request)
return render_to_response('template',
{'form': form,},
context_instance = RequestContext(request))