簡體   English   中英

如何將 url 參數傳遞到視圖中以供其他類函數和模板使用

[英]How to pass a url parameter into the views to be used by other class functions and the template

拜托,我有一個嚴重的問題,這讓我好幾天都犯了各種各樣的錯誤。 有一些我想實現但不知道如何實現的功能。 任何幫助將不勝感激。

我想創建一個注冊表格,用於注冊用戶並在他們注冊后將他們發送到他們的個人資料頁面。 我嘗試通過嘗試將用戶在表單中填寫的用戶名傳遞到我的個人資料視圖的 urls 參數來執行此操作。 但是,我不確切知道如何執行此操作,而且我在網上找到的每個代碼只會導致我出錯。 我是 Django 的新手。

除此之外,我想創建我的個人資料視圖,這樣如果用戶搜索他們自己的模板,他們就可以編輯它,我為此使用了 UpdateView,如果它不是他們的個人資料,那么他們只能以只讀方式查看它,我為此使用了 detailView。

另外,請有人也可以幫助我了解如何將 url 參數傳遞到基於類的視圖中,視圖中的所有函數如何訪問此參數。 如何在基於類的視圖中的另一個函數中使用基於類的視圖中的函數的變量。 也是使用 url 參數和重定向在不同視圖之間傳輸變量的唯一方法。

請注意,我使用了自定義用戶模型

這是我目前的錯誤當前錯誤信息

錯誤回溯

Traceback (most recent call last):
  File "C:\Users\Elisha\AppData\Local\Programs\Python\Python38\lib\site- 
packages\django\core\handlers\exception.py", line 47, in inner
    response = get_response(request)
  File "C:\Users\Elisha\AppData\Local\Programs\Python\Python38\lib\site- 
packages\django\core\handlers\base.py", line 179, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Elisha\AppData\Local\Programs\Python\Python38\lib\site- 
packages\django\views\generic\base.py", line 73, in view
    return self.dispatch(request, *args, **kwargs)
  File "C:\Users\Elisha\AppData\Local\Programs\Python\Python38\lib\site- 
packages\django\views\generic\base.py", line 101, in dispatch
    return handler(request, *args, **kwargs)
  File "C:\Users\Elisha\AppData\Local\Programs\Python\Python38\lib\site- 
packages\django\views\generic\edit.py", line 172, in post
    return super().post(request, *args, **kwargs)
  File "C:\Users\Elisha\AppData\Local\Programs\Python\Python38\lib\site- 
packages\django\views\generic\edit.py", line 142, in post
    return self.form_valid(form)
  File "c:\MouauEasyGo\user\views.py", line 38, in form_valid
    return HttpResponseRedirect(self.get_success_url())
  File "c:\MouauEasyGo\user\views.py", line 55, in get_success_url
    return reverse('profile', args=(self.kwargs['name_of_user']))
  File "C:\Users\Elisha\AppData\Local\Programs\Python\Python38\lib\site- 
packages\django\urls\base.py", line 87, in reverse
    return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs))
  File "C:\Users\Elisha\AppData\Local\Programs\Python\Python38\lib\site- 
packages\django\urls\resolvers.py", line 685, in _reverse_with_prefix
    raise NoReverseMatch(msg)

Exception Type: NoReverseMatch at /user/register/
Exception Value: Reverse for 'profile' with arguments '('a', 'g', 'e')' not found. 1 pattern(s) tried: ['user/profile/(?P<username>[^/]+)/$']

下面是我的代碼

網址.py

from django.urls import path
from user import views as user_views


urlpatterns = [
    path('profile/<str:username>/', user_views.profile_update_view.as_view(), name="profile"),
    path('register/', user_views.user_register_view.as_view(), name="register"),
]

視圖.py

class user_register_view(CreateView):
    template_name = "user/register.html"
    form_class = UserRegistrationForm
    model = NewUser


    # I had to override the form_valid method and added form to the self parameter since get_success_url can't access form directly

    def form_valid(self, form):
        self.form = form
        if form.is_bound:
            self.kwargs['name_of_user'] = form.cleaned_data['user_name']
        return HttpResponseRedirect(self.get_success_url())

    def get_context_data(self, **kwargs):
        data = super().get_context_data(**kwargs)
        try:
            data['name_of_user'] = self.kwargs['name_of_user']
        except KeyError:
            return data
        return data

    def get_queryset(self):
        qs = super().get_queryset()
        return qs.filter(name__startswith=self.kwargs[self.request.user.user_name])

    # if the user's username is in slug, then use it in the profile's url else then pick the username from the form and use instead
    def get_success_url(self):
        if self.kwargs['name_of_user']:
            return reverse('profile', args=(self.kwargs['name_of_user']))


# this is the profile page as viewed by the owner of the profile
# the viewer passes the test only if they are the logged in user
# if they are not, then they are redirected to the the
# profile_detail_view.
class profile_update_view(UserPassesTestMixin, UpdateView):
    model = Profile
    fields = ['date_of_birth', 'country', 'about', 'image', ]
    template_name = 'user/profile_update_form.html'

    def get_object(self):
        user = self.request.user
        return get_object_or_404(Profile, pk=user.id)

    # try to get the user_name from the current user.
    # if the user is an Anoynmous user then just redirect to detail page
    def test_func(self):
        try:
            x = self.request.user.user_name
            y = self.kwargs.get('name_of_user')
            if x == y:
                return True
            else:
                return redirect('profile_detail_view.as_view()')
        except AttributeError:
            return redirect('profile_detail_view.as_view()')


# this is the profile page as viewed by the general public
# this view can only be reached if the current logged  in user
# is not the one access the view
class profile_detail_view(DetailView):
    template_name = "user/profile_detail.html"
    model = Profile

    def get_object(self):
        user = self.request.user
        return get_object_or_404(Profile.objects.get(pk=user.id))

表格.py

class UserRegistrationForm(UserCreationForm):
    date_of_birth = forms.DateField(required=True)
    country = forms.CharField(max_length=50, required=True)
    image = forms.ImageField(required=False)
    about = forms.CharField(widget=forms.Textarea, required=False)

    class Meta:
        model = NewUser
        fields = ['email', 'user_name', 'first_name', 'last_name', ]

    # save profile info as well as the user info in the form
    def save(self, commit=True):
        if not commit:
            raise NotImplementedError(
                "Can't create User and UserProfile without database save")
        user = super(UserRegistrationForm, self).save(commit=True)
        user_name = self.cleaned_data['user_name']
        email = self.cleaned_data['email']
        first_name = self.cleaned_data['first_name']
        last_name = self.cleaned_data['last_name']
        user, created = NewUser.objects.get_or_create(user_name=user_name, email=email, first_name=first_name, last_name=last_name)
        user.save()
        user_profile = Profile(
            user=user,
            about=self.cleaned_data['about'],
            date_of_birth=self.cleaned_data['date_of_birth'],
            country=self.cleaned_data['country']
        )
        user_profile.save()
        return user, user_profile

模型.py

class CustomAccountManager(BaseUserManager):

    def create_superuser(self, email, user_name, first_name, last_name, password, **other_fields):

        other_fields.setdefault('is_staff', True)
        other_fields.setdefault('is_superuser', True)
        other_fields.setdefault('is_active', True)

        if other_fields.get('is_staff') is not True:
            raise ValueError('Superuser must be assigned to is_staff=True.')
        if other_fields.get('is_superuser') is not True:
            raise ValueError(
                'Superuser must be assigned to is_superuser=True.')

        return self.create_user(email, user_name, first_name, last_name, password, **other_fields)

    def create_user(self, email, user_name, first_name, last_name, password, **other_fields):

        if not email:
            raise ValueError(_('You must provide an email address'))

        email = self.normalize_email(email)
        user = self.model(email=email, user_name=user_name, first_name=first_name, last_name=last_name, **other_fields)
        user.set_password(password)
        user.save()
        return user


class NewUser(AbstractBaseUser, PermissionsMixin):

    email = models.EmailField(_('email address'), unique=True)
    user_name = models.CharField(max_length=150, unique=True)
    first_name = models.CharField(max_length=150, unique=True)
    last_name = models.CharField(max_length=150)
    is_staff = models.BooleanField(default=False)
    is_active = models.BooleanField(default=False)

    objects = CustomAccountManager()

    USERNAME_FIELD = 'email'
    REQUIRED_FIELDS = ['user_name', 'first_name', 'last_name']

    def __str__(self):
        return self.user_name


class Profile(models.Model):
    user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
    image = models.ImageField(default="default.jpg", upload_to="profile image/")
    about = models.TextField(_('about'), max_length=500, blank=True)
    date_of_birth = models.DateField(default=timezone.now)
    country = models.CharField(max_length=20, blank=True, null=True)

    def __str__(self):
        return f"{self.user}'s profile"

任何輸入將不勝感激。 如果需要任何其他信息,請告訴我。 在此先感謝您的幫助。

讓我舉個例子吧:

模板:


    <form method="GET" action="{% url 'register' %}">
        <div class="input-group">
            <input name="q" type="text" class="form-control" placeholder="Enter name..." />
            <span class="input-group-append">
                <input class="btn btn-secondary" type="submit" name="btn" value="Submit" />
            </span>
        </div>
    </form>

URL: path('register/', views.register, name='register'),

看法:

def register(request):
    name = request.GET.get('q')
    # redirect the page with this information.

實現參考 - 查看此處執行的search操作。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM