我收到了这个错误,
Reverse for 'profile-update' with no arguments not found. 1 pattern(s) tried: ['profile\\/update/(?P<pk>[\\-\\w]+)/']
表单验证后得到该错误。
我无法重定向它。如何重定向到profile-update
?
views.py
@login_required
def profile_update_view(request, pk):
user = User.objects.get(pk=pk)
form = UserProfileForm(instance=user)
if request.user.is_authenticated and request.user.id == user.id:
if request.method == "POST":
form = UserProfileForm(request.POST, request.FILES, instance=user)
if form.is_valid():
created_prof = form.save(commit=False)
created_prof.user = request.user
created_prof.save()
return redirect('profiles:profile-update')
return render(request, "profiles/profile_form.html", {
"pk": pk,
"form": form,
})
else:
raise PermissionDenied
class ProfileDetailView(LoginRequiredMixin,DetailView):
template_name = 'profiles/profile_detail.html'
def get_object(self):
username = self.kwargs.get("username")
if username is None:
raise Http404
return get_object_or_404(User, username__iexact=username, is_active=True)
models.py
def get_sentinel_user():
return User.objects.get_or_create(username='deleted')[0]
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.SET(get_sentinel_user))
profile_image = models.ImageField(blank=True, upload_to='imgfolder/profile_image/')
magz_cover_name = models.CharField(max_length=20, blank=True, default='')
website = models.URLField(default='', blank=True)
bio = models.TextField(default='', blank=True)
phone = models.CharField(max_length=20, blank=True, default='')
class Meta:
verbose_name = _("UserProfile")
verbose_name_plural = _("UserProfiles")
def __str__(self):
return '%s' % (self.user.username)
def create_profile(sender, **kwargs):
user = kwargs["instance"]
if kwargs["created"]:
user_profile = UserProfile(user=user)
user_profile.save()
post_save.connect(create_profile, sender=User)
urls.py
urlpatterns = [
re_path('update/(?P<pk>[\-\w]+)/', views.profile_update_view, name='profile-update'),
re_path('(?P<username>[\w-]+)/', ProfileDetailView.as_view(), name='profile-detail'),
]
模板
<form action="." method="post" enctype="multipart/form-data" >
{% csrf_token %}
{{form.as_p}}
</form>
答案 0 :(得分:1)
将pk发送到您的个人资料更新视图: 从您的代码中编辑此行:
return redirect('profiles:profile-update', pk=pk)
有关重定向的更多详细信息,请阅读以下内容: https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#django.shortcuts.redirect