我是Django和Web开发的新手。我目前正在处理表单,但似乎无法获取POST表单数据。
models.py
class Car(models.Model):
brand = models.CharField(max_length=20)
transmission = models.CharField(max_length=20)
number_plate = models.CharField(max_length=7)
price = models.IntegerField()
available = models.BooleanField(default=True)
views.py
def car_detail_view(request):
form = BookCar()
obj = Car.objects.get(number_plate="1JZ3OG")
context = {
'obj': obj,
'form': form
}
return render(request, "car/car_detail.html", context)
def book_car(request):
form = BuyCar(request.POST)
if form.is_valid():
instance = models.Car.objects.get(number_plate=request.POST.get('number_plate'))
instance.available=False
return redirect('../../')
forms.py
class BookCar(forms.ModelForm):
class Meta:
model = Car
fields = [
'brand',
'transmission',
'number_plate',
'price',
'available'
]
car_detail.html
{% block content %}
<h1>{{ obj.brand }}</h1>
<p>{{ obj.number_plate }}</p>
<p>{{ obj.price }}</p>
<p>{{ obj.available }}</p>
<form class="form" action="." method="post">{% csrf_token %}
<input type="hidden" value="{{obj.number_plate}}">
<input type="submit" value="Book">
</form>
{% endblock %}
每次我单击表单中的Book按钮时,book_car都不从表单获取POST。我已经查看了教程,但无法修复。
答案 0 :(得分:0)
在您看来,尝试这样
def book_car(request):
if request.method == 'POST':
field = request.POST.get('your-field-name')
同样在模板中,您应该这样做:
<form action="/your-name/" method="post">
{% csrf_token %}
{{ form }}
<input type="submit" value="Submit">