I want to receive a request by adding several inputs to the form by the user. I want to know how to control the received data separately. in html file, {% for i in request.POST.items %} it works. but in views.py, it doesn't work like this
views.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')
models.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>
CodePudding user response:
Kindly refer below link to understand how request handle in django for POST requests. I think that's all you need to do.
https://pythonguides.com/django-get-all-data-from-post-request/
Let me know if any this is confusing for you.
CodePudding user response:
There was a confusion between the django syntax in HTML and the syntax in python.
html
{% for i in request.POST.items %}
views.py
#for i in request.POST.items >>> syntaxerror
for i in request.POST.items():