I have some models classes. And some classes have bounding fields with another class. Each class have the field - author. I whould like that for each user the form bounding field shows only those data which was created these authors.
For example:
class “TypeJob” has field “author”.
User Jhon created a TypJob - “Painting”.
User Alex created a TypJob - “Cleaning”.
Class “Order” has bounding field - “name_typ_job”
When Jhon whould like create an order, he opens the form and click “name type job” field, he sees both type job: painting and cleaning.
I whould like that he sees and could choose only “painting”. Because he is it author.
I wrote that
class OrderTestForm(forms.ModelForm): class Meta: model = Order name_job = forms.ModelChoiceField(queryset=None) qs = TypJob.objects.filter(author__id=user.id) def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['name_job'].queryset = qs
But I have
name ‘user’ is not defined
name ‘author__id’ is not defined
--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/178dcdb1-c119-46ef-83c3-95bda19118c8%40googlegroups.com.
class Meta: model = Order
fields = '__all__' name_job = forms.ModelMultipleChoiceField(queryset=None)
def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs)
qs = TypJob.objects.filter(author__id=request.user.id)
self.fields['name_job'].queryset = qs
'NoneType' object has no attribute '_prefetch_related_lookups'
the form doesn't know the request only the view does. how does
your view function look like?
--
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...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/12538865-4221-40e9-92bf-b8efc1ed7309%40googlegroups.com.
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)
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)
the form doesn't know the request only the view does. how does your view function look like?
On 4/28/20 5:57 PM, Sergei Sokov wrote:
я не совсем понял--
class Meta:model = Orderfields = '__all__'name_job = forms.ModelMultipleChoiceField(queryset=None)def __init__(self, *args, **kwargs):super().__init__(*args, **kwargs)qs = TypJob.objects.filter(author__id=request.user.id)self.fields['name_job'].queryset = qs
I have error'NoneType' object has no attribute '_prefetch_related_lookups'
вторник, 28 апреля 2020 г., 17:19:01 UTC+2 пользователь hend hend написал:user.id надо брать из request объекта в контроллере request.user.id. В том же контроллере метод get_initial() позволяет инициализировать поля формы(указанной в аттрибуте "form_class")контроллера.Например:
def get_initial(self):# поле category формы будет установлено в результат выборки по ключуself.initial["category"] = Category.objects.get(pk=self.c_id)return self.initial.copy() #
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...@googlegroups.com.
no idea how you do this with a CreateView but with a simple view function you have a request object:
https://docs.djangoproject.com/en/3.0/topics/http/views/#a-simple-view
this thread is about passing a variable into from the view function to a form:
Antje
To unsubscribe from this group and stop receiving emails from it, send an email to django-users...@googlegroups.com.
To view this discussion on the web visit https://groups.google.com/d/msgid/django-users/bbbdf319-812c-40e0-9ebf-235efed46a9d%40googlegroups.com.
class OrderNewBigPrintView(LoginRequiredMixin, CustomSuccessMessageMixin, CreateView):
model = Order
template_name = 'new_order_bp.html'
form_class = OrderForm
success_url = reverse_lazy('orders')
success_msg = 'Ok'
class OrderNewBigPrintView(LoginRequiredMixin, CustomSuccessMessageMixin, CreateView):
model = Order
template_name = 'new_order_bp.html'
form_class = OrderForm
success_url = reverse_lazy('orders')
success_msg = 'Заказ сохранён'
def get_initial(self):
self.initial['name_job'] = TypJob.objects.filter(author__id=self.request.user.id)
return self.initial.copy()
# view
'OrderForm' object has no attribute 'user'
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'
__init__() got an unexpected keyword argument 'user'
Я так понимаю потому что во views.py вот это
def get_form_kwargs(self):
kwargs = super(OrderNewBigPrintView, self).get_form_kwargs()
kwargs['user'] = self.request.user
return kwargs
class SkladCreateView(LoginRequiredMixin, CustomSuccessMessageMixin, CreateView): model = Sklad template_name = 'sklad.html' form_class = SkladForm success_url = reverse_lazy('sklad') success_msg = 'Материал сохранён' def get_context_data(self, **kwargs): kwargs['list_sklad'] = Sklad.objects.all().order_by('material') return super().get_context_data(**kwargs) # это функция для назначения автора def form_valid(self, form): self.object = form.save(commit=False) self.object.author = self.request.user self.object.save() return super().form_valid(form)