Какие-либо представления на основе классов или пакет для Auth со связанной моделью? - PullRequest
0 голосов
/ 26 марта 2019

В настоящее время у меня есть два стиля шаблонов: Пользователь + Клиент и Пользователь + Компания.И я хочу создать представление для создания учетной записи User + из любого из этих двух связанных шаблонов.

В настоящее время я достиг этого, но есть проблема: код кажется очень раздутым, и я такжене знаю, есть ли CBV для редактирования модели со связанными моделями, тогда это приведет к тому, что другие виды также будут раздутыми.

Есть ли способ улучшить это?

models.py: https://pastebin.com/9Fp0F6CG

my views.py:

from django.shortcuts import render, redirect
from django.contrib.auth import login, authenticate
from django.views import generic
from .forms import UserForm, ClientForm, CompanyForm

class ClientFormView(generic.View):

    def get(self, request, *args, **kwargs):
        template_name = "users/registration/form_client.html"
        context = {"form_user": UserForm, "form_client": ClientForm}
        return render(request, template_name, context)

    def post(self, request, *args, **kwargs):
        template_name = "users/registration/form_client.html"
        context = {"form_user": UserForm, "form_client": ClientForm}

        form_user = UserForm(request.POST)
        form_client = ClientForm(request.POST)

        if form_user.is_valid() and form_client.is_valid():
            # get data for auth and login
            email = form_user.cleaned_data["email"]
            password_raw = form_user.cleaned_data["password1"]

            # add user_type = client
            instance_user = form_user.save(commit=False)
            instance_user.user_type = "cl"
            instance_user.save()

            instance_client = form_client.save(commit=False)

            user = authenticate(email=email, password=password_raw)
            if user is not None:
                # add the user in related user field
                instance_client.user = user
                instance_client.save()
                login(request, user)
                return redirect("main:home")

        return render(request, template_name, context)


class CompanyFormView(generic.View):
    def get(self, request, *args, **kwargs):
        template_name = "users/registration/form_company.html"
        context = {"form_user": UserForm, "form_company": CompanyForm}
        return render(request, template_name, context)

    def post(self, request, *args, **kwargs):
        template_name = "users/registration/form_company.html"
        context = {"form_user": UserForm, "form_company": CompanyForm}

        form_user = UserForm(request.POST)
        form_company = CompanyForm(request.POST)

        if form_user.is_valid() and form_company.is_valid():
            # get data for auth and login
            email = form_user.cleaned_data["email"]
            password_raw = form_user.cleaned_data["password1"]

            # add user_type = client
            instance_user = form_user.save(commit=False)
            instance_user.user_type = "comp"
            instance_user.save()

            instance_company = form_company.save(commit=False)

            user = authenticate(email=email, password=password_raw)
            if user is not None:
                # add the user in related user field
                instance_company.user = user
                instance_company.save()
                login(request, user)
                return redirect("main:home")

        return render(request, template_name, context)

1 Ответ

0 голосов
/ 26 марта 2019

Я только сделал некоторые улучшения в отношении представлений, я не смотрел на модели.

  • Сначала вы должны перейти с общего generic.View на generic.CreateView, поскольку высоздание вещей.
  • При выводе из generic.CreateView вы можете исключить template_name и context из функций и вместо этого поместить их в класс, поскольку они остаются одинаковыми для обоих GET и POST операции.
  • Тогда вам не нужно использовать функции render, вы можете просто вызвать super, который должен обрабатывать рендер для вас.
  • И, наконец, вы можете создать миксин, который обрабатывает логику при создании пользователя, так как он в основном такой же.Возможно, вам придется настроить его, я не смог проверить его полностью.
    from extra_views import CreateWithInlinesView, InlineFormSet
    
    class ClientCompanyMixin(object):
    
        def create_user(self, form_user, form_second, type):
            # get data for auth and login
            email = form_user.cleaned_data["email"]
            password_raw = form_user.cleaned_data["password1"]
    
            # add user_type = client/company
            instance_user = form_user.save(commit=False)
            instance_user.user_type = type
            instance_user.save()
    
            instance = form_second.save(commit=False)
    
            user = authenticate(email=email, password=password_raw)
    
            return instance, user
    
    class UserInline(InlineFormSet):
        model = User
    
    class ClientFormView(CreateWithInlinesView, ClientCompanyMixin):
        template_name = "users/registration/form_client.html"
        model = Client
        inlines = [UserInline]
    
        def get_context_data(self, **kwargs):
            context = super(ClientFormView, self).get_context_data(**kwargs)
            context["form_user"] = UserForm
            context["form_client"] = ClientForm
            return context
    
        def post(self, request, *args, **kwargs):
    
            form_user = UserForm(request.POST)
            form_client = ClientForm(request.POST)
    
            if form_user.is_valid() and form_client.is_valid():
    
                instance_client, user = self.create_user(form_user, form_client, "cl")
    
                if user is not None:
                    # add the user in related user field
                    instance_client.user = user
                    instance_client.save()
                    login(request, user)
                    return redirect("main:home")
    
            return super(ClientFormView, self).post(request, *args, **kwargs)
    
    class CompanyFormView(CreateWithInlinesView, ClientCompanyMixin):
        template_name = "users/registration/form_company.html"
        model = Company
        inlines = [UserInline]
    
        def get_context_data(self, **kwargs):
            context = super(CompanyFormView, self).get_context_data(**kwargs)
            context["form_user"] = UserForm
            context["form_company"] = CompanyForm
            return context
    
        def post(self, request, *args, **kwargs):
            form_user = UserForm(request.POST)
            form_company = CompanyForm(request.POST)
    
            if form_user.is_valid() and form_company.is_valid():
    
                instance_company, user = self.create_user(form_user, form_company, "comp")
    
                if user is not None:
                    # add the user in related user field
                    instance_company.user = user
                    instance_company.save()
                    login(request, user)
                    return redirect("main:home")
    
            return super(CompanyFormView, self).post(request, *args, **kwargs)
    
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...