[英]How can I handle the data of post requests in Django
我想通過用戶向表單添加幾個輸入來接收請求。 我想知道如何分別控制接收到的數據。 在 html 文件中,{% for i in request.POST.items %} 有效。 但是在views.py中,它不是這樣工作的
視圖.py
def debate_create(request):
if request.method == "POST":
content = request.POST
for k,v in content.items:
if k == 'sup_title':
sup_title = SuperTitle()
sup_title.author = request.user
sup_title.super_title = v
sup_title.save()
elif 'img' not in k and 'section' in k:
sub_title = Subtitle()
sub_title.super_title = sup_title.super_title.id
sub_title.sub_title = v
sub_title.save()
elif 'img' in k:
stg = Images()
imgs = request.FILES
stg.images = imgs
stg.sub_title = sub_title.sub_title.id
stg.save()
elif 'section' in k and 'opt' in k:
opt = SelectOption()
opt.sub_title = sub_title.sub_title.id
opt.option = v
return render(request, 'polls/test.html')
模型.py
class SuperTitle(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='debate_author')
super_title = models.CharField(max_length=100)
liker = models.ManyToManyField(User, related_name='debate_liker')
class Subtitle(models.Model):
super_title = models.ForeignKey(SuperTitle, on_delete=models.CASCADE)
sub_title = models.TextField(blank=True)
class Images(models.Model):
sub_title = models.ForeignKey(Subtitle, on_delete=models.CASCADE)
images = models.ImageField(null=True)
class SelectOption(models.Model):
sub_title = models.ForeignKey(Subtitle, on_delete=models.CASCADE)
option = models.CharField(max_length=20)
option_voter = models.ManyToManyField(User)
html
<form method="POST" id="debate_form" action="{% url 'polls:debate_create' %}">
{% csrf_token %}
<input type='text' name='sup_title' placeholder='제목'>
<div id="form_container">
<section id='section_1'>
<input type="text" name="section_1">
<input type="file" name="img_section_1" multiple>
<div id="section_1_div">
<input type="text" name="section_1_opt_1" value="1">
<input type="text" name="section_1_opt_2" value="2">
</div>
<input type="button" value="add option" onclick='add_option(this.id)' id="section_1">
<input type="button" value="sub option" onclick='sub_option(this.id)' id="section_1">
</section>
</div>
<input type="button" value='add content' onclick='add_content()'>
<input type="button" value='sub content' onclick='sub_content()'>
<input type="submit">
</form>
請參考以下鏈接以了解 django 中的請求如何處理 POST 請求。 我想這就是你需要做的。
https://pythonguides.com/django-get-all-data-from-post-request/
讓我知道這是否讓您感到困惑。
HTML 中的 django 語法與 python 中的語法之間存在混淆。
html
{% for i in request.POST.items %}
視圖.py
#for i in request.POST.items >>> syntaxerror
for i in request.POST.items():
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.