我正在尝试一件非常简单的事情。我有一个客户数据库。现在我正在建立一个网站,我选择其中一个客户并编辑有关它的信息。完全相同的是在您选择一个“视图”的管理页面中,您可以更改值。
不幸的是我犯了一个错误。
这是我的代码:
urls.py
from django.conf.urls import url
from django.contrib import admin
from Customer import views
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^customerDetails/(?P<pk>\d+)/$', views.customer_details, name='customer_details'),
url(r'^customerDetails/(?P<pk>\d+)/edit/$', views.edit_customer, name='edit_customer'),
url(r'^admin/', admin.site.urls),
]
views.py
def home(request):
customers = Customer.objects.all()
return render(request, 'home.html', {'customers': customers})
def customer_details(request, pk):
customerDetails = get_object_or_404(Customer, pk=pk)
return render(request, 'customerDetails.html', {'customerDetails': customerDetails})
def edit_customer(request, pk):
user = User.objects.first()
customerDataSet = get_object_or_404(Customer, pk=pk)
if request.method == 'POST':
form = EditCustomerForm(request.POST, instance=customerDataSet)
if form.is_valid():
form.save()
return redirect('customer_details', pk=customerDataSet.pk)
else:
form = EditCustomerForm(instance=customerDataSet)
return render(request, 'edit_customer.html', {'customerDataSet': customerDataSet, 'form': form})
modely.py
class Customer(models.Model):
someId = models.IntegerField()
customerName = models.CharField(max_length=50)
#with some more fields
class customerDetails(models.Model):
customerName = models.CharField(max_length=50)
#with some more fields
formy.py
from django import forms
from .models import Customer
class EditCustomerForm(forms.ModelForm):
class Meta:
model = Customer
fields = ['someId', 'customerName']
edit_customer.html
{% extends 'base.html' %}
{% block title %}Edit a customer{% endblock %}
{% block breadcrumb %}
<li class="breadcrumb-item"><a href="{% url 'home' %}">Customer</a></li>
<li class="breadcrumb-item"><a href="{% url 'customer_details' customerDetails.pk %}">{{ customerDetails.customerName }}</a></li>
<li class="breadcrumb-item active">Edit customer</li>
{% endblock %}
{% block content %}
<form method="post">
{% csrf_token %}
{{form.as_p}}
<button type="submit" class="btn btn-success">Post</button>
</form>
{% endblock %}
我收到了错误:
Exception Type: NoReverseMatch
Exception Value: Reverse for 'customer_details' with arguments '('',)' not found. 1 pattern(s) tried: ['customerDetails/(?P<pk>\\d+)/$']
你能帮我在我的代码中找到错误。
提前致谢!
答案 0 :(得分:0)
我得到了答案。我的 edit_customer.html 错了。
该行:
<li class="breadcrumb-item"><a href="{% url 'customer_details' customerDetails.pk %}">{{ customerDetails.customerName }}</a></li>
应该是:
<li class="breadcrumb-item">{{ customerDataSet.customerName }}</li>