0

I have something like this in my template.

<form action="" method="POST">
    {% csrf_token %}
     <select name='section'>
      {% for item in all_sections %}
              <option>{{ item.SectionName }}</option>
      {% endfor %}
     </select>
</form>

and in my view.py page:

obj=models.Section.objects.all()
context={
    'all_sections':obj,
}
return render(request,'matab/add-service.html',context)

but i get this is error while saving data:

Cannot assign "'{item}'": "Services.Section" must be a "Section" instance.

also my models.py is like this:

class Section(models.Model):
SectionName=models.CharField(max_length=50)
SectionId=models.CharField(max_length=10)

class Services(models.Model):
Section=models.OneToOneField(
    Section,
    on_delete=models.CASCADE,
)

how can i solve it?

4
  • 1
    Why are you not using django forms? Commented Aug 6, 2019 at 10:47
  • @IainShelvington they asked me to not working with forms Commented Aug 6, 2019 at 10:50
  • That's just making a lot more work for yourself... options should have a value <option value="{{ item.id }}"> Commented Aug 6, 2019 at 10:53
  • 1
    But seriously, just use a ModelForm and it will handle most of the input rendering and input cleaning/conversion Commented Aug 6, 2019 at 10:55

1 Answer 1

2

Services.Section is a OneToOneField, so you need to assign Section instance, not its name.

Depending on your code, it might work if you set the option value to the pk.

 <select name='section'>
  {% for item in all_sections %}
          <option value="{{ item.pk }}">{{ item.SectionName }}</option>
  {% endfor %}
 </select>

As Iain suggests in the comments, it would be better to change your views to use Django forms instead of manually render select inputs.

Sign up to request clarification or add additional context in comments.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.