[英]Redirect page to dynamic URL Django
我是使用 django 平台創建迷你項目網站並使用基於 function 的視圖的初學者。 我的項目中的一個功能是允許用戶編輯個人信息的個人資料頁面。 這是我的用戶資料models.py :
class UserProfile(models.Model):
user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE, blank=True)
company_name = models.CharField(max_length=50, blank=True)
company_url = models.URLField(max_length=50, blank=True)
country = CountryField(null=True)
AFF_CHOICES = (('Academic','Academic'),
('Business','Business'),
('Non-profit','Non-profit'),
('Industry/Government','Industry/Government'))
affiliation = models.CharField(max_length=50, choices=AFF_CHOICES, null=True, blank=True)
profile_picture = models.ImageField(upload_to='profile_picture', null=True, default='profile_picture/defaultphoto.png')
def __str__(self):
return str(self.user)
這是我的urls.py
app_name = 'dashboard'
urlpatterns = [
path('', dashboard, name='dashboard'),
path('<int:pk>/profile/',profile, name='profile'),
path('<int:pk>/edit_profile/',edit_profile, name='edit_profile'),
如您所見,它將傳遞用戶 PK,因此它看起來像這樣(配置文件頁面上的示例) http://127.0.0.1:8000/dashboard/42/profile/並且已經可以使用。 這是我的個人資料和 edit_profile views.py :
def profile(request, pk):
return render(request, 'dashboard/profile.html')
def edit_profile(request, pk):
user = request.user
form = UserProfileForm(instance=user)
if request.method == 'POST':
form = UserProfileForm(request.POST, request.FILES, instance=user,)
if form.is_valid():
form.save()
messages.success(request, 'Your profile has been updated.')
return redirect('/profile/dashboard/') #The problem is here #Still static
else :
form = UserProfileForm()
context = {'editform':form}
return render(request, 'dashboard/editprofile.html', context)
我已經用 static url 試過這個案例(沒有在 url 上傳遞用戶 PK),它已經可以工作了。 用戶編輯個人資料后,如何正確傳遞用戶 PK。 (我想將它們重定向到 /dashboard/user:pk/profile)。 謝謝
嘗試這個:
from django.urls import reverse
# In your view
return redirect(reverse('dashboard:profile', kwargs={'id': pk}))
嘗試這個:
return redirect('dashboard:profile', pk=pk)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.