0

Is it possible to save an object through Django HTML form with the value in option tag directly?

<select class="form-control" name="person">
        <option selected disabled>Choose</option>
        {% for person in group %}
        <option value="{{ person }}">{{ person.name }}</option>
        {% endfor %}
</select>
class Group(models.Model):
    group_name = models.CharField(max_length=255, blank=True)
    person = models.ForeignKey(Person, on_delete=models.CASCADE)

    def __str__(self):
        return self.group_name

Tried the above but I get "didn't return a HttpResponse object". I know I can pass an ID but is it possible to save the object directly instead of going to views.py and getting the object via an ID?

Usman Maqbool
  • 3,351
  • 10
  • 31
  • 48
jayimshan
  • 1
  • 3
  • Solved: `person = Person.objects.get(pk=request.POST['person'])` I guess I CAN send objects through form, just the way I was going about in views.py was incorrect. – jayimshan May 09 '19 at 22:34

2 Answers2

0

You can do this using AJAX request, but you still need a view(URL) that creates the object

Hint: How do I POST with jQuery/Ajax in Django?

Ashraf Emad
  • 183
  • 10
0

You can save the object using the value in option tag which is the person name, by fetching the object using the person_name value as below:

Assuming the value you are getting from the option tag as person_name and the object you are trying to save is Group object.

Group.objects.get(person__name=person_name)

and then update the object.

Manu mathew
  • 859
  • 8
  • 25