1

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..

h_vm
  • 91
  • 1
  • 12
  • why are you passing two integers with `` and `` in your urls? – arjun Apr 29 '20 at 11:11
  • Show us the link in your template to go for the update form ? – arjun Apr 29 '20 at 11:13
  • trying to make the url look better i guess, so it looks like: /release/1/feature/<1>or <2>/update/... 1st week in django.. Still Exploring.. :-) – h_vm Apr 29 '20 at 11:15
  • 1
    Then you can use slug for this. See [here](https://stackoverflow.com/questions/427102/what-is-a-slug-in-django). – arjun Apr 29 '20 at 11:20
  • not sure what is missing in template. I tho this is all what is required in generic class based view. if i need to add something to reach update form.. what should it be like.? – h_vm Apr 29 '20 at 11:22
  • Url is in the question.. If you are looking for the template where i call the update.. here : Update – h_vm Apr 29 '20 at 11:30

1 Answers1

2

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>
arjun
  • 7,230
  • 4
  • 12
  • 29
  • I am not sure how to tag you in other questions.. So can you please help with this: https://stackoverflow.com/questions/61514226/django-how-to-handle-error-message-in-createview-for-unique-constraint-failed – h_vm Apr 30 '20 at 01:05