我正在尝试为HTML中的“编辑”和“删除”按钮动态编写URL。但是在这里,当我尝试对其进行全部更改时,我只想编辑特定的行数据。
index.html
<tbody>
{% for ads_obj in ads_objs %}
<tr>
<th scope="row">{{ ads_obj.id }}</th>
<td>{{ ads_obj.business_id }}</td>
<td>{{ ads_obj.description }}</td>
<td><a href="{% url 'native:home_ads_edit' %}"><i class="fas fa-edit" style="color:green"></i></a></td>
<td><a href="{% url 'native:home_ads_delete' %}"><i class="fas fa-trash-alt" style="color:red"></i></a></td>
</tr>
{% endfor %}
</tbody>
</table>
view.py
def home_view(request):
if request.method == 'POST':
form = AdsForm(request.POST)
if form.is_valid():
business_id = request.POST.get('business_id')
description = request.POST.get('description')
adsedit_obj = Ads.objects.all().filter(username=username)
if len(adsedit_obj) > 0:
adsedit_obj.update(business_id=business_id,description=description)
return render(request, 'index.html',{})
return render(request, 'login/login.html', {})
urls.py
urlpatterns = [
path('signup/', views.signup_view, name='signup_view'),
path('login/', views.signin_view, name="signin_view"),
path('home/', views.home_view, name="home_view"),
path('adsedit/', views.home_ads_edit, name="home_ads_edit")
]
[模板视图] [1]
[1]: https://i.stack.imgur.com/jLzhE.png
答案 0 :(得分:0)
您应该在URL中传递obj.id
,然后从数据库中获取正确的对象并对其进行编辑。这样的事情会起作用:
template.html
<tbody>
{% for ads_obj in ads_objs %}
<tr>
<th scope="row">{{ ads_obj.id }}</th>
<td>{{ ads_obj.business_id }}</td>
<td>{{ ads_obj.description }}</td>
<td><a href="{% url 'native:home_ads_edit' asd_obj.id %}"><i class="fas fa-edit" style="color:green"></i></a></td>
<td><a href="{% url 'native:home_ads_delete' asd_obj.id %}"><i class="fas fa-trash-alt" style="color:red"></i></a></td>
</tr>
{% endfor %}
</tbody>
</table>
urls.py
urlpatterns = [
path('signup/', views.signup_view, name='signup_view'),
path('login/', views.signin_view, name="signin_view"),
path('home/', views.home_view, name="home_view"),
path('adsedit/<int:obj_id>', views.home_ads_edit, name="home_ads_edit")
]
views.py
def home_view(request, obj_id):
if request.method == 'POST':
form = AdsForm(request.POST)
if form.is_valid():
business_id = request.POST.get('business_id')
description = request.POST.get('description')
adsedit_obj = Ads.objects.filter(pk=obj_id, username=username)
if adsedit_obj:
adsedit_obj.update(business_id=business_id,description=description)
return render(request, 'index.html',{})
return render(request, 'login/login.html', {})