django 请求.用户在创建的视图中

qyyhg6bp  于 2023-01-18  发布在  Go
关注(0)|答案(2)|浏览(126)

如何实现模型实体中的用户自动添加在django中认证的用户?
现在,返回以下错误:
error
我试过不同的方法,我已经发现在互联网上,但没有功能。所有情况下返回错误的momento记录一行。
我只需要在创建行时,user字段是经过身份验证的用户。
我的模型:

class Entities(models.Model):
    #class Category(models.Model):   
    id = models.BigAutoField(primary_key=True)
    code = models.CharField(verbose_name='Código', max_length=10, blank=False, unique=True,
                                   help_text='Codigo de entidad.')
    name = models.CharField(max_length=150, verbose_name='Nombre', unique=True,
                                   help_text='Nombre de la entidad.')
    desc = models.CharField(max_length=500, null=True, blank=True, verbose_name='Descripción',
                                   help_text='Descripción de la entidad.')    
    name_report = models.CharField(verbose_name='Nombre Reporte', max_length=100, blank=False, unique=True,
                                   help_text='Rellenar para ACTIVAR el reporte')
    long_desc = models.CharField(verbose_name='Descripción Larga', max_length=800, blank=True,
                                   help_text='Descripción larga. Máximo 800 caracteres.')
    language = models.CharField(verbose_name='Idioma', max_length=2, choices=languages, default='ES',
                                   help_text='Idioma del reporte')
    user = models.ForeignKey(User, default=0, verbose_name='Usuario', on_delete=models.DO_NOTHING)
    date_created = models.DateTimeField(default=timezone.now, verbose_name='Creado',  blank=False, unique=False)
    date_updated = models.DateTimeField(default=timezone.now, verbose_name='Actualizado',  blank=False, unique=False)

    historical = HistoricalRecords()
    
    def __str__(self):
        return self.name

    def toJSON(self):
        item = model_to_dict(self)
        return item

    class Meta:
        verbose_name = 'Entidad'
        verbose_name_plural = 'Entidades'
        ordering = ['id']

我的创建视图:

class entitiesCreateView(LoginRequiredMixin, ValidatePermissionRequiredMixin, CreateView):
    model = Entities
    form_class = EntitiesForm
    template_name = 'Entities/create.html'
    success_url = reverse_lazy('erp:entities_list')
    permission_required = 'add_Entities'
    url_redirect = success_url

    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        data = {}
        try:
            action = request.POST['action']
            if action == 'add':
                form = self.get_form()
                data = form.save()
            else:
                data['error'] = 'No ha ingresado a ninguna opción'
        except Exception as e:
            data['error'] = str(e)
        return JsonResponse(data)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = 'Creación de una Entidad'
        context['entity'] = 'Entidades'
        context['list_url'] = self.success_url
        context['action'] = 'add'
        return context

我的表单:

class EntitiesForm(ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)
        # for form in self.visible_fields():
        #     form.field.widget.attrs['class'] = 'form-control'
        #     form.field.widget.attrs['autocomplete'] = 'off'
        self.fields['code'].widget.attrs['autofocus'] = True

    class Meta:
        model = Entities
        fields = '__all__'
        exclude = ['user','date_created','date_updated']
        widgets = {
            'name': forms.TextInput(
                attrs={
                    'placeholder': 'Ingrese un nombre',
                }
            ),
            'desc': forms.Textarea(
                attrs={
                    'placeholder': 'Ingrese un nombre',
                    'rows': 3,
                    'cols': 3
                }
            ),
        }

    def save(self, commit=True):
        data = {}
        form = super()
        try:
            if form.is_valid():
                **self.instante.user = self.request.user**
                form.save()
            else:
                data['error'] = form.errors
        except Exception as e:
            data['error'] = str(e)
        return data
bksxznpy

bksxznpy1#

解决了。
在视图中添加行:
表单示例用户=自身请求用户
完整的创建视图为:

class entitiesCreateView(LoginRequiredMixin, ValidatePermissionRequiredMixin, CreateView):
    model = Entities
    form_class = EntitiesForm
    template_name = 'Entities/create.html'
    success_url = reverse_lazy('erp:entities_list')
    permission_required = 'add_Entities'
    url_redirect = success_url

    def dispatch(self, request, *args, **kwargs):
        return super().dispatch(request, *args, **kwargs)

    def post(self, request, *args, **kwargs):
        data = {}
        try:
            action = request.POST['action']
            if action == 'add':
                form = self.get_form()
                form.instance.user = self.request.user      <============================
                data = form.save()
            else:
                data['error'] = 'No ha ingresado a ninguna opción'
        except Exception as e:
            data['error'] = str(e)
        return JsonResponse(data)

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)
        context['title'] = 'Creación de una Entidad'
        context['entity'] = 'Entidades'
        context['list_url'] = self.success_url
        context['action'] = 'add'
        return context
lb3vh1jj

lb3vh1jj2#

如果您想将其他数据保存到表单中,您可以为此设置commit=False ...

def post(self, request, *args, **kwargs):
        data = {}
        try:
            action = request.POST['action']
            if action == 'add':
                form = self.get_form()
                form = form.save(commit=False)
                form.user = request.user
                data = form.save()
            else:
                data['error'] = 'No ha ingresado a ninguna opción'
        except Exception as e:
            data['error'] = str(e)
        return JsonResponse(data)

相关问题