h_vm
h_vm

Reputation: 91

Django updateView always updating the first element in database

I have a simple model.py which has a ForeignKey relation.

    class Release(models.Model):
        name = models.CharField(max_length=200, db_index=True, unique=True)

    class Feature(models.Model):
        release = models.ForeignKey(Release, on_delete=models.SET_NULL, null=True, related_name='features')
        name = models.CharField(max_length=200, db_index=True, unique=True)

In url.py

        path('release/<int:pk>/feature/<int:pk1>/update/', views.FeatureUpdate.as_view(), name='feature-update'),

In views.py:

    class FeatureUpdate(UpdateView):
        model = Feature
        fields = ['name']

In feature_form.html

    {% block content %}
    <form action="" method="post">
    {% csrf_token %}
    <table>
    {{ form.as_table }}
    </table>
    <input type="submit" value="Submit">
    <input type="button" value="Cancel" onclick="history.back()">
    </form>
    {% endblock %}

Lets say I have 1 release(release-A) and 2 features(feature-A and feature-B) in database.

When i try to edit feature-A it works. However when i try to edit feature-B: the form shows feature-A data and also edits feature-A.

I am new to django and not able to go further. Please help..

Upvotes: 1

Views: 164

Answers (1)

Arjun Shahi
Arjun Shahi

Reputation: 7330

If you are updating feature just pass the feature pk from urls like this.

    path('feature/<int:pk>/update/', views.FeatureUpdate.as_view(), name='feature-update'),

Now in the view provide context_object_name to feature so that your feature.pk will work on the template And also you need to give template_name for the update

class FeatureUpdate(UpdateView):
        model = Feature
        fields = ['name']
        context_object_name='feature'
        template_name='your_template.html'

So your url to call the update will be like this.

<a class="btn btn-primary" href="{% url 'feature-update' feature.pk %}">Update</a>

Upvotes: 2

Related Questions