我正在创建一个页面,该页面允许用户编辑他或她的名字,其中的模型建立在Django中的AbstractUser
类之上。但是,Django引发了404错误No User matches the given query
:
views.py
@method_decorator(login_required, name='dispatch')
class ChangeInfoView(generic.edit.UpdateView):
model = models.User
template_name = 'myaccount/change_name.html'
form_class = forms.UpdateNameForm
def get_object(self):
return get_object_or_404(models.User, slug=models.User.slug)
def get_success_url(self):
return reverse('profile', kwargs={'slug': self.object.slug})
models.py
class User(util_models.CreationModificationDateMixin, util_models.UrlMixin, AbstractUser):
slug = models.SlugField(unique=True)
avatar = models.ImageField('Avatar', upload_to=upload_to, blank=True, null=True)
recovery_email = models.EmailField(_('Recovery Email'), blank=True, null=True)
about_me_email = models.EmailField(_('About Me Email'), blank=True, null=True)
def __str__(self):
assert isinstance(self.username, object)
return self.username
def save(self, *args, **kwargs):
self.slug = slugify(self.username, allow_unicode=True)
super().save(*args, **kwargs)
self.create_thumbnail()
@property
def get_url_path(self):
return reverse("profile", kwargs={"slug": self.object.slug})
forms.py
class UpdateNameForm(UpdateFormBase):
class Meta:
model = User
fields = ('first_name', 'last_name')
def __init__(self, *args, **kwargs):
super(UpdateNameForm, self).__init__(*args, **kwargs)
self.helper = helper.FormHelper(self)
self.helper.form_show_labels = False
self.helper.form_tag = False
self.helper.layout = layout.Layout(
layout.Div(
layout.Div(
layout.Div(
layout.HTML(fieldtostring("required", "autofocus", type="text", name="first_name", value="")),
layout.HTML(valuetolabel("first_name", "First Name")),
css_class="md-form",
),
),
layout.Div(
layout.Div(
layout.HTML(fieldtostring("required", type="text", name="last_name", value="")),
layout.HTML(valuetolabel("last_name", "Last Name")),
css_class="md-form",
),
),
)
)
myaccount / change_name.html
<div class="modal-body" style="padding-top: 0px;">
<form method="post" action="{% url 'change_name' %}">
{% crispy form %}
<div class="btn-group float-right" role="group" aria-label="Basic example">
<button type="button" class="btn btn-flat btn-sm float-right btn-custom-0" data-dismiss="modal">
<span class="text-secondary custom-text-3">Cancel</span>
</button>
<button type="submit" class="btn btn-flat btn-sm float-right btn-custom-0"><span class="text-primary custom-text-3">Done</span></button>
</div>
</form>
</div>
由于代码很长,因此请假设所有方法(如layouts
,属于django-crispy-form
)都已正确导入并声明。
帮助赞赏?