我的Django编辑按钮总是重定向到我的创建表单并创建一个新记录。我想要一个允许我编辑现有记录的编辑功能。不知道为什么它会继续返回创建表单!
home.html的:
{% extends 'base.html' %}
{% block content %}
{% for task in tasks %}
<div class="row pt-3">
<h1>{{ task.title }}</h1>
<br>
<p>{{ task.pub_date_pretty }}</p>
<br>
<p>{{ task.summary }}</p>
<br>
<br>
<p>{{ task.user }}</p>
<br>
<br>
</div>
<div class="row pt-3">
<a class="btn btn-primary" href="{% url 'edit' task.id %}">Edit</a>
</div>
{% endfor %}
<br>
<br>
<a class="btn btn-primary" href="{% url 'create' %}">Create</a>
{% endblock %}
views.py:
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from .models import Task
from django.utils import timezone
def home(request):
tasks = Task.objects
return render(request, 'home/home.html', {'tasks': Task.objects.all().order_by('-pub_date')})
def taskdetail(request, task_id):
task = get_object_or_404(Task, pk=task_id)
return render(request, 'home/taskdetail.html', {'task':task})
@login_required
def create(request):
if request.method == "POST":
if request.POST['title'] and request.POST['description']:
task = Task()
task.title = request.POST['title']
task.description = request.POST['description']
task.pub_date = timezone.datetime.now()
task.completed = False
task.user = request.user
task.save()
return render(request, 'home/taskdetail.html', {'task':task})
else:
return render(request, 'home/create.html', {'error':'All fields are required'})
else:
return render(request, 'home/create.html')
@login_required
def edit(request, task_id):
if request.method == "POST":
if request.POST['title'] and request.POST['description']:
task = Task(pk=task_id)
task.title = request.POST['title']
task.description = request.POST['description']
task.pub_date = timezone.datetime.now()
task.completed = False
task.user = request.user
task.save(pk=task_id)
return render(request, 'home/taskdetail.html', {'task':task})
else:
return render(request, 'home/create.html', {'error':'All fields are required'})
else:
return render(request, 'home/create.html')
@login_required(login_url="/accounts/signup")
def delete(request, task_id):
if request.method == "POST":
task = get_object_or_404(Task, pk=task_id)
task.delete()
return render(request, 'home', {'task':task})
urls.py:
from django.urls import path, include
from . import views
urlpatterns = [
path('create', views.create, name='create'),
path('<int:task_id>', views.taskdetail, name='taskdetail'),
path('edit/<int:task_id>', views.edit, name='edit'),
path('delete/<int:task_id>', views.delete, name='delete'),
]
我多次重置服务器并清除了浏览器缓存,但是
我不知道为什么它不会将我发送到我的编辑视图
答案 0 :(得分:1)
复制edit()
方法后,您忘记更改底部的模板名称。
return render(request, 'home/create.html')
答案 1 :(得分:1)
edit
函数中的这一行:return render(request, 'home/create.html')
当您打开该页面时,默认情况下它是GET
请求,因此它会转到此行。您应该渲染编辑页面。而且,使用表单来处理函数中的数据会更好。