我正在写一个视图来更新数据库中的记录,当我尝试切换到记录进行编辑时,出现错误:
错误:
我从另一个模型的现有视图一对一地编写了代码,所以我不明白错误是什么。我该如何解决?
urls.py
path(
'keys/<int:key_id>/',
views.UpdateKeyView.as_view(),
name='update_key'
),
views.py
class CreateKeyView(
SuccessMessageMixin,
CustomPermissionRequired,
CreateView
):
model = ApiKey
template_name = 'db_visual/create_key.html'
form_class = KeyForm
permission_required = (
'db_visual.add_keys',
)
success_message = "Ключи %(description)s успешно создан!"
def get_success_url(self):
print(self.object.id)
return reverse_lazy(
'update_key',
kwargs={'key_id': self.object.id}
)
class UpdateKeyView(
SuccessMessageMixin,
CustomPermissionRequired,
UpdateView
):
model = ApiKey
pk_url_kwarg = 'key_id'
template_name = 'db_visual/update_key.html'
form_class = KeyForm
success_url = reverse_lazy('keys')
permission_required = (
'db_visual.change_key',
)
success_message = "Ключ <a href='%(url)s'>%(description)s</a> " \
"успешно изменен!"
def get_success_message(self, cleaned_data):
return self.success_message % dict(
cleaned_data,
url=reverse_lazy(
'update_key',
kwargs={'key_id': self.object.id}
),
)
HTML代码create_key
{% for key in api_keys %}
<tr>
<td class="min-col">
<a href="{% url 'update_key' key_id=key.id %}">
{{ key.description}}
</a>
</td>
<td class="min-col">{{ key.open_key }}</td>
<td class="min-col">{{ key.secret_key }}</td>
<td class="min-col">
<a class="btn btn-sm btn-link"
href="{% url 'update_key' key_id=key.id %}">
<i class="far fa-edit fa-lg"></i>
</a>
</tr>
{% endfor %}
HTML代码update_key
<form action="{% url 'update_key' key_id=key.id %}"
method="post" class="col-12" id="key_form">
{% csrf_token %}
<div class="card">
<h2 class="card-header">
<div class="row">
<div class="col-6">
Ключи для {{ key.description }}
</div>
</div>
</h2>
<div class="card-body">
{% include 'db_visual/key_form_body.html' %}
</div>
<div class="card-footer text-muted">
<input type="submit" class="btn btn-primary" value="Сохранить"/>
</div>
</div>
</form>
Model.py
class ApiKey(models.Model):
open_key = models.CharField(max_length=128)
secret_key = models.CharField(max_length=128)
description = models.CharField(max_length=128)
restrict_ip = models.BooleanField()
ip = ArrayField(
models.CharField(max_length=32, blank=False, null=True), size=8, blank=True, null=True
)
valid_to_date = models.DateField()
restrict_methods = models.BooleanField()
allowed_methods = ArrayField(
models.CharField(max_length=32, blank=True, null=True),
size=8, blank=True, null=True
)
forbidden_methods = ArrayField(
models.CharField(max_length=32, blank=True, null=True),
size=8, blank=True, null=True
)
class Meta:
db_table = '"processing"."api_key"'
UPD:当我创建新对象并尝试执行功能get_success_url
时,它会收到相同的错误,但是self.object.id
不会出现错误。
UPD2:发现没有将模型对象传递给update_key
,但不清楚原因。
答案 0 :(得分:-1)
对象名称错误...