将当前用户保存在基于Django类的视图中

时间:2015-11-22 19:42:08

标签: python django django-class-based-views

我是django的新手,我需要将当前用户保存在基于类的视图中。 这是我的代码: views.py

from django.core.paginator import EmptyPage
from django.core.paginator import PageNotAnInteger
from django.core.paginator import Paginator
from django.http import HttpResponseRedirect, HttpResponse
from django.shortcuts import render
from django.shortcuts import render_to_response
from django.views.generic import CreateView, FormView
from partes.forms import ParteForm, VehiculoFormSet, ViviendaFormSet
from partes.models import Parte, Vehiculo




class CrearParte(CreateView):
    template_name   = 'nuevo.html'
    model           = Parte
    form_class      = ParteForm
    success_url     = '/partes'

    def get_context_data(self, **kwargs):
        # Llama primero a la implementación para traer el contexto
        context = super(CrearParte, self).get_context_data(**kwargs)
        # Se agrega el usuario
        context['form.usuario'] = self.request.user
        return context

    def get(self, request, *args, **kwargs):
        self.object    = None
        form_class      = self.get_form_class()
        form            = self.get_form(form_class)
        vehiculos_form  = VehiculoFormSet()
        vivienda_form   = ViviendaFormSet()
        return self.render_to_response(
                                       self.get_context_data (form=form,
                                       vehiculos_form=vehiculos_form,
                                       vivienda_form=vivienda_form,))

    def post(self, request, *args, **kwargs):
        self.object = None
        form_class  = self.get_form_class()
        form        = self.get_form(form_class)

        form.instance.usuario = self.request.user
        vehiculos_form  = VehiculoFormSet(self.request.POST)
        vivienda_form   = ViviendaFormSet(self.request.POST)
        if (form.is_valid() ):
            return self.form_valid(form, vehiculos_form, vivienda_form)
        else:
            return self.form_invalid(form, vehiculos_form, vivienda_form)

    def form_valid(self, form, vehiculos_form, vivienda_form):
        self.object = form.save()
        vehiculos_form.instance = self.object
        vehiculos_form.save()
        vivienda_form.instance = self.object
        vivienda_form.save()
        return HttpResponseRedirect(self.get_success_url())

    def form_invalid(self, form, vehiculos_form, vivienda_form):
        return HttpResponse(form.errors)

forms.py

from django import forms
from django.forms.models import inlineformset_factory
from partes.models import Parte, Vehiculo, Vivienda


class ParteForm(forms.ModelForm):

    class Meta:
        model = Parte
        fields = '__all__'
        widgets = {
            'tlf': forms.TextInput(attrs={'placeholder': 'Teléfono Alertante'}),
            'fecha': forms.TextInput(attrs={'placeholder': 'Fecha y hora de llamada'}),

            'description': forms.Textarea(
                                          attrs={'placeholder': 'Enter description here'}),
        }

VehiculoFormSet = inlineformset_factory(Parte, Vehiculo, fields='__all__', extra=1, )
ViviendaFormSet = inlineformset_factory(Parte, Vivienda, fields=('dni',))

models.py

    from django.db import models
    from django.utils import timezone
    from django.contrib.auth.models import User
    from material.models import Material

class Parte(models.Model):
    usuario     = models.ForeignKey("auth.User")
    fecha_reg    = models.DateTimeField() #fecha de registro del parte
    tlf         = models.CharField(max_length=15,blank=True, null=True)
    alertante   = models.CharField(max_length=50,blank=True, null=True)
    dat_cent    = models.BooleanField('Datos introducidos manualmente')
    parte       = models.IntegerField(blank=True, null=True)
    descrip     = models.CharField('Descripcion Corta',max_length=200,blank=True, null=True) # Desripción corta de la intervención
    f_inicio    = models.DateTimeField('Fecha y hora de la llamada', default=timezone.now().strftime("%Y-%m-%d"),blank=True, null=True)
    f_fin       = models.DateTimeField(default=timezone.now().strftime("%Y-%m-%d") ,blank=True, null=True)
    h_llegada   = models.DateTimeField(default=timezone.now,blank=True, null=True)
    h_retirada  = models.DateTimeField(default=timezone.now,blank=True, null=True)
    concello    = models.CharField(max_length=100,blank=True, null=True)
    parroquia   = models.CharField(max_length=100,blank=True, null=True)
    direccion   = models.CharField(max_length=150,blank=True, null=True)
    id112       = models.CharField('ID intervencion CAE112', max_length=20,blank=True, null=True)
    coment      = models.TextField('Descripción de la intervención',blank=True, null=True)
    intervi     = models.ManyToManyField(User, related_name='interviniente')
    material    = models.ManyToManyField(Material)

    def creado(self):
        self.fecha_reg = timezone.now()
        self.save()

    def __str__(self):
        return self.parte



class Vehiculo(models.Model):
    n_parte     = models.ForeignKey(Parte,blank=True, null=True)
    matricula   = models.CharField(max_length=9,blank=True, null=True)
    marca       = models.CharField(max_length=100,blank=True, null=True)
    modelo      = models.CharField(max_length=100,blank=True, null=True)
    propieta    = models.CharField('Propietario',max_length=150,blank=True, null=True)
    tlf         = models.CharField('Teléfono',max_length=15,blank=True, null=True)
    dni         = models.CharField(max_length=10,blank=True, null=True)
    aseguradora = models.CharField(max_length=100,blank=True, null=True)
    n_poliza    = models.CharField(max_length=50,blank=True, null=True)
    vencimiento = models.DateField(blank=True, null=True)

    def __str__(self):
        return self.matricula


class Vivienda(models.Model):
    n_parte     = models.ForeignKey(Parte)
    tlf         = models.CharField(max_length=15)
    dni         = models.CharField(max_length=10)
    aseguradora = models.CharField(max_length=100)
    n_poliza    = models.CharField(max_length=50)
    vencimiento = models.DateField()

我可以在模板中使用{{request.user}}呈现身份验证用户,但我使用usuario字段获得form_invalid。有什么帮助吗?

1 个答案:

答案 0 :(得分:1)

这里你的usuario字段是必填字段;因此在表单中它会给出错误,因为你没有传递该字段的任何数据。您可以使用blank=True

将其改为这样;

usuario = models.ForeignKey("auth.User", blank=True)

您可以通过表单ParteForm;

维护它

将此fields = '__all__'更改为exclude = ['usuario']

修改

更改此行; self.object = form.save()

self.object = form.save(commit=False)
self.object.usuario = self.request.user
self.object.save()