How to transfer edit method of an ID to a button/links in Django?

可紊 提交于 2019-12-25 07:35:30

问题


This is the code in my ulrs.py

url(r'^viewguides/detail/(?P<id>\d+)/edit/$', views.post_update, name='update'),

Now I want to make it look like this:

<a href="/detail/(?P<id>\d+)/edit" class="btn btn-default btn-lg" style="background-color: transparent;"><font color="Orange"> EDIT </font></a><hr>

So that I can edit the certain ID that I want to. But it gives me an error. How do you do it? or is there any other way? I'm new to Django.


回答1:


I just asked my colleagues who have some experience in Django. The answer is very simple.

you just need to create this function in "models.py" :

def get_absolute_url(self):
    return "/viewguides/detail/%s/" %(self.id)

and then you can call it in the html by:

<a href="{{obj.get_absolute_url}}edit" class="btn">EDIT</a>

Every time you click the btn EDIT, it will take you to the following edit page with the given id (id that contains the forms/models of the user).




回答2:


You must use the url tag in your template, something like this:

<a href="{% url update guide.id %}">EDIT</a>

Where "update" is the name found in urls.py and "guide" the instance you want to update.



来源:https://stackoverflow.com/questions/40066882/how-to-transfer-edit-method-of-an-id-to-a-button-links-in-django

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!