模块“accounts.views”没有属性“signup”

2024-05-01 21:55:22 发布

您现在位置:Python中文网/ 问答频道 /正文

File "/Users/work/Projects/blog/myblog/urls.py", line 22, in <module>
    path('post/<int:pk>/signup/', views.signup, name="signup"),
AttributeError: module 'accounts.views' has no attribute 'signup'

我正在尝试使用此指南通过邮件进行注册https://shafikshaon.medium.com/user-registration-with-email-verification-in-django-8aeff5ce498d

myblog/views.py

import json
from urllib import request

from django.views import View
from django.views.generic import ListView, DetailView
from django.views.generic.edit import CreateView, UpdateView, DeleteView
from django.urls import reverse_lazy
from .models import Post, Comment
from .forms import CommentForm


from django.contrib.auth import get_user_model
from django.contrib.auth.models import User
from django.contrib.auth.tokens import default_token_generator
from django.contrib.sites.shortcuts import get_current_site
from django.core.mail import EmailMessage
from django.http import HttpResponse
from django.shortcuts import render
from django.template.loader import render_to_string
from django.utils.encoding import force_bytes
from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode

UserModel = get_user_model()
from .forms import SignUpForm
from .tokens import account_activation_token


def signup(request):
    if request.method == 'GET':
        return render(request, 'signup.html')
    if request.method == 'POST':
        form = SignUpForm(request.POST)
        # print(form.errors.as_data())
        if form.is_valid():
            user = form.save(commit=False)
            user.is_active = False
            user.save()
            current_site = get_current_site(request)
            mail_subject = 'Activate your account.'
            message = render_to_string('acc_active_email.html', {
                'user': user,
                'domain': current_site.domain,
                'uid': urlsafe_base64_encode(force_bytes(user.pk)),
                'token': default_token_generator.make_token(user),
            })
            to_email = form.cleaned_data.get('email')
            email = EmailMessage(
                mail_subject, message, to=[to_email]
            )
            email.send()
            return HttpResponse('Please confirm your email address to complete the registration')
    else:
        form = SignUpForm()
    return render(request, 'signup.html', {'form': form})


def activate(request, uidb64, token):
    try:
        uid = urlsafe_base64_decode(uidb64).decode()
        user = UserModel._default_manager.get(pk=uid)
    except(TypeError, ValueError, OverflowError, User.DoesNotExist):
        user = None
    if user is not None and default_token_generator.check_token(user, token):
        user.is_active = True
        user.save()
        return HttpResponse('Thank you for your email confirmation. Now you can login your account.')
    else:
        return HttpResponse('Activation link is invalid!')


class BlogListView(ListView):
    model = Post
    template_name = 'home.html'

    context_object_name = 'posts'
    paginate_by = 2
    queryset = Post.objects.all()

class BlogDetailView(DetailView):
    model = Post
    template_name = 'post_detail.html'

class BlogCreateView(CreateView):
    model = Post
    template_name = 'post_new.html'
    fields = ['title', 'author', 'body', 'header_image']

class BlogCommentView(CreateView):
    model = Comment
    form_class = CommentForm
    template_name = 'post_comment.html'
    def form_valid(self, form):
        form.instance.post_id = self.kwargs['pk']
        return super().form_valid(form)

    success_url = reverse_lazy('home')
    #fields = '__all__'

class BlogUpdateView(UpdateView):
    model = Post
    template_name = 'post_edit.html'
    fields = ['title', 'body', 'header_image']

class BlogDeleteView(DeleteView):
    model = Post
    template_name = 'post_delete.html'
    success_url = reverse_lazy('home')

@property
def image_url(self):
    if self.image:
        return getattr(self.photo, 'url', None)
    return None

帐户/视图.py

from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
from django.urls import reverse_lazy
from django.views import generic


class SignUpView(generic.CreateView):
    form_class = UserCreationForm
    success_url = reverse_lazy('login')
    template_name = 'signup.html'

myblog/url.py

from django.urls import path
from accounts import views

from .views import (
    BlogListView,
    BlogDetailView,
    BlogCreateView,
    BlogUpdateView,
    BlogDeleteView,
    BlogCommentView,

)

urlpatterns = [
    path('post/new/', BlogCreateView.as_view(), name='post_new'),
    path('post/<int:pk>/', BlogDetailView.as_view(), name='post_detail'),
    path('post/<int:pk>/edit/', BlogUpdateView.as_view(), name='post_edit'),
    path('post/<int:pk>/delete/', BlogDeleteView.as_view(), name='post_delete'),
    path('post/<int:pk>/comment/', BlogCommentView.as_view(), name='post_comment'),
    path('', BlogListView.as_view(), name='home'),

    path('post/<int:pk>/signup/', views.signup, name="signup"),
    path('activate/<uidb64>/<token>/', views.activate, name='activate'),

]

blog/url.py

from django.contrib import admin
from django.urls import path, include

from django.conf import settings
from django.conf.urls.static import static

urlpatterns = [
    path('admin/', admin.site.urls),
    path('accounts/', include('django.contrib.auth.urls')),
    path('accounts/', include('accounts.urls')),
    path('', include('myblog.urls')),


]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

forms.py

from django import forms
from .models import Post, Comment
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User


class CommentForm(forms.ModelForm):
    class Meta:
        model = Comment
        fields = ('name', 'body')

        widgets = {
            'name': forms.TextInput(attrs={'class': 'form-control'}),
            'body': forms.Textarea(attrs={'class': 'form-control'}),
        }


class SignUpForm(UserCreationForm):
    class Meta:
        model = User
        fields = ('email', 'first_name', 'last_name', 'username')

因为我是django的新手,所以我可能在错误的地方插入了一些代码

我希望问题尽可能清楚,以解决问题,但我不知道怎么做,因为我不理解代码中的所有内容,所以我请您写下任何建议,如果您需要扔其他东西,请告诉我,我会扔了它

附言。 用户注册=my博客

帐户=我的我的博客

myaccounts/views.py-它是一个单独的文件夹,包含迁移和文件

我不知道,也许指南中的views.py代码不需要插入到myblog/views.py,而是插入到accounts.py,因为“注册”和“活动”在myblog/url.py中突出显示,并且出现一条消息,提示您需要在accounts/view.py中创建这些功能,一般来说,我很困惑,这可能是一个没用的问题,如果一切都太困难,请指示我另一个方向,我如何尝试通过邮件注册,mb的视频教程或其他指南,非常感谢


Tags: pathdjangonamefrompyimportformemail
2条回答

尝试将以下代码添加到myblog/url.py文件中

from .views import signup

accounts.views中的SignUpView在基于类的视图中不是基于函数的视图中,因此应该以不同的方式提及它

path('post/<int:pk>/signup/', views.SignUpView.as_view(), name="signup")

相关问题 更多 >