NoReverseMatch at /update-orders/12 Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) tried: ['update\\-orders/(?P[0-9]+)$']

2020-04-23 Thread Sergei Sokov
Hello everybody

I have a problem:

NoReverseMatch at /update-orders/12

Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) 
tried: ['update\\-orders/(?P[0-9]+)$']

Request Method: GET
Request URL: http://192.168.0.249:8000/update-orders/12
Django Version: 3.0.5
Exception Type: NoReverseMatch
Exception Value: 

Reverse for 'update_order' with arguments '('',)' not found. 1 pattern(s) 
tried: ['update\\-orders/(?P[0-9]+)$']

Exception Location: 
/root/.local/share/virtualenvs/myp4-4l8n6HJk/lib/python3.7/site-packages/django/urls/resolvers.py
 
in _reverse_with_prefix, line 677
Python Executable: /root/.local/share/virtualenvs/myp4-4l8n6HJk/bin/python
Python Version: 3.7.3
Python Path: 

['/var/workspace/myp4/webprint',
 '/usr/lib/python37.zip',
 '/usr/lib/python3.7',
 '/usr/lib/python3.7/lib-dynload',
 '/root/.local/share/virtualenvs/myp4-4l8n6HJk/lib/python3.7/site-packages']


Why do I have this Error during template rendering?

detail_order.html
{% extends 'index.html' %}

{% block content %}
Back
Заказ {{get_order.number_order}}
Update

views.py
class UpdateOrderView(CustomSuccessMessageMixin, UpdateView):
model = Order
template_name = 'detail_order.html'
form_class = OrderForm
success_url = reverse_lazy('detail_order')
success_msg = 'Ok'
def get_context_data(self, **kwargs):
kwargs['update'] = True
return super().get_context_data(**kwargs)

urls.py
from django.contrib import admin
from django.urls import path, include
from .views import *
from print import views

urlpatterns = [
path('', views.home_page, name='index'),
path('orders', views.OrderCreateView.as_view(), name='orders'),
path('update-orders/', views.UpdateOrderView.as_view(), 
name='update_order'), # THIS PATH
path('delete-orders/', views.DeleteOrderView.as_view(), 
name='delete_order'),
path('detail-order/', views.DetailOrderView.as_view(), 
name='detail_order'),
path('login', views.MyprojectLoginView.as_view(), name='login_page'),
path('register', views.RegisterUserView.as_view(), 
name='register_page'),
path('logout', views.MyprojectLogout.as_view(), name='logout_page'),
]



-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/ed4df72d-838e-4e53-b79e-78eda6902195%40googlegroups.com.


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

2020-04-28 Thread Sergei Sokov


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+unsubscr...@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.


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

2020-04-28 Thread Sergei Sokov
я не совсем понял

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

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-users+unsubscr...@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.


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

2020-04-28 Thread 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)


вторник, 28 апреля 2020 г., 18:41:25 UTC+2 пользователь Antje Kazimiers 
написал:
>
> 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 = 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
>
> 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 .
> To view this discussion on the web visit 
> https://groups.google.com/d/msgid/django-users/12538865-4221-40e9-92bf-b8efc1ed7309%40googlegroups.com
>  
> <https://groups.google.com/d/msgid/django-users/12538865-4221-40e9-92bf-b8efc1ed7309%40googlegroups.com?utm_medium=email&utm_source=footer>
> .
>
>

-- 
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+unsubscr...@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.


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

2020-04-29 Thread Sergei Sokov
hend hend  Не работает, но и ошибку не выдает. Что-то нужно передать в 
класс формы?
It doesn't work. And it doesn't show an error (

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()


среда, 29 апреля 2020 г., 9:07:41 UTC+2 пользователь hend hend написал:
>
>
>
>
>>> class OrderNewBigPrintView(LoginRequiredMixin, CustomSuccessMessageMixin
>>> , CreateView):
>>> model = Order
>>> template_name = 'new_order_bp.html'
>>> form_class = OrderForm
>>> success_url = reverse_lazy('orders')
>>> success_msg = 'Ok'
>>>
>>
>   # get_initial позволяет установить значения полей связанной 
> формы
>   def get_initial(self):
>   self.initial["name_job"] = TypJob.objects.filter(
> author__id=self.request.user.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-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/41269b59-ac29-4f84-8f5f-80525ff98991%40googlegroups.com.


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

2020-04-29 Thread Sergei Sokov
please could you see this 

https://ru.stackoverflow.com/questions/594743/forms-modelchoicefield-%d0%9a%d0%b0%d0%ba-%d0%bf%d0%be%d0%bb%d1%83%d1%87%d0%b8%d1%82%d1%8c-%d1%81-%d0%bf%d0%be%d0%bc%d0%be%d1%89%d1%8c%d1%8e-queryset-name-model-objects-filt

how to write this "form = KommpredForm(request.POST, user=user)"  in 
views.py?
If I have Class and form_class

среда, 29 апреля 2020 г., 9:07:41 UTC+2 пользователь hend hend написал:
>
>
>
>
>>> class OrderNewBigPrintView(LoginRequiredMixin, CustomSuccessMessageMixin
>>> , CreateView):
>>> model = Order
>>> template_name = 'new_order_bp.html'
>>> form_class = OrderForm
>>> success_url = reverse_lazy('orders')
>>> success_msg = 'Ok'
>>>
>>
>   # get_initial позволяет установить значения полей связанной 
> формы
>   def get_initial(self):
>   self.initial["name_job"] = TypJob.objects.filter(
> author__id=self.request.user.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-users+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/ead817cb-ab77-4c1c-803a-8aa4c3c7b02a%40googlegroups.com.


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

2020-04-29 Thread Sergei Sokov
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+unsubscr...@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.


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

2020-04-29 Thread Sergei Sokov
без self такая ошибка

'OrderForm' object has no attribute 'user'


среда, 29 апреля 2020 г., 17:56:10 UTC+2 пользователь hend hend написал:
>
> Если 'user'  в классе не нужен, можно не вешать его на self. просто вместо 
> 'self.user' используем 'user': в этом случае 'user' просто локальная 
> переменная метода init.
> def __init__(self, *args, **kwargs):
> # get 'user' param from kwargs
> user = kwargs.pop('user', None)
> super().__init__(*args, **kwargs)
> # set 'name_job' queryset
> self.fields['name_job'].queryset = TypJob.objects.filter(
> author__id=user.id)
>
> среда, 29 апреля 2020 г., 17:19:41 UTC+3 пользователь Sergei Sokov написал:
>>
>> 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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/42c3b7dc-cbb9-4643-b57d-78299ec1b1a7%40googlegroups.com.


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

2020-04-30 Thread Sergei Sokov
А как тогда?
self.fields['name_job'].queryset = 
TypJob.objects.filter(author__id=self.user.id)
как тогда фильтр будет работать?

среда, 29 апреля 2020 г., 20:36:00 UTC+2 пользователь hend hend написал:
>
> *Не нужно нигде  в классе формы обращаться к  'self.user'.  *
>
> среда, 29 апреля 2020 г., 19:49:45 UTC+3 пользователь Sergei Sokov написал:
>>
>> без self такая ошибка
>>
>> 'OrderForm' object has no attribute 'user'
>>
>>
>> среда, 29 апреля 2020 г., 17:56:10 UTC+2 пользователь hend hend написал:
>>>
>>> Если 'user'  в классе не нужен, можно не вешать его на self. просто 
>>> вместо 'self.user' используем 'user': в этом случае 'user' просто локальная 
>>> переменная метода init.
>>> def __init__(self, *args, **kwargs):
>>> # get 'user' param from kwargs
>>> user = kwargs.pop('user', None)
>>> super().__init__(*args, **kwargs)
>>> # set 'name_job' queryset
>>> self.fields['name_job'].queryset = TypJob.objects.filter(
>>> author__id=user.id)
>>>
>>> среда, 29 апреля 2020 г., 17:19:41 UTC+3 пользователь Sergei Sokov 
>>> написал:
>>>>
>>>> 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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/9f4edaa1-e8ba-43ee-b180-bd4b192cfe4c%40googlegroups.com.


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

2020-04-30 Thread Sergei Sokov
так работает, но если я добавляю вот это для редактирования отображения 
полей в форме
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'
тогда у меня вот такая ошибка
TypeError at /new-big-print-order

__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



четверг, 30 апреля 2020 г., 12:19:35 UTC+2 пользователь hend hend написал:
>
> Уже приводил вариант без self, хотя и с self должно бы работать нормально, 
> но раз ругается попробуйте без self.
> def __init__(self, *args, **kwargs):
> # get 'user' param from kwargs
> # user without self
> user = kwargs.pop('user', None)
> super().__init__(*args, **kwargs)
> # set 'name_job' queryset
> # user.id without self
> self.fields['name_job'].queryset = TypJob.objects.filter(
> author__id=user.id)
>
>
> четверг, 30 апреля 2020 г., 11:34:28 UTC+3 пользователь Sergei Sokov 
> написал:
>>
>> А как тогда?
>> self.fields['name_job'].queryset = TypJob.objects.filter(author__id=
>> self.user.id)
>> как тогда фильтр будет работать?
>>
>> среда, 29 апреля 2020 г., 20:36:00 UTC+2 пользователь hend hend написал:
>>>
>>> *Не нужно нигде  в классе формы обращаться к  'self.user'.  *
>>>
>>> среда, 29 апреля 2020 г., 19:49:45 UTC+3 пользователь Sergei Sokov 
>>> написал:
>>>>
>>>> без self такая ошибка
>>>>
>>>> 'OrderForm' object has no attribute 'user'
>>>>
>>>>
>>>> среда, 29 апреля 2020 г., 17:56:10 UTC+2 пользователь hend hend написал:
>>>>>
>>>>> Если 'user'  в классе не нужен, можно не вешать его на self. просто 
>>>>> вместо 'self.user' используем 'user': в этом случае 'user' просто 
>>>>> локальная 
>>>>> переменная метода init.
>>>>> def __init__(self, *args, **kwargs):
>>>>> # get 'user' param from kwargs
>>>>> user = kwargs.pop('user', None)
>>>>> super().__init__(*args, **kwargs)
>>>>> # set 'name_job' queryset
>>>>> self.fields['name_job'].queryset = TypJob.objects.filter(
>>>>> author__id=user.id)
>>>>>
>>>>> среда, 29 апреля 2020 г., 17:19:41 UTC+3 пользователь Sergei Sokov 
>>>>> написал:
>>>>>>
>>>>>> 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):
>>>>>>>>

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

2020-04-30 Thread Sergei Sokov
Так перестает работать первоначальная задача

четверг, 30 апреля 2020 г., 18:14:38 UTC+2 пользователь hend hend написал:
>
> Не совсем понимаю, это init какого класса...Но можно попробовать так:
> def __init__(self, *args, **kwargs):
> # delete 'user' from kwargs before calling perent init
> user = kwargs.pop('user', None)
> 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'
>
>
> четверг, 30 апреля 2020 г., 15:46:43 UTC+3 пользователь Sergei Sokov 
> написал:
>>
>> так работает, но если я добавляю вот это для редактирования отображения 
>> полей в форме
>> 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'
>> тогда у меня вот такая ошибка
>> TypeError at /new-big-print-order
>>
>> __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
>>
>>
>>
>> четверг, 30 апреля 2020 г., 12:19:35 UTC+2 пользователь hend hend написал:
>>>
>>> Уже приводил вариант без self, хотя и с self должно бы работать 
>>> нормально, но раз ругается попробуйте без self.
>>> def __init__(self, *args, **kwargs):
>>> # get 'user' param from kwargs
>>> # user without self
>>> user = kwargs.pop('user', None)
>>> super().__init__(*args, **kwargs)
>>> # set 'name_job' queryset
>>> # user.id without self
>>> self.fields['name_job'].queryset = TypJob.objects.filter(
>>> author__id=user.id)
>>>
>>>
>>> четверг, 30 апреля 2020 г., 11:34:28 UTC+3 пользователь Sergei Sokov 
>>> написал:
>>>>
>>>> А как тогда?
>>>> self.fields['name_job'].queryset = TypJob.objects.filter(author__id=
>>>> self.user.id)
>>>> как тогда фильтр будет работать?
>>>>
>>>> среда, 29 апреля 2020 г., 20:36:00 UTC+2 пользователь hend hend написал:
>>>>>
>>>>> *Не нужно нигде  в классе формы обращаться к  'self.user'.  *
>>>>>
>>>>> среда, 29 апреля 2020 г., 19:49:45 UTC+3 пользователь Sergei Sokov 
>>>>> написал:
>>>>>>
>>>>>> без self такая ошибка
>>>>>>
>>>>>> 'OrderForm' object has no attribute 'user'
>>>>>>
>>>>>>
>>>>>> среда, 29 апреля 2020 г., 17:56:10 UTC+2 пользователь hend hend 
>>>>>> написал:
>>>>>>>
>>>>>>> Если 'user'  в классе не нужен, можно не вешать его на self. просто 
>>>>>>> вместо 'self.user' используем 'user': в этом случае 'user' просто 
>>>>>>> локальная 
>>>>>>> переменная метода init.
>>>>>>> def __init__(self, *args, **kwargs):
>>>>>>> # get 'user' param from kwargs
>>>>>>> user = kwargs.pop('user', None)
>>>>>>> super().__init__(*args, **kwargs)
>>>>>>>     # set 'name_job' queryset
>>>>>>> self.fields['name_job'].queryset = TypJob.objects.filter(
>>>>>>> author__id=user.id)
>>>>>>>
>>>>>>> среда, 29 апреля 2020 г., 17:19:41 UTC+3 пользователь Sergei Sokov 
>>>>>>> написал:
>>>>>>>>
>>>>>>>> hend hend спасибо большое!
>>>>>>>> Работает!
>>>>>>>> Но!
>>>>>>>> *Теперь у меня не получается управлять внешним видом полей*
>>>>>>>>
>>>>>>>> Я хочу переопреде

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

2020-04-30 Thread Sergei Sokov
Действительно!!
А я и не заметил.
Благодарю от всего сердца!!!
Это будет слишком нагло с моей стороны, но
можно ли ваш контакт, чтобы вас (или тебя) на прямую спрашивать разные 
вопросы касаемо джанго, я совсем новичок в этом деле и, например, этот 
вопрос задавал на разных форумах, но никто мне не смог помочь.
Если нет так нет, я кроме hend hend ничего не знаю из контактов.
Моя почта sokov точка tlt собака гмэйл точка ком

четверг, 30 апреля 2020 г., 19:51:54 UTC+2 пользователь hend hend написал:
>
> Кажется я понял, вы влепили два init в класс? А зачем...
> def __init__(self, *args, **kwargs):
> # get 'user' param from kwargs
> user = kwargs.pop('user', None)
> super().__init__(*args, **kwargs)
> # set class attrs  
> for field in self.fields.values():
>  field.widget.attrs['class'] = 'form-control'
> # set 'name_job' queryset
> self.fields['name_job'].queryset = TypJob.objects.filter(
> author__id=user.id)
>
> четверг, 30 апреля 2020 г., 20:00:57 UTC+3 пользователь Sergei Sokov 
> написал:
>>
>> Так перестает работать первоначальная задача
>>
>> четверг, 30 апреля 2020 г., 18:14:38 UTC+2 пользователь hend hend написал:
>>>
>>> Не совсем понимаю, это init какого класса...Но можно попробовать так:
>>> def __init__(self, *args, **kwargs):
>>> # delete 'user' from kwargs before calling perent init
>>> user = kwargs.pop('user', None)
>>> 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'
>>>
>>>
>>> четверг, 30 апреля 2020 г., 15:46:43 UTC+3 пользователь Sergei Sokov 
>>> написал:
>>>>
>>>> так работает, но если я добавляю вот это для редактирования отображения 
>>>> полей в форме
>>>> 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'
>>>> тогда у меня вот такая ошибка
>>>> TypeError at /new-big-print-order
>>>>
>>>> __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
>>>>
>>>>
>>>>
>>>> четверг, 30 апреля 2020 г., 12:19:35 UTC+2 пользователь hend hend 
>>>> написал:
>>>>>
>>>>> Уже приводил вариант без self, хотя и с self должно бы работать 
>>>>> нормально, но раз ругается попробуйте без self.
>>>>> def __init__(self, *args, **kwargs):
>>>>> # get 'user' param from kwargs
>>>>> # user without self
>>>>> user = kwargs.pop('user', None)
>>>>> super().__init__(*args, **kwargs)
>>>>> # set 'name_job' queryset
>>>>> # user.id without self
>>>>> self.fields['name_job'].queryset = TypJob.objects.filter(
>>>>> author__id=user.id)
>>>>>
>>>>>
>>>>> четверг, 30 апреля 2020 г., 11:34:28 UTC+3 пользователь Sergei Sokov 
>>>>> написал:
>>>>>>
>>>>>> А как тогда?
>>>>>> self.fields['name_job'].queryset = TypJob.objects.filter(author__id=
>>>>>> self.user.id)
>>>>>> как тогда фильтр будет работать?
>>>>>>
>>>>>> среда, 29 апреля 2020 г., 20:36:00 UTC+2 пользователь hend hend 
>>>>>> написал:
>>>>>>>
>>>>>>> *Не нужно нигде  в классе формы обращаться к  'self.user'.  *
>>>>>>>
>>>>>>> среда, 29 апреля 2020 г., 19:49:45 UTC+3 поль

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

2020-05-01 Thread Sergei Sokov
А не могли бы вы подсказать как вызвать две разные формы, от двух разных 
классов в models.py, на одной странице?
Нужно передать в контекст views.py две формы, и эти две формы по разному 
назвать.

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)




четверг, 30 апреля 2020 г., 19:51:54 UTC+2 пользователь hend hend написал:
>
> Кажется я понял, вы влепили два init в класс? А зачем...
> def __init__(self, *args, **kwargs):
> # get 'user' param from kwargs
> user = kwargs.pop('user', None)
> super().__init__(*args, **kwargs)
> # set class attrs  
> for field in self.fields.values():
>  field.widget.attrs['class'] = 'form-control'
> # set 'name_job' queryset
> self.fields['name_job'].queryset = TypJob.objects.filter(
> author__id=user.id)
>
> четверг, 30 апреля 2020 г., 20:00:57 UTC+3 пользователь Sergei Sokov 
> написал:
>>
>> Так перестает работать первоначальная задача
>>
>> четверг, 30 апреля 2020 г., 18:14:38 UTC+2 пользователь hend hend написал:
>>>
>>> Не совсем понимаю, это init какого класса...Но можно попробовать так:
>>> def __init__(self, *args, **kwargs):
>>> # delete 'user' from kwargs before calling perent init
>>> user = kwargs.pop('user', None)
>>> 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'
>>>
>>>
>>> четверг, 30 апреля 2020 г., 15:46:43 UTC+3 пользователь Sergei Sokov 
>>> написал:
>>>>
>>>> так работает, но если я добавляю вот это для редактирования отображения 
>>>> полей в форме
>>>> 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'
>>>> тогда у меня вот такая ошибка
>>>> TypeError at /new-big-print-order
>>>>
>>>> __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
>>>>
>>>>
>>>>
>>>> четверг, 30 апреля 2020 г., 12:19:35 UTC+2 пользователь hend hend 
>>>> написал:
>>>>>
>>>>> Уже приводил вариант без self, хотя и с self должно бы работать 
>>>>> нормально, но раз ругается попробуйте без self.
>>>>> def __init__(self, *args, **kwargs):
>>>>> # get 'user' param from kwargs
>>>>> # user without self
>>>>> user = kwargs.pop('user', None)
>>>>> super().__init__(*args, **kwargs)
>>>>> # set 'name_job' queryset
>>>>> # user.id without self
>>>>> self.fields['name_job'].queryset = TypJob.objects.filter(
>>>>> author__id=user.id)
>>>>>
>>>>>
>>>>> четверг, 30 апреля 2020 г., 11:34:28 UTC+3 пользователь Sergei Sokov 
>>>>> написал:
>>>>>>
>>>>>> А как тогда?
>>>>>> self.fields['name_job'].queryset = TypJob.objects.filter(author__id=
>>>>>> self.user.i

Two forms in one template

2020-05-04 Thread Sergei Sokov
I have two forms in one template, but one of them doesn't  have data to my 
database.
Why does it happen and how to fix it?

When I fill out the Pack form and press "submit" the terminal shows that: 
"POST" /sklad HTTP/1.1" 200 9937
This data doesn't save to my database.

When I fill out the Sklad form and press "submit" the terminal shows that: 
"POST" /sklad HTTP/1.1" 302 0
This data saves to my database fine.

views.py
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['sklad_form'] = SkladForm
kwargs['pack_form'] = PackForm
kwargs['list_sklad'] = Sklad.objects.all().order_by('material')
kwargs['list_pack'] = Pack.objects.all().order_by('name_pack')
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)

models.py
class Sklad(models.Model):
author = models.ForeignKey(User, on_delete = models.CASCADE, 
verbose_name='автор склада', null=True)
material = models.CharField('название', max_length=200)
unit = models.CharField('единица измерения', max_length=200)
description = models.CharField('описание', max_length=200, null=True)
price_buy = models.IntegerField('цена закупки', )
price_sell = models.IntegerField('цена продажи', )
amount = models.IntegerField('количество', default='0')

def __str__(self):
return self.material

class Pack(models.Model):
author = models.ForeignKey(User, on_delete = models.CASCADE, 
verbose_name='автор упаковки', null=True)
name_pack = models.CharField('название', max_length=100)
price_pack = models.IntegerField('цена', )

def __str__(self):
return self.name_pack


forms.py
class SkladForm(forms.ModelForm):
class Meta:
model = Sklad
fields = (
'material',
'unit',
'description',
'price_buy',
'price_sell',
'amount',
)

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs['class'] = 'form-control'

class PackForm(forms.ModelForm):
class Meta:
model = Pack
fields = (
'name_pack',
'price_pack',
)

def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
for field in self.fields:
self.fields[field].widget.attrs['class'] = 'form-control'


-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/dc035331-23e6-483e-b6d1-ba8847e2abe6%40googlegroups.com.


Re: Two forms in one template

2020-05-04 Thread Sergei Sokov
I guessed about it.
But I dont know how to do that.

понедельник, 4 мая 2020 г., 18:42:10 UTC+2 пользователь Sherif Adigun 
написал:
>
> Your code is working perfectly. Just that you need to remember that the 
> view has its model set to Sklad. Hence, when you called super() on 
> form_valid, only the Skald instance is saved. 
>
> You need to manually save the Pack form in the form_valid method. 
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/37a078e2-833a-4794-853d-896058ae2c0b%40googlegroups.com.


Re: Two forms in one template

2020-05-05 Thread Sergei Sokov
Thank you for answer.
I have this error when I try save data for SkladForm, when I press submit
Request Method: POST
Request URL: http://192.168.0.249:8000/sklad
Django Version: 3.0.5
Exception Type: KeyError
Exception Value: 

'pack_form'

Exception Location: /var/workspace/myp4/webprint/print/views.py in 
form_valid, line 362
line 362 is   pack_form = context['pack_form']

And the PackForm is empty, when I call it.

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):
context = super(SkladCreateView, self).get_context_data(**kwargs)
if self.request.POST:
context['pack_form'] = PackForm(self.request.POST)
else:
context['pack_form'] = PackForm()
return super().get_context_data(**kwargs)

kwargs['list_sklad'] = Sklad.objects.all().order_by('material')
kwargs['list_pack'] = Pack.objects.all().order_by('name_pack')
kwargs['list_hole'] = Hole.objects.all().order_by('name_hole')
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()

context = self.get_context_data()
pack_form = context['pack_form']
if pack_form.is_valid():
pack_form.instance = self.object
pack_form.save()
return super().form_valid(form)




вторник, 5 мая 2020 г., 11:30:57 UTC+2 пользователь Sherif Adigun написал:
>
> Try this code. Instead of using kwargs[], context is most common.
>
>
> 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['sklad_form'] = SkladForm # you do not need this anymore since 
> you have set the form_class above.
>   context = super(SkladCreateView, self).get_context_data(**kwargs)
>   if self.request.POST:
>context['pack_form'] = PackForm(self.request.POST)
>   else:
>context['pack_form'] = PackForm()
>   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()
>   context = self.get_context_data()
>   pack_form = context['pack_form']
>   if pack_form.is_valid():
>pack_form.instance = self.object
>pack_form.save()
>   return super().form_valid(form)
>
>
>
>
>
>
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/6a47b1be-e884-498e-817f-c91771de4ee2%40googlegroups.com.


Re: Two forms in one template

2020-05-05 Thread Sergei Sokov
I have this error when I try save data for SkladForm, when I press submit
Request Method: POST
Request URL: http://192.168.0.249:8000/sklad
Django Version: 3.0.5
Exception Type: KeyError
Exception Value: 

'pack_form'

Exception Location: /var/workspace/myp4/webprint/print/views.py in 
form_valid, line 362
line 362 is   pack_form = context['pack_form']

And the PackForm is empty, when I call it.


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')
kwargs['list_pack'] = Pack.objects.all().order_by('name_pack')
kwargs['list_hole'] = Hole.objects.all().order_by('name_hole')
context = super(SkladCreateView, self).get_context_data(**kwargs)
if self.request.POST:
context['pack_form'] = PackForm(self.request.POST)
else:
context['pack_form'] = PackForm()
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()

context = self.get_context_data()
pack_form = context['pack_form']
if pack_form.is_valid():
pack_form.instance = self.object
pack_form.save()
return super().form_valid(form)




вторник, 5 мая 2020 г., 18:08:56 UTC+2 пользователь Sherif Adigun написал:
>
> you have two returns in get_Context_data. use only this
>>
>
>
> def get_context_data(self, **kwargs):
> context = super(SkladCreateView, self).get_context_data(**kwargs)
> if self.request.POST:
> context['pack_form'] = PackForm(self.request.POST)
> else:
> context['pack_form'] = PackForm()
> return super().get_context_data(**kwargs) 
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/b3bcc2cc-aa55-42b1-a322-769f177c1862%40googlegroups.com.


Re: Two forms in one template

2020-05-06 Thread Sergei Sokov


[image: kwargs.JPG]
But the form is empty.

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')
kwargs['list_pack'] = Pack.objects.all().order_by('name_pack')
kwargs['list_hole'] = Hole.objects.all().order_by('name_hole')
context = super(SkladCreateView, self).get_context_data(**kwargs)
if self.request.POST:
context['pack_form'] = PackForm(self.request.POST)
else:
context['pack_form'] = PackForm()
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()

context = self.get_context_data()
pack_form = context['pack_form']
# if pack_form.is_valid():
# pack_form.instance = self.object
# pack_form.save()
print(pack_form)
return super().form_valid(form)



вторник, 5 мая 2020 г., 22:17:08 UTC+2 пользователь Sherif Adigun написал:
>
> Please remove 
>
>   if pack_form.is_valid():
> pack_form.instance = self.object
> pack_form.save()
>
>
> And replace with print(pack_form)
>
>
> Then let's see what it's printing in the console
>
> On Tue, May 5, 2020, 8:30 PM Sergei Sokov > 
> wrote:
>
>> I have this error when I try save data for SkladForm, when I press submit
>> Request Method: POST
>> Request URL: http://192.168.0.249:8000/sklad
>> Django Version: 3.0.5
>> Exception Type: KeyError
>> Exception Value: 
>>
>> 'pack_form'
>>
>> Exception Location: /var/workspace/myp4/webprint/print/views.py in 
>> form_valid, line 362
>> line 362 is   pack_form = context['pack_form']
>>
>> And the PackForm is empty, when I call it.
>>
>>
>> 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')
>> kwargs['list_pack'] = Pack.objects.all().order_by('name_pack')
>> kwargs['list_hole'] = Hole.objects.all().order_by('name_hole')
>> context = super(SkladCreateView, self).get_context_data(**kwargs)
>> if self.request.POST:
>> context['pack_form'] = PackForm(self.request.POST)
>> else:
>> context['pack_form'] = PackForm()
>> 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()
>>
>> context = self.get_context_data()
>> pack_form = context['pack_form']
>> if pack_form.is_valid():
>> pack_form.instance = self.object
>> pack_form.save()
>> return super().form_valid(form)
>>
>>
>>
>>
>> вторник, 5 мая 2020 г., 18:08:56 UTC+2 пользователь Sherif Adigun написал:
>>>
>>> you have two returns in get_Context_data. use only this
>>>>
>>>
>>>
>>> def get_context_data(self, **kwargs):
>>> context = super(SkladCreateView, self).get_context_data(**kwargs)
>>> if self.request.POST:
>>> context['pack_form'] = PackForm(self.request.POST)
>>> else:
>>> context['pack_form'] = PackForm()
>>> return super().get_context_data(**kwargs) 
>>>
>> -- 
>> You received this message because you are subscribed to a topic in the 
>> Google Groups "Django users" group.
>> To unsubscribe from this topic, visit 
>> https://groups.google.com/d/topic/django-users/I_32m8lWd-g/unsubscribe.
>> To unsubscribe from this group and all its topics, send an email to 
>> django...@googlegroups.com .
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/b3bcc2cc-aa55-42b1-a322-769f177c1862%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/b3bcc2cc-aa55-42b1-a322-769f177c1862%40googlegroups.com?utm_medium=email&utm_source=footer>
>> .
>>
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/e6bd5958-e885-488c-85e8-9452589d50cf%40googlegroups.com.


Re: Two forms in one template

2020-05-06 Thread Sergei Sokov
my zoom
Sergey Sokov

среда, 6 мая 2020 г., 10:37:42 UTC+2 пользователь Sergei Sokov написал:
>
> I can but my english is very bad.
>
> среда, 6 мая 2020 г., 10:08:47 UTC+2 пользователь Sherif Adigun написал:
>>
>> Can you come to zoom so we fix this ones and for all
>>
>> On Wed, May 6, 2020, 8:13 AM Sergei Sokov  wrote:
>>
>>> [image: kwargs.JPG]
>>> But the form is empty.
>>>
>>> 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')
>>> kwargs['list_pack'] = Pack.objects.all().order_by('name_pack')
>>> kwargs['list_hole'] = Hole.objects.all().order_by('name_hole')
>>> context = super(SkladCreateView, self).get_context_data(**kwargs)
>>> if self.request.POST:
>>> context['pack_form'] = PackForm(self.request.POST)
>>> else:
>>> context['pack_form'] = PackForm()
>>> 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()
>>>
>>> context = self.get_context_data()
>>> pack_form = context['pack_form']
>>> # if pack_form.is_valid():
>>> # pack_form.instance = self.object
>>> # pack_form.save()
>>> print(pack_form)
>>> return super().form_valid(form)
>>>
>>>
>>>
>>> вторник, 5 мая 2020 г., 22:17:08 UTC+2 пользователь Sherif Adigun 
>>> написал:
>>>>
>>>> Please remove 
>>>>
>>>>   if pack_form.is_valid():
>>>> pack_form.instance = self.object
>>>> pack_form.save()
>>>>
>>>>
>>>> And replace with print(pack_form)
>>>>
>>>>
>>>> Then let's see what it's printing in the console
>>>>
>>>> On Tue, May 5, 2020, 8:30 PM Sergei Sokov  wrote:
>>>>
>>>>> I have this error when I try save data for SkladForm, when I press 
>>>>> submit
>>>>> Request Method: POST
>>>>> Request URL: http://192.168.0.249:8000/sklad
>>>>> Django Version: 3.0.5
>>>>> Exception Type: KeyError
>>>>> Exception Value: 
>>>>>
>>>>> 'pack_form'
>>>>>
>>>>> Exception Location: /var/workspace/myp4/webprint/print/views.py in 
>>>>> form_valid, line 362
>>>>> line 362 is   pack_form = context['pack_form']
>>>>>
>>>>> And the PackForm is empty, when I call it.
>>>>>
>>>>>
>>>>> 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')
>>>>> kwargs['list_pack'] = Pack.objects.all().order_by('name_pack')
>>>>> kwargs['list_hole'] = Hole.objects.all().order_by('name_hole')
>>>>> context = super(SkladCreateView, 
>>>>> self).get_context_data(**kwargs)
>>>>> if self.request.POST:
>>>>> context['pack_form'] = PackForm(self.request.POST)
>>>>> else:
>>>>> context['pack_form'] = PackForm()
>>>>> return super().get_context_data(**kwargs) 
>>>>>
>>>>> def form_valid(self, form):
>>>>> self.object = form.save(commit=False)
>>>>>

Re: Two forms in one template

2020-05-06 Thread Sergei Sokov
I can but my english is very bad.

среда, 6 мая 2020 г., 10:08:47 UTC+2 пользователь Sherif Adigun написал:
>
> Can you come to zoom so we fix this ones and for all
>
> On Wed, May 6, 2020, 8:13 AM Sergei Sokov > 
> wrote:
>
>> [image: kwargs.JPG]
>> But the form is empty.
>>
>> 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')
>> kwargs['list_pack'] = Pack.objects.all().order_by('name_pack')
>> kwargs['list_hole'] = Hole.objects.all().order_by('name_hole')
>> context = super(SkladCreateView, self).get_context_data(**kwargs)
>> if self.request.POST:
>> context['pack_form'] = PackForm(self.request.POST)
>> else:
>> context['pack_form'] = PackForm()
>> 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()
>>
>> context = self.get_context_data()
>> pack_form = context['pack_form']
>> # if pack_form.is_valid():
>> # pack_form.instance = self.object
>> # pack_form.save()
>> print(pack_form)
>> return super().form_valid(form)
>>
>>
>>
>> вторник, 5 мая 2020 г., 22:17:08 UTC+2 пользователь Sherif Adigun написал:
>>>
>>> Please remove 
>>>
>>>   if pack_form.is_valid():
>>> pack_form.instance = self.object
>>> pack_form.save()
>>>
>>>
>>> And replace with print(pack_form)
>>>
>>>
>>> Then let's see what it's printing in the console
>>>
>>> On Tue, May 5, 2020, 8:30 PM Sergei Sokov  wrote:
>>>
>>>> I have this error when I try save data for SkladForm, when I press 
>>>> submit
>>>> Request Method: POST
>>>> Request URL: http://192.168.0.249:8000/sklad
>>>> Django Version: 3.0.5
>>>> Exception Type: KeyError
>>>> Exception Value: 
>>>>
>>>> 'pack_form'
>>>>
>>>> Exception Location: /var/workspace/myp4/webprint/print/views.py in 
>>>> form_valid, line 362
>>>> line 362 is   pack_form = context['pack_form']
>>>>
>>>> And the PackForm is empty, when I call it.
>>>>
>>>>
>>>> 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')
>>>> kwargs['list_pack'] = Pack.objects.all().order_by('name_pack')
>>>> kwargs['list_hole'] = Hole.objects.all().order_by('name_hole')
>>>> context = super(SkladCreateView, 
>>>> self).get_context_data(**kwargs)
>>>> if self.request.POST:
>>>> context['pack_form'] = PackForm(self.request.POST)
>>>> else:
>>>> context['pack_form'] = PackForm()
>>>> 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()
>>>>
>>>> context = self.get_context_data()
>>>> pack_form = context['pack_form']
>>>> if pack_form.is_valid():
>>>> pack_form.instance = self.object
>>>> pack_form.save()
>>>> return super().form_valid(form)
>>>>
>>>>
>>>

Re: Two forms in one template

2020-05-06 Thread Sergei Sokov
I can a little bit later, ok?
I think in 2 hour

среда, 6 мая 2020 г., 12:00:13 UTC+2 пользователь Sherif Adigun написал:
>
> Please join the meeting now let's quickly fix it .
>
> https://us04web.zoom.us/j/77729655336?pwd=c1o2Q0JQOFJiYm5hTlJTYjgra0dOQT09
>
> On Monday, May 4, 2020 at 4:37:39 PM UTC+1, Sergei Sokov wrote:
>>
>> I have two forms in one template, but one of them doesn't  have data to 
>> my database.
>> Why does it happen and how to fix it?
>>
>> When I fill out the Pack form and press "submit" the terminal shows that: 
>> "POST" /sklad HTTP/1.1" 200 9937
>> This data doesn't save to my database.
>>
>> When I fill out the Sklad form and press "submit" the terminal shows 
>> that: "POST" /sklad HTTP/1.1" 302 0
>> This data saves to my database fine.
>>
>> views.py
>> 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['sklad_form'] = SkladForm
>> kwargs['pack_form'] = PackForm
>> kwargs['list_sklad'] = Sklad.objects.all().order_by('material')
>> kwargs['list_pack'] = Pack.objects.all().order_by('name_pack')
>> 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)
>>
>> models.py
>> class Sklad(models.Model):
>> author = models.ForeignKey(User, on_delete = models.CASCADE, 
>> verbose_name='автор склада', null=True)
>> material = models.CharField('название', max_length=200)
>> unit = models.CharField('единица измерения', max_length=200)
>> description = models.CharField('описание', max_length=200, null=True)
>> price_buy = models.IntegerField('цена закупки', )
>> price_sell = models.IntegerField('цена продажи', )
>> amount = models.IntegerField('количество', default='0')
>>
>> def __str__(self):
>> return self.material
>>
>> class Pack(models.Model):
>> author = models.ForeignKey(User, on_delete = models.CASCADE, 
>> verbose_name='автор упаковки', null=True)
>> name_pack = models.CharField('название', max_length=100)
>> price_pack = models.IntegerField('цена', )
>>
>> def __str__(self):
>> return self.name_pack
>>
>>
>> forms.py
>> class SkladForm(forms.ModelForm):
>> class Meta:
>> model = Sklad
>> fields = (
>> 'material',
>> 'unit',
>> 'description',
>> 'price_buy',
>> 'price_sell',
>> 'amount',
>> )
>>
>> def __init__(self, *args, **kwargs):
>> super().__init__(*args, **kwargs)
>> for field in self.fields:
>> self.fields[field].widget.attrs['class'] = 'form-control'
>>
>> class PackForm(forms.ModelForm):
>> class Meta:
>> model = Pack
>> fields = (
>> 'name_pack',
>> 'price_pack',
>> )
>>
>> def __init__(self, *args, **kwargs):
>> super().__init__(*args, **kwargs)
>> for field in self.fields:
>> self.fields[field].widget.attrs['class'] = 'form-control'
>>
>>
>>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/257e308b-91d3-4fa3-8f8f-ca758b72e7e0%40googlegroups.com.


Re: Two forms in one template

2020-05-06 Thread Sergei Sokov
I am ready

среда, 6 мая 2020 г., 12:35:28 UTC+2 пользователь Sherif Adigun написал:
>
> ok. send a reply when you are available.
>
> On Wed, May 6, 2020 at 11:13 AM Sergei Sokov  > wrote:
>
>> I can a little bit later, ok?
>> I think in 2 hour
>>
>> среда, 6 мая 2020 г., 12:00:13 UTC+2 пользователь Sherif Adigun написал:
>>>
>>> Please join the meeting now let's quickly fix it .
>>>
>>>
>>> https://us04web.zoom.us/j/77729655336?pwd=c1o2Q0JQOFJiYm5hTlJTYjgra0dOQT09
>>>
>>> On Monday, May 4, 2020 at 4:37:39 PM UTC+1, Sergei Sokov wrote:
>>>>
>>>> I have two forms in one template, but one of them doesn't  have data to 
>>>> my database.
>>>> Why does it happen and how to fix it?
>>>>
>>>> When I fill out the Pack form and press "submit" the terminal shows 
>>>> that: "POST" /sklad HTTP/1.1" 200 9937
>>>> This data doesn't save to my database.
>>>>
>>>> When I fill out the Sklad form and press "submit" the terminal shows 
>>>> that: "POST" /sklad HTTP/1.1" 302 0
>>>> This data saves to my database fine.
>>>>
>>>> views.py
>>>> 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['sklad_form'] = SkladForm
>>>> kwargs['pack_form'] = PackForm
>>>> kwargs['list_sklad'] = Sklad.objects.all().order_by('material')
>>>> kwargs['list_pack'] = Pack.objects.all().order_by('name_pack')
>>>> 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)
>>>>
>>>> models.py
>>>> class Sklad(models.Model):
>>>> author = models.ForeignKey(User, on_delete = models.CASCADE, 
>>>> verbose_name='автор склада', null=True)
>>>> material = models.CharField('название', max_length=200)
>>>> unit = models.CharField('единица измерения', max_length=200)
>>>> description = models.CharField('описание', max_length=200, null=True)
>>>> price_buy = models.IntegerField('цена закупки', )
>>>> price_sell = models.IntegerField('цена продажи', )
>>>> amount = models.IntegerField('количество', default='0')
>>>>
>>>> def __str__(self):
>>>> return self.material
>>>>
>>>> class Pack(models.Model):
>>>> author = models.ForeignKey(User, on_delete = models.CASCADE, 
>>>> verbose_name='автор упаковки', null=True)
>>>> name_pack = models.CharField('название', max_length=100)
>>>> price_pack = models.IntegerField('цена', )
>>>>
>>>> def __str__(self):
>>>> return self.name_pack
>>>>
>>>>
>>>> forms.py
>>>> class SkladForm(forms.ModelForm):
>>>> class Meta:
>>>> model = Sklad
>>>> fields = (
>>>> 'material',
>>>> 'unit',
>>>> 'description',
>>>> 'price_buy',
>>>> 'price_sell',
>>>> 'amount',
>>>> )
>>>>
>>>> def __init__(self, *args, **kwargs):
>>>> super().__init__(*args, **kwargs)
>>>> for field in self.fields:
>>>> self.fields[field].widget.attrs['class'] = 'form-control'
>>>>
>>>> class PackForm(forms.ModelForm):
>>>> class Meta:
>>>> model = Pack
>>>> fields = (
>>>> 'name_pack',
>>>> 'price_pack',
>>>> )
>>>>
>>>> def __init__(self, *args, **kwargs):
>>>> super().__init__(*args, **kwargs)
>>>> for field in self.fields:
>>>> self.fields[field].widget.attrs['class'] = 'form-control'
>>>>
>>>>
>>>> -- 
>> You received this message because you are subscribed to a topic in the 
>> Google Groups "Django users" group.
>> To unsubscribe from this topic, visit 
>> https://groups.google.com/d/topic/django-users/I_32m8lWd-g/unsubscribe.
>> To unsubscribe from this group and all its topics, send an email to 
>> django...@googlegroups.com .
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/257e308b-91d3-4fa3-8f8f-ca758b72e7e0%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/257e308b-91d3-4fa3-8f8f-ca758b72e7e0%40googlegroups.com?utm_medium=email&utm_source=footer>
>> .
>>
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/1ec08501-5c34-4f1b-b5e2-10e03362e835%40googlegroups.com.


Re: Two forms in one template

2020-05-06 Thread Sergei Sokov
Thank you very much!!
You are best!!!

среда, 6 мая 2020 г., 15:09:39 UTC+2 пользователь Sherif Adigun написал:
>
> https://us04web.zoom.us/j/79500561313?pwd=TnIzekVTMU0xRDNsaGpaS0kxQlhTdz09
>
>
> JOIN NOW
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/60cfdac9-6060-4605-8a89-3477791b27e3%40googlegroups.com.


How to make to display the button which I need in my template Django?

2020-05-16 Thread Sergei Sokov


I need:

1) If a user has created a object of the class by a form, then he sees the 
button which calls the webpage of the object detail.

2)  If a user didn't create a object of the class, but another user did it, 
then he sees the button which calls this form to create a object and the 
user will be a author this object.

3) If a user didn't create a object of the class by a form, then he sees 
the button which calls this form.


If a user didn't create a object of the class, but another user did it, 
then he sees the button which calls this form to create a object and the 
user will be a author this object.


I made this:


{% if list %}
{% for i in list %}
{% if request.user == i.author %}

  {{i.detail}}

{% else %}
   
 Кнопка для вызова формы
   
{% endif %}
{% endfor %}
{% else %}

  Кнопка для вызова формы
{% endif %}


But if a user created a object of the class, then he sees both button.

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/5844076b-d426-40db-bc93-1dfa7d5be510%40googlegroups.com.


How to create custom tag - break for tamplate?

2020-05-16 Thread Sergei Sokov
Hi
I would like abort a loop in my template.
How to create custom tag - break for tamplate?

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/127f2c81-ab88-4d40-b08a-f8d7d86bdb37%40googlegroups.com.


Re: How to create custom tag - break for tamplate?

2020-05-17 Thread Sergei Sokov


views.py

class MyClassCreateView(LoginRequiredMixin, CustomSuccessMessageMixin, 
CreateView):
model = MyClass
template_name = 'mypage.html'
form_class = MyClassForm
success_url = reverse_lazy('mypage')
success_msg = 'сохранён'
def get_context_data(self, **kwargs):
kwargs['list_mylist'] = MyClass.objects.all()
list_mylist = kwargs['list_mylist']
for i in list_mylist:
if i.author == self.request.user:
print('my_button')
kwargs['my_button'] = True
break
return super().get_context_data(**kwargs)

template

{% if my_button %}
   {% for i in list_mylist %}
 {% if request.user == i.author %}

  кнопка первая

 {% endif %}
   {% endfor %}
{% else %}

  кнопка вторая

    {% endif %}




суббота, 16 мая 2020 г., 20:05:01 UTC+2 пользователь Sergei Sokov написал:
>
> Hi
> I would like abort a loop in my template.
> How to create custom tag - break for tamplate?
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/5f05fc6e-13a0-47ba-be33-9c860dc48dee%40googlegroups.com.


How to get a full path of web page to my views.py?

2020-06-07 Thread Sergei Sokov
I have the path in the web browser like this
http://192.168.0.178:8000/customers-orders/37/customers-orders-date/?datefilter=06%2F14%2F2020+-+06%2F26%2F2020

How to get this path to my views.py for to work with it?

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/c241e2d0-e83c-4f30-a4cb-3005728fae9ao%40googlegroups.com.


Re: How to get a full path of web page to my views.py?

2020-06-09 Thread Sergei Sokov
I would like to use a current url path in my views.py

понедельник, 8 июня 2020 г., 14:25:25 UTC+2 пользователь Rupesh Dahal 
написал:
>
> Can you please elaborate your problem.
>
> On Monday, June 8, 2020 at 12:26:12 AM UTC+5:45, Sergei Sokov wrote:
>>
>> I have the path in the web browser like this
>>
>> http://192.168.0.178:8000/customers-orders/37/customers-orders-date/?datefilter=06%2F14%2F2020+-+06%2F26%2F2020
>>
>> How to get this path to my views.py for to work with it?
>>
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/d6fe7979-a895-4797-98b1-ea4fdbdc8c34o%40googlegroups.com.


Re: How to get a full path of web page to my views.py?

2020-06-09 Thread Sergei Sokov
Thank you

вторник, 9 июня 2020 г., 15:37:39 UTC+2 пользователь RyuCoder написал:
>
> https://docs.djangoproject.com/en/3.0/ref/request-response/ 
> <https://docs.djangoproject.com/en/3.0/ref/request-response/#:~:text=Quick%20overview,argument%20to%20the%20view%20function>
>
> On Tue, Jun 9, 2020, 6:41 PM Sergei Sokov > 
> wrote:
>
>> I would like to use a current url path in my views.py
>>
>> понедельник, 8 июня 2020 г., 14:25:25 UTC+2 пользователь Rupesh Dahal 
>> написал:
>>>
>>> Can you please elaborate your problem.
>>>
>>> On Monday, June 8, 2020 at 12:26:12 AM UTC+5:45, Sergei Sokov wrote:
>>>>
>>>> I have the path in the web browser like this
>>>>
>>>> http://192.168.0.178:8000/customers-orders/37/customers-orders-date/?datefilter=06%2F14%2F2020+-+06%2F26%2F2020
>>>>
>>>> How to get this path to my views.py for to work with it?
>>>>
>>> -- 
>> 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 .
>> To view this discussion on the web visit 
>> https://groups.google.com/d/msgid/django-users/d6fe7979-a895-4797-98b1-ea4fdbdc8c34o%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/d6fe7979-a895-4797-98b1-ea4fdbdc8c34o%40googlegroups.com?utm_medium=email&utm_source=footer>
>> .
>>
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/c529f1ea-d1e0-4e1b-b942-a578a174359co%40googlegroups.com.


Re: Two forms in one template

2021-02-04 Thread Sergei Sokov
Hi, I have same problem.
I am doing same like did you but it doesnt work. POST doesnt work.
Could you please hrlp me with it?

среда, 6 мая 2020 г. в 12:47:00 UTC-1, adigun...@gmail.com: 

> You are welcome.
>
> I'm happy to help
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/5e47a142-3526-45b4-895d-60c7aa5eab3an%40googlegroups.com.


Re: Two forms in one template

2021-02-04 Thread Sergei Sokov
Thank you so mach!

четверг, 4 февраля 2021 г. в 14:13:24 UTC-1, wne...@gmail.com: 

> https://riptutorial.com/django/example/16667/one-view--multiple-forms
> https://pylab.ru/django-dve-formy-v-odnom-view/
>
>
> четверг, 4 февраля 2021 г. в 16:44:54 UTC+3, soko...@gmail.com: 
>
>> Hi, I have same problem.
>> I am doing same like did you but it doesnt work. POST doesnt work.
>> Could you please hrlp me with it?
>>
>> среда, 6 мая 2020 г. в 12:47:00 UTC-1, adigun...@gmail.com: 
>>
>>> You are welcome.
>>>
>>> I'm happy to help
>>>
>>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/5f36a83f-a973-4131-9f78-1f3b8f365466n%40googlegroups.com.


Django does't send email on the remote server

2021-02-23 Thread Sergei Sokov
I am trying to send an email when a user fills out a form on my site.
Everything works on my local server, letters are sent and I am got them.
On a remote timeweb.com server with the same settings, letters are not sent.
Tried DEBUG = False and True
I tried different mail services: gmail, mail, yandex, timeweb mail.
In gmail included "Unreliable applications that have access to the account".
And here I included https://accounts.google.com/DisplayUnlockCaptcha
Nothing helps.

Who knows, please tell me where to dig.

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/9c081e17-30ad-4bf9-9728-6b3010b3736an%40googlegroups.com.


Re: Django does't send email on the remote server

2021-02-23 Thread Sergei Sokov


'setting.py'
EMAIL_BACKEND = "django.core.mail.backends.smtp.EmailBackend"
EMAIL_HOST_USER = "em...@gmail.com"
EMAIL_HOST = "smtp.gmail.com" EMAIL_PORT = 587
EMAIL_USE_TLS = True
EMAIL_HOST_PASSWORD = "Your_Password"


   I have chtcked spam, I have tried different email services   
   I switched the security allow less secure app on
   
вторник, 23 февраля 2021 г. в 12:05:27 UTC+1, anubhavg...@gmail.com: 

> you should be using app password instead of less secure option 
>
> On Tue, Feb 23, 2021 at 3:36 PM Sergei Sokov  wrote:
>
>> I am trying to send an email when a user fills out a form on my site.
>> Everything works on my local server, letters are sent and I am got them.
>> On a remote timeweb.com server with the same settings, letters are not 
>> sent.
>> Tried DEBUG = False and True
>> I tried different mail services: gmail, mail, yandex, timeweb mail.
>> In gmail included "Unreliable applications that have access to the 
>> account".
>> And here I included https://accounts.google.com/DisplayUnlockCaptcha
>> Nothing helps.
>>
>> Who knows, please tell me where to dig.
>>
>> -- 
>>
> 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/9c081e17-30ad-4bf9-9728-6b3010b3736an%40googlegroups.com
>>  
>> <https://groups.google.com/d/msgid/django-users/9c081e17-30ad-4bf9-9728-6b3010b3736an%40googlegroups.com?utm_medium=email&utm_source=footer>
>> .
>>
>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/5a345341-e0b6-4d81-87d4-b2cbdcbbd1c0n%40googlegroups.com.


Why _thread doesnt work on the remote server?

2021-02-26 Thread Sergei Sokov


This code works on my local server, but doesnt work on the hosting. What 
could be the problem?
import _thread

def email_index(*args):
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('k...@gmail.com', 'pas')
try:
server.sendmail('k...@gmail.com', 's...@gmail.com', 
body_mes.encode('utf-8')) print('ok')
 except:
 print('An error occurred when trying to send an email')
try:
_thread.start_new_thread( email_index, ("Thread-1", 2, ) )
except:
print ("Error: unable to start thread")

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/ef6bd638-9d05-42ce-8de2-8397e01d9813n%40googlegroups.com.


Re: Django does't send email on the remote server

2021-02-26 Thread Sergei Sokov
This code is working
server = smtplib.SMTP('smtp.gmail.com', 587)
server.starttls()
server.login('k...@gmail.com', 'pas')
try:
server.sendmail('k...@gmail.com', 's...@gmail.com', 
body_mes.encode('utf-8')) print('ok')
 except:
 print('An error occurred when trying to send an email')

четверг, 25 февраля 2021 г. в 21:53:26 UTC+1, ule...@gmail.com: 

> i can send email when i use a local server 127.0.0.1:8000 but when i use 
> pythonanywhere.com or eu.pythonanywhere.com 
> i can not send mails
>
> Op donderdag 25 februari 2021 om 21:44:53 UTC+1 schreef Mike Dewhirst:
>
>> On 26/02/2021 7:26 am, ule...@gmail.com wrote: 
>> > Any solution ? 
>>
>> You need a friendly sysadmin from your mail provider. Nowadays with so 
>> much spam and botnet activity there are  many email relay checks and 
>> hurdles to deal with. Your remote server has to be established with your 
>> provider and recognised as a bona fide sender. 
>>
>> > 
>> > Op dinsdag 23 februari 2021 om 18:42:42 UTC+1 schreef ule...@gmail.com: 
>>
>> > 
>> > I have this same problem when i use smtp = out.telenet.be 
>> >  
>> > on my local server it works fine but when it use 
>> > pythonanywhere.com  i get OSError: 
>> > [Errno 101] Network is unreachable 
>> > 
>> > Op dinsdag 23 februari 2021 om 11:06:09 UTC+1 schreef 
>> > soko...@gmail.com: 
>> > 
>> > I am trying to send an email when a user fills out a form on 
>> > my site. 
>> > Everything works on my local server, letters are sent and I am 
>> > got them. 
>> > On a remote timeweb.com  server with the 
>> > same settings, letters are not sent. 
>> > Tried DEBUG = False and True 
>> > I tried different mail services: gmail, mail, yandex, timeweb 
>> > mail. 
>> > In gmail included "Unreliable applications that have access to 
>> > the account". 
>> > And here I included 
>> > https://accounts.google.com/DisplayUnlockCaptcha 
>> >  
>> > Nothing helps. 
>> > 
>> > Who knows, please tell me where to dig. 
>> > 
>> > -- 
>> > 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/671d189a-3fc3-426b-a579-18e8f08421b9n%40googlegroups.com
>>  
>> > <
>> https://groups.google.com/d/msgid/django-users/671d189a-3fc3-426b-a579-18e8f08421b9n%40googlegroups.com?utm_medium=email&utm_source=footer>.
>>  
>>
>>
>>
>> -- 
>> Signed email is an absolute defence against phishing. This email has 
>> been signed with my private key. If you import my public key you can 
>> automatically decrypt my signature and be sure it came from me. Just 
>> ask and I'll send it to you. Your email software can handle signing. 
>>
>>
>>

-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/24577fe3-f08c-446a-9b95-156abced57ccn%40googlegroups.com.


Why does my django form with recaptcha send data even empty the recaptcha?

2021-03-11 Thread Sergei Sokov
I put the google recaptcha V2 to my django project form. It looks like 
working, but if I leave empty the recaptcha checkbox my form is sent still.

forms.py
from django import
forms from captcha.fields
import ReCaptchaField
from django.forms import Textarea
from .models import *
class CustomerForm(forms.ModelForm):
captcha = ReCaptchaField( public_key='key', private_key='key', )
class Meta:
model = Customer fields = '__all__'
def __init__(self, *args, **kwargs):
# get 'user' param from kwargs
user = kwargs.pop('user', None)
super().__init__(*args, **kwargs)
self.fields['message'].widget = Textarea(attrs={'rows': 4})
self.fields['i_have_read_rules'].widget.attrs['required'] = 'True'
self.fields['i_agree'].widget.attrs['required'] = 'True'
self.fields['captcha'].widget.attrs['required'] = 'True'
for field in self.fields:
self.fields[field].widget.attrs['class'] = 'form-control'
self.fields['i_have_read_rules'].widget.attrs['class'] = 
'form-check'
self.fields['i_agree'].widget.attrs['class'] = 'form-check'

html

{% csrf_token %}
Выберите услугу
{{form.choice_services}}
{{form.name}}
{{form.telephone_number}}
{{form.email}}
{{form.message}}
{{form.contact_text}}
 {{ 
form.captcha }}


-- 
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+unsubscr...@googlegroups.com.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-users/e18dcba2-07e2-44d9-ace6-744a2bb69234n%40googlegroups.com.


Re: Why does my django form with recaptcha send data even empty the recaptcha?

2021-03-13 Thread Sergei Sokov
html


{% csrf_token %}
{{form.choice_services}}
{{form.name}}
{{form.telephone_number}}
{{form.email}}
{{form.message}}
{{form.contact_text}}
{{ form.captcha }}





https://www.google.com/recaptcha/api.js?render=reCAPTCHA_site_key"</a>;>

window.onload = function() {
var $recaptcha = document.querySelector('#g-recaptcha-response');

if($recaptcha) {
$recaptcha.setAttribute("required", "required");
}
  const $form = document.querySelector('form');
  $form.addEventListener('submit', (event) => {
event.preventDefault();
console.log('prevented submit by code for demo');
  });
};


css

#g-recaptcha-response {
display: block !important;
position: absolute;
margin: -78px 0 0 0 !important;
width: 302px !important;
height: 76px !important;
z-index: -99;
opacity: 0;
}

пятница, 12 марта 2021 г. в 21:06:56 UTC+1, RyuCoder: 

> Remove below line and try again
>
> self.fields['captcha'].widget.attrs['required'] = 'True'
>
>
> If the problem persists, try some js or jquery validation in frontend
>
>
>
>
>
> On Thu, Mar 11, 2021, 9:19 PM Gabriel Araya Garcia  
> wrote:
>
>> Camarada Sokov:
>> Your code is very difficult to understand at first sight. I did not know 
>> about ReCaptchaField().
>> But, is interesting to learn something new.
>>
>> Recards,
>>
>> Gabriel Araya Garcia
>> GMI - Desarrollo de Sistemas Informáticos
>> from Santiago de Chile
>>
>>
>>
>> El jue, 11 mar 2021 a las 12:40, Sergei Sokov () 
>> escribió:
>>
>>> I put the google recaptcha V2 to my django project form. It looks like 
>>> working, but if I leave empty the recaptcha checkbox my form is sent still.
>>>
>>> forms.py
>>> from django import
>>> forms from captcha.fields
>>> import ReCaptchaField
>>> from django.forms import Textarea
>>> from .models import *
>>> class CustomerForm(forms.ModelForm):
>>> captcha = ReCaptchaField( public_key='key', private_key='key', )
>>> class Meta:
>>> model = Customer fields = '__all__'
>>> def __init__(self, *args, **kwargs):
>>> # get 'user' param from kwargs
>>> user = kwargs.pop('user', None)
>>> super().__init__(*args, **kwargs)
>>> self.fields['message'].widget = Textarea(attrs={'rows': 4})
>>> self.fields['i_have_read_rules'].widget.attrs['required'] = 
>>> 'True'
>>> self.fields['i_agree'].widget.attrs['required'] = 'True'
>>> self.fields['captcha'].widget.attrs['required'] = 'True'
>>> for field in self.fields:
>>> self.fields[field].widget.attrs['class'] = 'form-control'
>>> self.fields['i_have_read_rules'].widget.attrs['class'] = 
>>> 'form-check'
>>> self.fields['i_agree'].widget.attrs['class'] = 'form-check'
>>>
>>> html
>>> 
>>> {% csrf_token %}
>>> Выберите услугу
>>> >> class="form-group">{{form.choice_services}}
>>> {{form.name}}
>>> >> class="form-group">{{form.telephone_number}}
>>> {{form.email}}
>>> {{form.message}}
>>> {{form.contact_text}}
>>>  {{ 
>>> form.captcha }}
>>> 
>>>
>>> -- 
>>> 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/e18dcba2-07e2-44d9-ace6-744a2bb69234n%40googlegroups.com
>>>  
>>> <https://groups.google.com/d/msgid/django-users/e18dcba2-07e2-44d9-ace6-744a