Eimantas
Eimantas

Reputation: 429

Django forms - form field for each model

I am stuck with a problem - I want to add a simple form field to edit the objects that I am looping through in the template. Here's my model:

class Topic(BaseModel):
name = models.TextField()

Here's my model form:

class TopicForm(forms.ModelForm):
class Meta:
    model = Topic
    fields = ["name"]

And here's my views:

def App(request):
    tname = Topic.objects.get(pk=1)
    if request.method == "POST":
        form = TopicForm(data = request.POST, instance=tname)
        if form.is_valid():
            form.save()

And my template is simple:

{% for lecture in lectures %}
<form action="/app/" method="POST">
{% csrf_token %}
{{ form }}
<input type="submit" value="Post">
</form>
{% endfor %}

The thing is that I want to have a form field to edit EACH model not just one that has a pk of 1... how do I do that ?

Upvotes: 2

Views: 546

Answers (2)

faph
faph

Reputation: 1815

More specifically, you probably want to look into Model formsets. See https://docs.djangoproject.com/en/1.6/topics/forms/modelforms/#changing-the-queryset. Then you can directly give a queryset as initial data.

Upvotes: 0

bozdoz
bozdoz

Reputation: 12870

I think you need to do objects.all() instead of get(pk=1). Then loop over those objects, and save them to a list that you save to the context. Something like this:

tnames = Topic.objects.all()
lectures = []
for tname in tnames:
  lectures.append(TopicForm(instance=tname))

context = { 
  'lectures' : lectures
}

Upvotes: 1

Related Questions