Re: ModelForm unique validation is not done right IMHO.

2018-09-24 Thread Protik
Yes, it is working now.

Thank you very much.

On Monday, September 24, 2018 at 1:43:00 PM UTC+5:30, Todor Velichkov wrote:
>
> Protik, just use `self.fields['user'].initial = user.id` instead of just 
> `user`. Just tested it and it work fine. 
>
> On Monday, September 24, 2018 at 9:36:19 AM UTC+3, Protik wrote:
>>
>>
>> Book.objects.filter(user=form.user, name=form.cleaned_data["name"]). 
>> exists()
>>
>> This will only work for creating records, not updating.
>>
>> But what's the issue with the current solution posted by Todor. If you 
>> look at the model form it looks like this:
>>
>> class BookForm(forms.ModelForm):
>> class Meta:
>>  model = Book
>>  fields = ('user', 'name')
>>
>> def __init__(self, *args, **kwargs):
>> user = kwargs.pop('user')
>> super(BookForm, self).__init__(*args, **kwargs)
>> self.fields['user'].widget = forms.HiddenInput()
>> self.fields['user'].initial = user
>> self.fields['user'].disabled = True
>>
>> Logically, It should work. But it is not, so far I have checked this code 
>> with django version 1.11 and 2.1. 
>>
>> What do you think where the problem lies?
>>
>> On Monday, September 24, 2018 at 11:39:58 AM UTC+5:30, ludovic coues 
>> wrote:
>>>
>>> First, that's a discussion for the Django user list, not the Django 
>>> developers one.
>>>
>>> I would add a clean_book method on the form and use it to check if the 
>>> user already have a book with that name. For that specific problems, that's 
>>> the cleanest solution in my opinion. Simply do a 
>>> Book.objects.filter(user=form.user, name=form.cleaned_data["name"]). 
>>> exists() and if you get a hit, raise a Validation error. The error will be 
>>> associated to the book field.
>>>
>>> If someone want to write a patch for adding full validation of a 
>>> ModelForm, I wish them good luck. You could try a save commit=False but you 
>>> will only get an integrity error and a string coming from the database. 
>>> Which can be translated. You could check for your unique_together with an 
>>> extra request. Then the form will raise a Validation error saying there is 
>>> already a book with that user and that name. Confusing the user.
>>>
>>> If you think a ModelForm giving guarantee that the save method will work 
>>> make sense, the best way to proceed is a third party module. Doing so let 
>>> you do quick release for development and testing, user will be able try the 
>>> module and see if it solves their problems. In my opinion, something 
>>> generic won't help when validating unique_together relationship when one of 
>>> the fields is not exposed to the user. But I could be wrong.
>>>
>>> On Sep 24, 2018 07:34, "Protik"  wrote:
>>>
>>> I am using Django 1.11. Further, adding a new book with user field 
>>> disabled results in the following error:
>>>
>>> [image: Selection_046.png]
>>>
>>>
>>> I have attached the code to reproduce the error.
>>>
>>>
>>> On Monday, September 24, 2018 at 1:59:31 AM UTC+5:30, Todor Velichkov 
>>> wrote:

 First thought: What is your Django version? The `disabled` attribute 
 was added in Django 1.9.
 However by looking at your code (w/o testing anything) after 
 `form.is_valid()` you should only call `form.save()`, no need to do 
 `commit=False` and manually assigning user, you have already done that in 
 the form constructor (by settings initial value + disabled attr).

 On Sunday, September 23, 2018 at 9:25:41 PM UTC+3, Protik wrote:
>
> Hi, Todor
>
> I have tested this solution and It looks like it works only when you 
> don't disable the field (i.e the last line in the BookForm's `__init__()` 
> method. My views looks like this:
>
>
> def book_add(request):
> user = get_object_or_404(User, id=1)
>
> if request.method == 'POST':
>
> f = BookForm(request.POST, user=user)
> if f.is_valid():
> book = f.save(commit=False)
> book.user = user
> book.save()
> messages.add_message(request, messages.INFO, 'book added.')
> return redirect('book_add')
> else:
> f = BookForm(user=user)
>
> return render(request, 'blog/book_add.html', {'f': f})
>
>
> def post_update(request, post_pk):
> user = get_object_or_404(User, id=1)
> book = get_object_or_404(Book, pk=post_pk)
> if request.method == 'POST':
> f = BookForm(request.POST, instance=book, user=user)
> if f.is_valid():
> post = f.save(commit=False)
> post.user = user
> post.save()
> messages.add_message(request, messages.INFO, 'Post added.')
> return redirect('post_update', post.pk)
> else:
> f = BookForm(instance=book, user=user)
>
> return render(request, 'blog/book_update.html', 

Re: Slicing on queryset not working when using .last() after queryset

2018-09-24 Thread Vasili Korol
Okay, this seems to produce TypeError in Django 2.0. See here: 
https://code.djangoproject.com/ticket/22550

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/97fd6cbf-2f63-4e96-9045-1611a3ac9716%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Slicing on queryset not working when using .last() after queryset

2018-09-24 Thread SHIVAM JINDAL
I am facing this on Django 1.9, Python 2.7

On Mon, Sep 24, 2018 at 5:42 PM Vasili Korol  wrote:

> I can confirm this issue on Django 1.11.15 (Python 3.4.3, MySQL 5.5.61).
> Calling 'last()' on a slice produces wrong result:
>
> >>> News.objects.all().order_by('id')[:5].values('id')
> 
>
> >>> News.objects.all().order_by('id')[:5][4].id
> 5
>
> >>> #But calling 'last' gives us wrong id:
> >>> News.objects.all().order_by('id')[:5].last()
> 11
>
>
> понедельник, 24 сентября 2018 г., 13:49:08 UTC+2 пользователь Shivam
> Jindal написал:
>>
>> Hi,
>>
>> I am making a queryset by slicing it to return only first 2 objects but
>> When I am using .last() on this queryset then it is not applying slicing
>>
>> Pharmaceutical.objects.order_by('id').values('id')
>> >>> [{'id': 2L}, {'id': 3L}, {'id': 4L}, {'id': 5L}]
>>
>> >>> Pharmaceutical.objects.order_by('id')[:2].values('id')
>> [{'id': 2L}, {'id': 3L}]
>>
>> >>> Pharmaceutical.objects.order_by('id')[:2].values('id').last()
>> {'id': 5L} # But this should be 3
>>
>> --
>> Thanks,
>>
>> Regards
>> Shivam Jindal
>> +91 8586896112
>>
> --
> You received this message because you are subscribed to the Google Groups
> "Django developers (Contributions to Django itself)" group.
> To unsubscribe from this group and stop receiving emails from it, send an
> email to django-developers+unsubscr...@googlegroups.com.
> To post to this group, send email to django-developers@googlegroups.com.
> Visit this group at https://groups.google.com/group/django-developers.
> To view this discussion on the web visit
> https://groups.google.com/d/msgid/django-developers/d2a29c84-00f8-41e9-85fa-a8bf20985218%40googlegroups.com
> 
> .
> For more options, visit https://groups.google.com/d/optout.
>


-- 
Thanks,

Regards
Shivam jindal
+91 8586896112

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/CAL6wZzndL%3D%2B%2BVXKkjmH6JLGnjLO48fzamWLS_i%3DOE4mcg1OaMw%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: django makemessages management command

2018-09-24 Thread Claude Paroz
Hi Osama,

You can simply do that by including a gettext_noop('your custom string') 
line anywhere in your code (or in a specific file you create for that 
purpose).

Regards,

Claude

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/ca158d8d-e667-46c5-bebe-ca6c76635b29%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Re: Slicing on queryset not working when using .last() after queryset

2018-09-24 Thread Vasili Korol
I can confirm this issue on Django 1.11.15 (Python 3.4.3, MySQL 5.5.61). 
Calling 'last()' on a slice produces wrong result:

>>> News.objects.all().order_by('id')[:5].values('id')


>>> News.objects.all().order_by('id')[:5][4].id
5

>>> #But calling 'last' gives us wrong id:
>>> News.objects.all().order_by('id')[:5].last()
11


понедельник, 24 сентября 2018 г., 13:49:08 UTC+2 пользователь Shivam Jindal 
написал:
>
> Hi,
>
> I am making a queryset by slicing it to return only first 2 objects but 
> When I am using .last() on this queryset then it is not applying slicing
>
> Pharmaceutical.objects.order_by('id').values('id')
> >>> [{'id': 2L}, {'id': 3L}, {'id': 4L}, {'id': 5L}]
>
> >>> Pharmaceutical.objects.order_by('id')[:2].values('id')
> [{'id': 2L}, {'id': 3L}]
>
> >>> Pharmaceutical.objects.order_by('id')[:2].values('id').last()
> {'id': 5L} # But this should be 3
>
> -- 
> Thanks,
>
> Regards
> Shivam Jindal
> +91 8586896112
>

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/d2a29c84-00f8-41e9-85fa-a8bf20985218%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


django makemessages management command

2018-09-24 Thread Osama AbuOmar
About the django *makemessages *management command. I think there should by 
an option to *NOT *let django comment out manually added translations to 
the .po files.
sometimes I need to manually add a translation definition (msgid, msgstr), 
these are not in any of my template or python files. and when I run 
makemessages they get commented out. and this is an issue.
thanks 

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/5e187cc8-4acb-4787-98eb-72ee069ce10a%40googlegroups.com.
For more options, visit https://groups.google.com/d/optout.


Slicing on queryset not working when using .last() after queryset

2018-09-24 Thread SHIVAM JINDAL
Hi,

I am making a queryset by slicing it to return only first 2 objects but
When I am using .last() on this queryset then it is not applying slicing

Pharmaceutical.objects.order_by('id').values('id')
>>> [{'id': 2L}, {'id': 3L}, {'id': 4L}, {'id': 5L}]

>>> Pharmaceutical.objects.order_by('id')[:2].values('id')
[{'id': 2L}, {'id': 3L}]

>>> Pharmaceutical.objects.order_by('id')[:2].values('id').last()
{'id': 5L} # But this should be 3

-- 
Thanks,

Regards
Shivam Jindal
+91 8586896112

-- 
You received this message because you are subscribed to the Google Groups 
"Django developers  (Contributions to Django itself)" group.
To unsubscribe from this group and stop receiving emails from it, send an email 
to django-developers+unsubscr...@googlegroups.com.
To post to this group, send email to django-developers@googlegroups.com.
Visit this group at https://groups.google.com/group/django-developers.
To view this discussion on the web visit 
https://groups.google.com/d/msgid/django-developers/CAL6wZzm92j_aEzjSJim4j5u54fW9EGXEJovy5eCyedbFqzunkA%40mail.gmail.com.
For more options, visit https://groups.google.com/d/optout.


Re: ModelForm unique validation is not done right IMHO.

2018-09-24 Thread Todor Velichkov
One more thing I forgot to add

I would add a clean_book method on the form and use it to check if the user 
> already have a book with that name.
>

You actually can't to this, because this just a simplified example where we 
have two fields only, what if we have a 3rd one and two of the fields are 
visible for the user? Then you will have to use Form.clean, where you will 
basically rewrite the unique check which Django decides to skip. 

On Monday, September 24, 2018 at 11:51:49 AM UTC+3, Todor Velichkov wrote:
>
> Then the form will raise a Validation error saying there is already a book 
>> with that user and that name. Confusing the user.
>>
> What error message are you gonna put instead? Book with that name already 
> exists? This is even more confusing, because its actually allowed to have 
> more books with that name.
> What about Hidden field errors? Aren't they confusing? 
>
> If you think a ModelForm giving guarantee that the save method will work 
>> make sense, the best way to proceed is a third party module.
>>
> Yes, lets keep pretending that ModelForms are just Forms, without Model in 
> their name. Server errors are much better than "Confusing" form errors.
>
>
> Simply do a Book.objects.filter(user=form.user, 
>> name=form.cleaned_data["name"]). exists()
>>
>  Why should I repeat something already implemented? More over, how are you 
> gonna keep this up to date with model unique constrains ? So every time I 
> touch unique_together I should go around all the forms and double check if 
> this wont break anything ?
>
>
> On Monday, September 24, 2018 at 9:09:58 AM UTC+3, ludovic coues wrote:
>>
>> First, that's a discussion for the Django user list, not the Django 
>> developers one.
>>
>> I would add a clean_book method on the form and use it to check if the 
>> user already have a book with that name. For that specific problems, that's 
>> the cleanest solution in my opinion. Simply do a 
>> Book.objects.filter(user=form.user, name=form.cleaned_data["name"]). 
>> exists() and if you get a hit, raise a Validation error. The error will be 
>> associated to the book field.
>>
>> If someone want to write a patch for adding full validation of a 
>> ModelForm, I wish them good luck. You could try a save commit=False but you 
>> will only get an integrity error and a string coming from the database. 
>> Which can be translated. You could check for your unique_together with an 
>> extra request. Then the form will raise a Validation error saying there is 
>> already a book with that user and that name. Confusing the user.
>>
>> If you think a ModelForm giving guarantee that the save method will work 
>> make sense, the best way to proceed is a third party module. Doing so let 
>> you do quick release for development and testing, user will be able try the 
>> module and see if it solves their problems. In my opinion, something 
>> generic won't help when validating unique_together relationship when one of 
>> the fields is not exposed to the user. But I could be wrong.
>>
>> On Sep 24, 2018 07:34, "Protik"  wrote:
>>
>> I am using Django 1.11. Further, adding a new book with user field 
>> disabled results in the following error:
>>
>> [image: Selection_046.png]
>>
>>
>> I have attached the code to reproduce the error.
>>
>>
>> On Monday, September 24, 2018 at 1:59:31 AM UTC+5:30, Todor Velichkov 
>> wrote:
>>>
>>> First thought: What is your Django version? The `disabled` attribute was 
>>> added in Django 1.9.
>>> However by looking at your code (w/o testing anything) after 
>>> `form.is_valid()` you should only call `form.save()`, no need to do 
>>> `commit=False` and manually assigning user, you have already done that in 
>>> the form constructor (by settings initial value + disabled attr).
>>>
>>> On Sunday, September 23, 2018 at 9:25:41 PM UTC+3, Protik wrote:

 Hi, Todor

 I have tested this solution and It looks like it works only when you 
 don't disable the field (i.e the last line in the BookForm's `__init__()` 
 method. My views looks like this:


 def book_add(request):
 user = get_object_or_404(User, id=1)

 if request.method == 'POST':

 f = BookForm(request.POST, user=user)
 if f.is_valid():
 book = f.save(commit=False)
 book.user = user
 book.save()
 messages.add_message(request, messages.INFO, 'book added.')
 return redirect('book_add')
 else:
 f = BookForm(user=user)

 return render(request, 'blog/book_add.html', {'f': f})


 def post_update(request, post_pk):
 user = get_object_or_404(User, id=1)
 book = get_object_or_404(Book, pk=post_pk)
 if request.method == 'POST':
 f = BookForm(request.POST, instance=book, user=user)
 if f.is_valid():
 post = f.save(commit=False)
 post.user = user
   

Re: ModelForm unique validation is not done right IMHO.

2018-09-24 Thread Todor Velichkov

>
> Then the form will raise a Validation error saying there is already a book 
> with that user and that name. Confusing the user.
>
What error message are you gonna put instead? Book with that name already 
exists? This is even more confusing, because its actually allowed to have 
more books with that name.
What about Hidden field errors? Aren't they confusing? 

If you think a ModelForm giving guarantee that the save method will work 
> make sense, the best way to proceed is a third party module.
>
Yes, lets keep pretending that ModelForms are just Forms, without Model in 
their name. Server errors are much better than "Confusing" form errors.


Simply do a Book.objects.filter(user=form.user, 
> name=form.cleaned_data["name"]). exists()
>
 Why should I repeat something already implemented? More over, how are you 
gonna keep this up to date with model unique constrains ? So every time I 
touch unique_together I should go around all the forms and double check if 
this wont break anything ?


On Monday, September 24, 2018 at 9:09:58 AM UTC+3, ludovic coues wrote:
>
> First, that's a discussion for the Django user list, not the Django 
> developers one.
>
> I would add a clean_book method on the form and use it to check if the 
> user already have a book with that name. For that specific problems, that's 
> the cleanest solution in my opinion. Simply do a 
> Book.objects.filter(user=form.user, name=form.cleaned_data["name"]). 
> exists() and if you get a hit, raise a Validation error. The error will be 
> associated to the book field.
>
> If someone want to write a patch for adding full validation of a 
> ModelForm, I wish them good luck. You could try a save commit=False but you 
> will only get an integrity error and a string coming from the database. 
> Which can be translated. You could check for your unique_together with an 
> extra request. Then the form will raise a Validation error saying there is 
> already a book with that user and that name. Confusing the user.
>
> If you think a ModelForm giving guarantee that the save method will work 
> make sense, the best way to proceed is a third party module. Doing so let 
> you do quick release for development and testing, user will be able try the 
> module and see if it solves their problems. In my opinion, something 
> generic won't help when validating unique_together relationship when one of 
> the fields is not exposed to the user. But I could be wrong.
>
> On Sep 24, 2018 07:34, "Protik" > wrote:
>
> I am using Django 1.11. Further, adding a new book with user field 
> disabled results in the following error:
>
> [image: Selection_046.png]
>
>
> I have attached the code to reproduce the error.
>
>
> On Monday, September 24, 2018 at 1:59:31 AM UTC+5:30, Todor Velichkov 
> wrote:
>>
>> First thought: What is your Django version? The `disabled` attribute was 
>> added in Django 1.9.
>> However by looking at your code (w/o testing anything) after 
>> `form.is_valid()` you should only call `form.save()`, no need to do 
>> `commit=False` and manually assigning user, you have already done that in 
>> the form constructor (by settings initial value + disabled attr).
>>
>> On Sunday, September 23, 2018 at 9:25:41 PM UTC+3, Protik wrote:
>>>
>>> Hi, Todor
>>>
>>> I have tested this solution and It looks like it works only when you 
>>> don't disable the field (i.e the last line in the BookForm's `__init__()` 
>>> method. My views looks like this:
>>>
>>>
>>> def book_add(request):
>>> user = get_object_or_404(User, id=1)
>>>
>>> if request.method == 'POST':
>>>
>>> f = BookForm(request.POST, user=user)
>>> if f.is_valid():
>>> book = f.save(commit=False)
>>> book.user = user
>>> book.save()
>>> messages.add_message(request, messages.INFO, 'book added.')
>>> return redirect('book_add')
>>> else:
>>> f = BookForm(user=user)
>>>
>>> return render(request, 'blog/book_add.html', {'f': f})
>>>
>>>
>>> def post_update(request, post_pk):
>>> user = get_object_or_404(User, id=1)
>>> book = get_object_or_404(Book, pk=post_pk)
>>> if request.method == 'POST':
>>> f = BookForm(request.POST, instance=book, user=user)
>>> if f.is_valid():
>>> post = f.save(commit=False)
>>> post.user = user
>>> post.save()
>>> messages.add_message(request, messages.INFO, 'Post added.')
>>> return redirect('post_update', post.pk)
>>> else:
>>> f = BookForm(instance=book, user=user)
>>>
>>> return render(request, 'blog/book_update.html', {'f': f})
>>>
>>>
>>> The code for models and modelform is exactly same as yours.
>>>
>>>
>>> Am I doing something wrong?
>>>
>>>
>>> On Sunday, September 23, 2018 at 9:11:55 PM UTC+5:30, Todor Velichkov 
>>> wrote:

 You can use the `disabled 
 ` 
 attribute on form fields 

Re: ModelForm unique validation is not done right IMHO.

2018-09-24 Thread Todor Velichkov
Protik, just use `self.fields['user'].initial = user.id` instead of just 
`user`. Just tested it and it work fine. 

On Monday, September 24, 2018 at 9:36:19 AM UTC+3, Protik wrote:
>
>
> Book.objects.filter(user=form.user, name=form.cleaned_data["name"]). 
> exists()
>
> This will only work for creating records, not updating.
>
> But what's the issue with the current solution posted by Todor. If you 
> look at the model form it looks like this:
>
> class BookForm(forms.ModelForm):
> class Meta:
>  model = Book
>  fields = ('user', 'name')
>
> def __init__(self, *args, **kwargs):
> user = kwargs.pop('user')
> super(BookForm, self).__init__(*args, **kwargs)
> self.fields['user'].widget = forms.HiddenInput()
> self.fields['user'].initial = user
> self.fields['user'].disabled = True
>
> Logically, It should work. But it is not, so far I have checked this code 
> with django version 1.11 and 2.1. 
>
> What do you think where the problem lies?
>
> On Monday, September 24, 2018 at 11:39:58 AM UTC+5:30, ludovic coues wrote:
>>
>> First, that's a discussion for the Django user list, not the Django 
>> developers one.
>>
>> I would add a clean_book method on the form and use it to check if the 
>> user already have a book with that name. For that specific problems, that's 
>> the cleanest solution in my opinion. Simply do a 
>> Book.objects.filter(user=form.user, name=form.cleaned_data["name"]). 
>> exists() and if you get a hit, raise a Validation error. The error will be 
>> associated to the book field.
>>
>> If someone want to write a patch for adding full validation of a 
>> ModelForm, I wish them good luck. You could try a save commit=False but you 
>> will only get an integrity error and a string coming from the database. 
>> Which can be translated. You could check for your unique_together with an 
>> extra request. Then the form will raise a Validation error saying there is 
>> already a book with that user and that name. Confusing the user.
>>
>> If you think a ModelForm giving guarantee that the save method will work 
>> make sense, the best way to proceed is a third party module. Doing so let 
>> you do quick release for development and testing, user will be able try the 
>> module and see if it solves their problems. In my opinion, something 
>> generic won't help when validating unique_together relationship when one of 
>> the fields is not exposed to the user. But I could be wrong.
>>
>> On Sep 24, 2018 07:34, "Protik"  wrote:
>>
>> I am using Django 1.11. Further, adding a new book with user field 
>> disabled results in the following error:
>>
>> [image: Selection_046.png]
>>
>>
>> I have attached the code to reproduce the error.
>>
>>
>> On Monday, September 24, 2018 at 1:59:31 AM UTC+5:30, Todor Velichkov 
>> wrote:
>>>
>>> First thought: What is your Django version? The `disabled` attribute was 
>>> added in Django 1.9.
>>> However by looking at your code (w/o testing anything) after 
>>> `form.is_valid()` you should only call `form.save()`, no need to do 
>>> `commit=False` and manually assigning user, you have already done that in 
>>> the form constructor (by settings initial value + disabled attr).
>>>
>>> On Sunday, September 23, 2018 at 9:25:41 PM UTC+3, Protik wrote:

 Hi, Todor

 I have tested this solution and It looks like it works only when you 
 don't disable the field (i.e the last line in the BookForm's `__init__()` 
 method. My views looks like this:


 def book_add(request):
 user = get_object_or_404(User, id=1)

 if request.method == 'POST':

 f = BookForm(request.POST, user=user)
 if f.is_valid():
 book = f.save(commit=False)
 book.user = user
 book.save()
 messages.add_message(request, messages.INFO, 'book added.')
 return redirect('book_add')
 else:
 f = BookForm(user=user)

 return render(request, 'blog/book_add.html', {'f': f})


 def post_update(request, post_pk):
 user = get_object_or_404(User, id=1)
 book = get_object_or_404(Book, pk=post_pk)
 if request.method == 'POST':
 f = BookForm(request.POST, instance=book, user=user)
 if f.is_valid():
 post = f.save(commit=False)
 post.user = user
 post.save()
 messages.add_message(request, messages.INFO, 'Post added.')
 return redirect('post_update', post.pk)
 else:
 f = BookForm(instance=book, user=user)

 return render(request, 'blog/book_update.html', {'f': f})


 The code for models and modelform is exactly same as yours.


 Am I doing something wrong?


 On Sunday, September 23, 2018 at 9:11:55 PM UTC+5:30, Todor Velichkov 
 wrote:
>
> You can use the 

Re: ModelForm unique validation is not done right IMHO.

2018-09-24 Thread Protik

Book.objects.filter(user=form.user, name=form.cleaned_data["name"]). exists
()

This will only work for creating records, not updating.

But what's the issue with the current solution posted by Todor. If you look 
at the model form it looks like this:

class BookForm(forms.ModelForm):
class Meta:
 model = Book
 fields = ('user', 'name')

def __init__(self, *args, **kwargs):
user = kwargs.pop('user')
super(BookForm, self).__init__(*args, **kwargs)
self.fields['user'].widget = forms.HiddenInput()
self.fields['user'].initial = user
self.fields['user'].disabled = True

Logically, It should work. But it is not, so far I have checked this code 
with django version 1.11 and 2.1. 

What do you think where the problem lies?

On Monday, September 24, 2018 at 11:39:58 AM UTC+5:30, ludovic coues wrote:
>
> First, that's a discussion for the Django user list, not the Django 
> developers one.
>
> I would add a clean_book method on the form and use it to check if the 
> user already have a book with that name. For that specific problems, that's 
> the cleanest solution in my opinion. Simply do a 
> Book.objects.filter(user=form.user, name=form.cleaned_data["name"]). 
> exists() and if you get a hit, raise a Validation error. The error will be 
> associated to the book field.
>
> If someone want to write a patch for adding full validation of a 
> ModelForm, I wish them good luck. You could try a save commit=False but you 
> will only get an integrity error and a string coming from the database. 
> Which can be translated. You could check for your unique_together with an 
> extra request. Then the form will raise a Validation error saying there is 
> already a book with that user and that name. Confusing the user.
>
> If you think a ModelForm giving guarantee that the save method will work 
> make sense, the best way to proceed is a third party module. Doing so let 
> you do quick release for development and testing, user will be able try the 
> module and see if it solves their problems. In my opinion, something 
> generic won't help when validating unique_together relationship when one of 
> the fields is not exposed to the user. But I could be wrong.
>
> On Sep 24, 2018 07:34, "Protik" > wrote:
>
> I am using Django 1.11. Further, adding a new book with user field 
> disabled results in the following error:
>
> [image: Selection_046.png]
>
>
> I have attached the code to reproduce the error.
>
>
> On Monday, September 24, 2018 at 1:59:31 AM UTC+5:30, Todor Velichkov 
> wrote:
>>
>> First thought: What is your Django version? The `disabled` attribute was 
>> added in Django 1.9.
>> However by looking at your code (w/o testing anything) after 
>> `form.is_valid()` you should only call `form.save()`, no need to do 
>> `commit=False` and manually assigning user, you have already done that in 
>> the form constructor (by settings initial value + disabled attr).
>>
>> On Sunday, September 23, 2018 at 9:25:41 PM UTC+3, Protik wrote:
>>>
>>> Hi, Todor
>>>
>>> I have tested this solution and It looks like it works only when you 
>>> don't disable the field (i.e the last line in the BookForm's `__init__()` 
>>> method. My views looks like this:
>>>
>>>
>>> def book_add(request):
>>> user = get_object_or_404(User, id=1)
>>>
>>> if request.method == 'POST':
>>>
>>> f = BookForm(request.POST, user=user)
>>> if f.is_valid():
>>> book = f.save(commit=False)
>>> book.user = user
>>> book.save()
>>> messages.add_message(request, messages.INFO, 'book added.')
>>> return redirect('book_add')
>>> else:
>>> f = BookForm(user=user)
>>>
>>> return render(request, 'blog/book_add.html', {'f': f})
>>>
>>>
>>> def post_update(request, post_pk):
>>> user = get_object_or_404(User, id=1)
>>> book = get_object_or_404(Book, pk=post_pk)
>>> if request.method == 'POST':
>>> f = BookForm(request.POST, instance=book, user=user)
>>> if f.is_valid():
>>> post = f.save(commit=False)
>>> post.user = user
>>> post.save()
>>> messages.add_message(request, messages.INFO, 'Post added.')
>>> return redirect('post_update', post.pk)
>>> else:
>>> f = BookForm(instance=book, user=user)
>>>
>>> return render(request, 'blog/book_update.html', {'f': f})
>>>
>>>
>>> The code for models and modelform is exactly same as yours.
>>>
>>>
>>> Am I doing something wrong?
>>>
>>>
>>> On Sunday, September 23, 2018 at 9:11:55 PM UTC+5:30, Todor Velichkov 
>>> wrote:

 You can use the `disabled 
 ` 
 attribute on form fields with a combination of HiddenInput 
 

 Using the Book example from the first comment it will look like this:
   
 class 

Re: ModelForm unique validation is not done right IMHO.

2018-09-24 Thread ludovic coues
First, that's a discussion for the Django user list, not the Django
developers one.

I would add a clean_book method on the form and use it to check if the user
already have a book with that name. For that specific problems, that's the
cleanest solution in my opinion. Simply do a
Book.objects.filter(user=form.user, name=form.cleaned_data["name"]).
exists() and if you get a hit, raise a Validation error. The error will be
associated to the book field.

If someone want to write a patch for adding full validation of a ModelForm,
I wish them good luck. You could try a save commit=False but you will only
get an integrity error and a string coming from the database. Which can be
translated. You could check for your unique_together with an extra request.
Then the form will raise a Validation error saying there is already a book
with that user and that name. Confusing the user.

If you think a ModelForm giving guarantee that the save method will work
make sense, the best way to proceed is a third party module. Doing so let
you do quick release for development and testing, user will be able try the
module and see if it solves their problems. In my opinion, something
generic won't help when validating unique_together relationship when one of
the fields is not exposed to the user. But I could be wrong.

On Sep 24, 2018 07:34, "Protik"  wrote:

I am using Django 1.11. Further, adding a new book with user field disabled
results in the following error:

[image: Selection_046.png]


I have attached the code to reproduce the error.


On Monday, September 24, 2018 at 1:59:31 AM UTC+5:30, Todor Velichkov wrote:
>
> First thought: What is your Django version? The `disabled` attribute was
> added in Django 1.9.
> However by looking at your code (w/o testing anything) after
> `form.is_valid()` you should only call `form.save()`, no need to do
> `commit=False` and manually assigning user, you have already done that in
> the form constructor (by settings initial value + disabled attr).
>
> On Sunday, September 23, 2018 at 9:25:41 PM UTC+3, Protik wrote:
>>
>> Hi, Todor
>>
>> I have tested this solution and It looks like it works only when you
>> don't disable the field (i.e the last line in the BookForm's `__init__()`
>> method. My views looks like this:
>>
>>
>> def book_add(request):
>> user = get_object_or_404(User, id=1)
>>
>> if request.method == 'POST':
>>
>> f = BookForm(request.POST, user=user)
>> if f.is_valid():
>> book = f.save(commit=False)
>> book.user = user
>> book.save()
>> messages.add_message(request, messages.INFO, 'book added.')
>> return redirect('book_add')
>> else:
>> f = BookForm(user=user)
>>
>> return render(request, 'blog/book_add.html', {'f': f})
>>
>>
>> def post_update(request, post_pk):
>> user = get_object_or_404(User, id=1)
>> book = get_object_or_404(Book, pk=post_pk)
>> if request.method == 'POST':
>> f = BookForm(request.POST, instance=book, user=user)
>> if f.is_valid():
>> post = f.save(commit=False)
>> post.user = user
>> post.save()
>> messages.add_message(request, messages.INFO, 'Post added.')
>> return redirect('post_update', post.pk)
>> else:
>> f = BookForm(instance=book, user=user)
>>
>> return render(request, 'blog/book_update.html', {'f': f})
>>
>>
>> The code for models and modelform is exactly same as yours.
>>
>>
>> Am I doing something wrong?
>>
>>
>> On Sunday, September 23, 2018 at 9:11:55 PM UTC+5:30, Todor Velichkov
>> wrote:
>>>
>>> You can use the `disabled
>>> `
>>> attribute on form fields with a combination of HiddenInput
>>> 
>>>
>>> Using the Book example from the first comment it will look like this:
>>>
>>> class BookForm(forms.ModelForm):
>>> class Meta:
>>> model = Book
>>> fields = ('user', 'name')
>>>
>>> def __init__(self, *args, **kwargs):
>>> user = kwargs.pop('user')
>>> super(BookForm, self).__init__(*args, **kwargs)
>>> self.fields['user'].widget = forms.HiddenInput()
>>> self.fields['user'].initial = user
>>> self.fields['user'].disabled = True
>>>
>>>
>>> First we hide the the user field because we dont want the user to see
>>> it, and at the same time keeping it inside form fields we wont prevent the
>>> unique_together validation.
>>> Second - we disable the field and programmatically set initial value to
>>> be used during form validation
>>>
>>> On Sunday, September 23, 2018 at 4:57:15 PM UTC+3, Protik wrote:

 Hi  Todor

 I am experiencing the same problem. Can you please post the
 possible solution?

 On Tuesday, October 10, 2017 at 8:26:32 AM UTC+5:30, Todor Velichkov
 wrote:
>
> It does? Can you give me a