Home > Mobile >  request.user in createdview
request.user in createdview

Time:01-16

How implement that the user in the Model Entities add automatically the user that is authenticated in django?

now, returning the following error:

error

I have tried differents methods that i have founding in the internet but not function. all cases return error in the momento to record a row.

only, i need that, in the moment that create a row, the user field was the user that is authenticated.

My Model:

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']

My CreateView:

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

My Form:

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

CodePudding user response:

SOLVED.

Adding, in the view, the line :

form.instance.user = self.request.user

full Createview would be :

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

CodePudding user response:

If you want to save additional data into form you can commit=False for this...

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)
  • Related