如何从Django CreateView检索表单数据?

时间:2020-03-26 18:08:38

标签: python django django-forms django-views

我有一个Django博客,用户可以在其中创建每个帖子(活动,不活动)的状态。我使用的是Django基于类的通用视图,并且仅在状态设置为“活动”时才将用户重定向到其创建的帖子,否则应将其重定向到首页。如何从表单中检索此提交的信息以创建if语句?例如:if status ==“ a” ...

views.py

from .models import Listing
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.messages.views import SuccessMessageMixin
from django.views.generic import CreateView

class PostCreateView(LoginRequiredMixin, SuccessMessageMixin, CreateView):
    model = Post
    fields = ['title', 'status', 'content']
    template_name = 'blog/post-form.html'
    success_message = 'Your post has been created.'

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super().form_valid(form)

1 个答案:

答案 0 :(得分:0)

我认为“ redirect ”对方法(form_valid)无效,因此,您一定要放置def post之类的东西,并在request.data中获取值。我将尝试向您展示在生产中对我有用的代码。您让我知道这是否是正确的答案。

LoginFormView类(FormInvalidMessageMixin,LoginView):

template_name = "clientes/login.html

def post(self, request, *args, **kwargs):
    username = self.request.POST.get('username')
    password = self.request.POST.get('password')
    tipo_cuenta = self.request.POST.get('tipo-cuenta')
    tipo_cuenta = tipo_cuenta.strip()

    user = authenticate(username=username, password=password)

    if user:
        if has_group(user, 'admin'):
            messages.success(request, _('Not for admin'))
            return redirect('/login')

        cliente = Usuario.objects.filter(usuario=user).first()
        sucursal = Sucursal.objects.filter(usuario=user).first()
        empleado = Empleado.objects.filter(usuario=user).first()

        if tipo_cuenta == 'Punto afiliado':
            login(self.request, user)
            return redirect('/envios')