Wednesday, April 29, 2020

Re: How to use ModelChoiceField? I whould like to filter the output from a field form.

hend hend спасибо большое!
Работает!
Но!
Теперь у меня не получается управлять внешним видом полей

Я хочу переопределить класс в форме, но "user" из представления попадает в этот __init__  тоже

     def __init__(self, *args, **kwargs):
         super().__init__(*args, **kwargs)
         #количество строк в поле комментариев
         self.fields['comment'].widget = Textarea(attrs={'rows': 3})
         for field in self.fields:
             self.fields[field].widget.attrs['class'] = 'form-control'


среда, 29 апреля 2020 г., 13:54:23 UTC+2 пользователь hend hend написал:


вторник, 28 апреля 2020 г., 19:56:37 UTC+3 пользователь Sergei Sokov написал:
forms.py
class OrderForm(forms.ModelForm):
   
class Meta:
        model
= Order
    name_job
= forms.ModelMultipleChoiceField(queryset=None)
   
def __init__(self, *args, **kwargs):
       
super().__init__(*args, **kwargs)
        qs
= TypJob.objects.filter(author__id=request.user.id)

views.py
class OrderNewBigPrintView(LoginRequiredMixin, CustomSuccessMessageMixin, CreateView):
    model
= Order
    template_name
= 'new_order_bp.html'
    form_class
= OrderForm
    success_url
= reverse_lazy('orders')
    success_msg
= 'Ok'
 

models.py
class TypJob(models.Model):
 author
= models.ForeignKey(User, on_delete = models.CASCADE, verbose_name='author', null=True)
 name_job
= models.CharField('name job', max_length=200)


class Order(models.Model):
 author
= models.ForeignKey(User, on_delete = models.CASCADE, verbose_name='author', blank=True, null=True)
 number_order
= models.CharField('number of order', max_length=100)
 date_create
= models.DateTimeField(auto_now=True)
 name
= models.ForeignKey(Customer, on_delete = models.CASCADE, verbose_name='customer', null=True)
 name_order
= models.CharField('name of order', max_length=200)

# Так должно работать вроде.. 
# view
 class OrderNewBigPrintView(LoginRequiredMixin, CustomSuccessMessageMixin, CreateView):
    model = Order
    template_name 
= 'new_order_bp.html'
    form_class 
= OrderForm
    success_url 
= reverse_lazy('orders')
    success_msg 
= 'Ok'

    # this method will pass 'user' as param in kwargs to form __init__()
    def get_form_kwargs(self):
        kwargs = super(OrderNewBigPrintView, self).get_form_kwargs()
        kwargs['user'] =  self.request.user
        return kwargs

# form
class OrderForm(forms.ModelForm):
    
class Meta:
        model 
= Order
    name_job 
= forms.ModelMultipleChoiceField(queryset=None)

    
def __init__(self, *args, **kwargs):
        # get 'user' param from kwargs
        self.user = kwargs.pop('user', None)
        
super().__init__(*args, **kwargs)
        # set 'name_job' queryset
        self.fields['name_job'].queryset = TypJob.objects.filter(author__id=self.user.id)

--
You received this message because you are subscribed to the Google Groups "Django users" group.
To unsubscribe from this group and stop receiving emails from it, send an email to django-users+unsubscribe@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/79c1b55d-caaa-4a43-8ce7-f4b60eeaa3f6%40googlegroups.com.

No comments:

Post a Comment