ImportError: невозможно импортировать имя UserForm из apps.common.forms - PullRequest
1 голос
/ 05 мая 2020

Я использую код для проекта, и этот код работал раньше, и я не могу заставить его работать. Похоже, что в forms.py есть проблема, которая не может отрисовывать информацию. В остальном я не совсем уверен, почему я получаю эту ошибку. Я долгое время пытался работать над этим в тишине, и мне кажется, что пара глаз могла бы найти решение. Пожалуйста, помогите.

Отслеживание ошибок:

Watching for file changes with StatReloader
Performing system checks...

Exception in thread django-main-thread:
Traceback (most recent call last):
File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner
self.run()
File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run
self._target(*self._args, **self._kwargs)
File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\autoreload.py", line 53, in wrapper
fn(*args, **kwargs)
File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 117, in inner_run
self.check(display_num_errors=True)
File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 392, in check
all_issues = self._run_checks(
File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 382, in _run_checks
return checks.run_checks(**kwargs)
File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\registry.py", line 72, in run_checks
new_errors = check(app_configs=app_configs)
File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 13, in check_url_config
return check_resolver(resolver)
File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\checks\urls.py", line 23, in check_resolver
return check_method()
File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 407, in check
for pattern in self.url_patterns:
File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 588, in url_patterns
patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module)
File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\utils\functional.py", line 48, in __get__
res = instance.__dict__[self.name] = self.func(instance)
File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\urls\resolvers.py", line 581, in urlconf_module
return import_module(self.urlconf_name)
File "C:\Users\aviparna.biswas\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module
return _bootstrap._gcd_import(name[level:], package, level)
File "<frozen importlib._bootstrap>", line 1014, in _gcd_import
File "<frozen importlib._bootstrap>", line 991, in _find_and_load
File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked
File "<frozen importlib._bootstrap>", line 671, in _load_unlocked
File "<frozen importlib._bootstrap_external>", line 783, in exec_module
File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed
File "C:\Users\aviparna.biswas\PycharmProjects\NexCRM\nex_main\urls.py", line 19, in <module>
from apps.common.views import HomeView, SignUpView, DashboardView, ProfileUpdateView, ProfileView
File "C:\Users\aviparna.biswas\PycharmProjects\NexCRM\apps\common\views.py", line 7, in <module>
from .forms import SignUpForm, UserForm, ProfileForm
ImportError: cannot import name 'UserForm' from 'apps.common.forms' 

forms.py:

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm


from apps.userprofile.models import Profile

class SignUpForm(UserCreationForm):

  first_name = forms.CharField(max_length=30, required=False, help_text='Optional')
  last_name = forms.CharField(max_length=30, required=False, help_text='Optional')
  email = forms.EmailField(max_length=254, help_text='Enter a valid email address')

  class Meta:
      model = User
      fields = [
          'username',
          'first_name',
          'last_name',
          'email',
          'password1',
          'password2',
      ]

  class UserForm(forms.ModelForm):
      class Meta:
          model = User
          fields = [
              'username',
              'first_name',
              'last_name',
              'email',
          ]

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = [
            'bio',
            'phone_number',
            'birth_date',
            'profile_image'
        ]

views.py:

from django.shortcuts import render
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy

from django.views.generic import TemplateView, CreateView

from .forms import SignUpForm, UserForm, ProfileForm
from django.contrib.auth.models import User
from django.http import HttpResponseRedirect
from django.contrib import messages
from apps.userprofile.models import Profile

class HomeView(TemplateView):
  template_name = 'common/home.html'

class DashboardView(LoginRequiredMixin, TemplateView):
  template_name = 'common/dashboard.html'
  login_url = reverse_lazy('home')

  def get_context_data(self, **kwargs):
     # Call the base implementation first to get a context
      context = super().get_context_data(**kwargs)
     # Add in a QuerySet of all the books
      print(self.request.user.id)
      context['book_list'] = self.request.user
      return context

class SignUpView(CreateView):
  form_class =  SignUpForm
  success_url = reverse_lazy('home')
  template_name = 'common/register.html'

from django.http import HttpResponseRedirect
from django.contrib.auth.mixins import LoginRequiredMixin
from django.urls import reverse_lazy
from django.contrib import messages
from .forms import UserForm, ProfileForm
from django.contrib.auth.models import User
from apps.userprofile.models import Profile

class ProfileView(LoginRequiredMixin, TemplateView):
  template_name = 'common/profile.html'

class ProfileUpdateView(LoginRequiredMixin, TemplateView):
  user_form = UserForm
  profile_form = ProfileForm
  template_name = 'common/profile-update.html'

  def post(self, request):

      post_data = request.POST or None
      file_data = request.FILES or None

      user_form = UserForm(post_data, instance=request.user)
      profile_form = ProfileForm(post_data, file_data, instance=request.user.profile)

      if user_form.is_valid() and profile_form.is_valid():
          user_form.save()
          profile_form.save()
          messages.success(request, 'Your profile was successfully updated!')
          return HttpResponseRedirect(reverse_lazy('profile'))

      context = self.get_context_data(
                                    user_form=user_form,
                                    profile_form=profile_form
                                )

      return self.render_to_response(context)

def get(self, request, *args, **kwargs):
    return self.post(request, *args, **kwargs)

urls.py :

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

from apps.common.views import HomeView, SignUpView, DashboardView, ProfileUpdateView, ProfileView

from django.contrib.auth import views as auth_views

urlpatterns = [
path('admin/', admin.site.urls),

path('', HomeView.as_view(), name='home'),
path('register/', SignUpView.as_view(), name="register"),
path('dashboard/', DashboardView.as_view(), name='dashboard'),

path('login/', auth_views.LoginView.as_view(
    template_name='common/login.html'
    ),
    name='login'
),

path('logout/', auth_views.LogoutView.as_view(
    next_page='home'
),
     name='logout'
),

path(
    'change-password/',
    auth_views.PasswordChangeView.as_view(
        template_name='common/change-password.html',
        success_url='/'
    ),
    name='change-password'
),

# Forget Password
path(
    'password-reset/',
     auth_views.PasswordResetView.as_view(
         template_name='common/password-reset/password_reset.html',
         subject_template_name='common/password-reset/password_reset_subject.txt',
         email_template_name='common/password-reset/password_reset_email.html',
         success_url='/login/'
     ),
     name='password_reset'),
path('password-reset/done/',
     auth_views.PasswordResetDoneView.as_view(
         template_name='common/password-reset/password_reset_done.html'
     ),
     name='password_reset_done'),
path('password-reset-confirm/<uidb64>/<token>/',
     auth_views.PasswordResetConfirmView.as_view(
         template_name='common/password-reset/password_reset_confirm.html'
     ),
     name='password_reset_confirm'),
path('password-reset-complete/',
     auth_views.PasswordResetCompleteView.as_view(
         template_name='common/password-reset/password_reset_complete.html'
     ),
     name='password_reset_complete'),

#Profile Update
path('profile-update/', ProfileUpdateView.as_view(), name='profile-update'),
path('profile/', ProfileView.as_view(), name='profile'),
]


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

if settings.DEBUG:
    urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)

1 Ответ

0 голосов
/ 05 мая 2020

Потому что вы неправильно импортировали UserForm. Indentation для UserForm неверно, так как он находится внутри SignUpForm.

class SignUpForm(UserCreationForm):

  first_name = forms.CharField(max_length=30, required=False, help_text='Optional')
  last_name = forms.CharField(max_length=30, required=False, help_text='Optional')
  email = forms.EmailField(max_length=254, help_text='Enter a valid email address')

  class Meta:
      model = User
      fields = [
          'username',
          'first_name',
          'last_name',
          'email',
          'password1',
          'password2',
      ]

// Check indentation here
class UserForm(forms.ModelForm):
  class Meta:
      model = User
      fields = [
          'username',
          'first_name',
          'last_name',
          'email',
      ]

class ProfileForm(forms.ModelForm):
    class Meta:
        model = Profile
        fields = [
            'bio',
            'phone_number',
            'birth_date',
            'profile_image'
        ]

Или, если UserForm действительно находится внутри SignUpForm, вам следует импортировать UserForm, например:

from .forms import SignUpForm.UserForm as UserForm

Но , Думаю все дело в indentation проблеме !!!

...