How To Restrict Who Can Make Blog Posts - Django Blog #17

  Рет қаралды 18,262

Codemy.com

Codemy.com

Күн бұрын

Пікірлер: 150
@Codemycom
@Codemycom 4 жыл бұрын
▶️ Watch Entire Django Blog Playlist ✅ Subscribe To My KZbin Channel: bit.ly/3bWN6wj bit.ly/2IGzvOR ▶️ See More At: ✅ Join My Facebook Group: Codemy.com bit.ly/2GFmOBz ▶️ Learn to Code at Codemy.com ✅ Buy a Codemy T-Shirt! Take $30 off with coupon code: youtube1 bit.ly/2VC9WUN
@brinaskoda2141
@brinaskoda2141 4 жыл бұрын
For anyone having this problem: (Hidden field author) Select a valid choice. ... What worked for me was in JS code to change username to id. So: var name = "{{ user.username }}"; into ----> var name = "{{user.id}}";
@annagrigoreva7230
@annagrigoreva7230 4 жыл бұрын
OMG thank you!
@wowoz8048
@wowoz8048 3 жыл бұрын
Many thx
@viditsinghal5796
@viditsinghal5796 3 жыл бұрын
thanks a lot
@carfan441
@carfan441 3 жыл бұрын
hey, Thnx a lot
@johannesperez9548
@johannesperez9548 2 жыл бұрын
thank you so much!
@spreadhysteria3650
@spreadhysteria3650 4 жыл бұрын
to solve this problem without using JavaScript, remove author from fields and widgets in the forms.py and add this code to views.py class AddPostView(CreateView): model = Post form_class = PostForm template_name = 'add_post.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form)
@SajjadHematiNourani
@SajjadHematiNourani 2 жыл бұрын
genius. excellent job
@fatihsinankara
@fatihsinankara 2 жыл бұрын
I am grateful, thanks
@rogueDukakis
@rogueDukakis Жыл бұрын
Thanks so much for this! Not opposed to the JS solution but really like maintaining the django/python theme.
@diegooli9253
@diegooli9253 11 ай бұрын
@@rogueDukakis "I also don't understand why people like to look for alternative solutions when there's already something more practical. It's a positive criticism, let's go for the simplest option, folks."
@hamdablife7782
@hamdablife7782 9 ай бұрын
Legend
@spideyparker8396
@spideyparker8396 4 жыл бұрын
Hello, thanks for all your videos, I really learn a lot ! For the solution with Django we can add a function after the validation of the form in the Add view and get rid of the author in the form :) class AddPostView(LoginRequiredMixin, CreateView): model = Post form_class = PostForm template_name = 'create_post.html' def form_valid(self, form): form.instance.author = self.request.user return super().form_valid(form)
@thenextlevel1228
@thenextlevel1228 4 жыл бұрын
I don't get it
@coolrezaul
@coolrezaul 4 жыл бұрын
Thank you its working
@kennywolf4380
@kennywolf4380 2 жыл бұрын
bro you saved my life
@Cecileeeeeeeeeeeeeee
@Cecileeeeeeeeeeeeeee Жыл бұрын
Hey ! Thank you of all your videos, Django finally made sense :D Thaaaaaank you soooo muuuuuuch !
@Codemycom
@Codemycom Жыл бұрын
Very welcome!
@jhoanmartinezsilva2609
@jhoanmartinezsilva2609 4 жыл бұрын
Insane playlist my fella :O, huge thanks
@Codemycom
@Codemycom 4 жыл бұрын
glad you like it!
@deki90to
@deki90to 4 жыл бұрын
You are so easy to follow! Keep it up
@Codemycom
@Codemycom 4 жыл бұрын
Thanks!
@madalinantonoiu9714
@madalinantonoiu9714 4 жыл бұрын
You can actually see what is in the value, look below at script code, says "3". If a logged in staff member looks at page source, grabs the CSRF token, goes to POSTMAN and recreates a POST with the valid CSRF but changes the author to be somebody else, wouldn't that be possible with the current way of doing things? How to prevent that from happening?
@Codemycom
@Codemycom 4 жыл бұрын
No
@LeonJoseph-j2d
@LeonJoseph-j2d 5 ай бұрын
csrf token are session based so its different for each device/browser.
@ange-dev854
@ange-dev854 2 жыл бұрын
thanks sir !! but i've a question how must i do to take all elements which have the same author ?please help me
@islassquad9508
@islassquad9508 4 жыл бұрын
Great ways to do it instead having to write a page full of code.. Would be great if you could do tutorial on how to add likes, vote feature for posts. That’s would be great.
@Codemycom
@Codemycom 4 жыл бұрын
Might do that
@randyk7238
@randyk7238 4 жыл бұрын
Hi John I got an error "'Select a valid choice. That choice is not one of the available choices." while saving a post
@Codemycom
@Codemycom 4 жыл бұрын
Weird
@randyk7238
@randyk7238 4 жыл бұрын
@@Codemycom in admin panel I still have a select option for the author. so its causing problem "'Select a valid choice. That choice is not one of the available choices." while saving.
@sandeep-rai07
@sandeep-rai07 4 жыл бұрын
I'm also getting same error
@lordfurion
@lordfurion 4 жыл бұрын
this is still vulnerable to people modifying the textbox by simply going through the html and modifying the number. I've created a function in the AddPostView class that stops this from working: def post(self, request, **kwargs): request.POST = request.POST.copy() request.POST['author'] = request.user.id return super(AddPostView, self).post(request, **kwargs) if someone tries to change the blog post author value this function will replace that value with the authenticated users id
@alessiomusic96
@alessiomusic96 4 жыл бұрын
I also found this vulnerability!!! The playlist is very good and helpful but this should be pointed out in the video!!!
@sharbin1181
@sharbin1181 4 жыл бұрын
Thank you!!! This worked perfectly!
@antonyjackson1301
@antonyjackson1301 3 жыл бұрын
Hi Lord, thanks for your support this really worked for me. i have added this code into my views.py file and i used the same code for forms.py that was used in this video and i have skipped the Js part and now i am not getting any error. Can you please guide me was this right or need more to do in this. Appreciate you in advance
@augustschleich5057
@augustschleich5057 3 жыл бұрын
Nice One John! Yea much easier with JavaScript! Great use of code right there!
@Codemycom
@Codemycom 3 жыл бұрын
Thanks!
@jhoanmartinezsilva2609
@jhoanmartinezsilva2609 4 жыл бұрын
How can auto select the foreign key if instead user model is another random model
@hosseingharsi4497
@hosseingharsi4497 Жыл бұрын
now in login with another user and when i make new post and go in weblog page didn't who user name in Created By : ????? how can i fix this ?
@eshikagupta6616
@eshikagupta6616 2 жыл бұрын
But instead of hiding the author text field I want to make it a read only field with the author's name in it instead of the author's id. How can I achieve that because when I'm using user.username it's showing a 'Select a valid choice' error?
@omarmughrabi1419
@omarmughrabi1419 2 жыл бұрын
In order to have have a field that shows the author name there are many ways or walk-around: 1- You can simply add an html tag in to ur add-post.html file, place it in your code (maybe above the button tag) then set the {{user.name}} directly to it. it can be a text input with "readonly" = "True" attribute. This will give the illusion of using the same form :P Author 2- Keep the field as drop-down option, in order to have value and text for your selection as input field cannot have both. Then using JS set a pre-selected value for the field with the user id's, and disable the selection update. You can do it by: a- On forms.py file keep the author field as "form.select" and pass the following attributes to prevent update 'author': forms.Select(choices=size_list, attrs={'id':'creator', 'style': 'pointer-events: none;','onclick':'return false;', 'onkeydown':'return false;'}), b- On the javascript tag set the user by his id as the selection option var myId = "{{ user.id}}"; document.querySelector('#creator').value = myId ; I think option 2 is really cool but not for this case as on your html source code the list of all your authors will be populated on your html. Having many users will slow down your page and expose you user's data. Though it might be really useful in other cases, for example if you have "add post" per each category and you want to the category to be pre-selected and not being changeable to keep each post in its right section. Hope this is useful for what you looking for
@charlottewood9538
@charlottewood9538 4 жыл бұрын
I cannot hide this field nor make it a textinput as long as it is a foreignkey in my models. the only way to get rid of the dropdown is to change the model to a charfield. did i miss this in the instructions somewhere? again, python3.
@Codemycom
@Codemycom 4 жыл бұрын
I think you're mistaken
@mohammadhyari142
@mohammadhyari142 4 жыл бұрын
same problem here, if you found a solution let me know please
@mohammadhyari142
@mohammadhyari142 4 жыл бұрын
i also had an issue with the category field
@mohammadhyari142
@mohammadhyari142 4 жыл бұрын
i finally found the solution! it was an indentation error! the widgets should be inside the meta class
@greetingsgentlemen.8179
@greetingsgentlemen.8179 4 жыл бұрын
It keeps giving me a value = True, How can i get rid of that? I know this because in the page source it shows value = true and no matter what i cant get rid of it.
@greetingsgentlemen.8179
@greetingsgentlemen.8179 4 жыл бұрын
Never Mind, i had set default = true in the models.py 🤦‍♂️
@DjangoUnhinged
@DjangoUnhinged 4 жыл бұрын
If we are only displaying the author as an FYI on the form. Is there a point in displaying it at all? Would it not make sense to just not display the author field at all?
@Codemycom
@Codemycom 4 жыл бұрын
uh, there's no reason to do any of this...we're doing it all to learn.
@johannesperez9548
@johannesperez9548 2 жыл бұрын
great tutorial!
@Codemycom
@Codemycom 2 жыл бұрын
Thanks!
@umutercinbas2764
@umutercinbas2764 2 жыл бұрын
I think better solution would be overriding 'form_valid' function of generic view: def form_valid(self, form): post = form.save(commit=False) post.author_id = self.request.user.id post.save() return redirect(reverse_lazy('...', args=[...]))
@derekkroeker4582
@derekkroeker4582 3 жыл бұрын
When using slugify on the category, then if you have a category with the name "Django" it will go to "django", so you need to manually correct it to "Django", how can you solve this issue?
@derekkroeker4582
@derekkroeker4582 3 жыл бұрын
I have tried deleting slugify, it's the solution, but why are you using slugify?
@maxmay3364
@maxmay3364 4 жыл бұрын
Hello, thanks for all the help with this tutorial so far! I have an issue I cant find an answer to: whenever I make a post, i get an error saying NoReverseMatch, even though the post appears on the homeview after hitting the back button on the error page. please help!
@Codemycom
@Codemycom 4 жыл бұрын
Check your code for typos vs the video
@euriperez9586
@euriperez9586 4 жыл бұрын
Hello jhon, how can we avoid users to not change the value manually?, since you can do it if you know little html by removing the hidden type?
@Codemycom
@Codemycom 4 жыл бұрын
How would they know to even look?
@euriperez9586
@euriperez9586 4 жыл бұрын
@@Codemycom Using inspect tool you can find this: value="3" where value is supposed to be the user.id, so if you change it for example to value="1" that do the thrick
@danieldiaz855
@danieldiaz855 4 жыл бұрын
@@euriperez9586 I'm Totally Agree, Forums should be managed entirely by Django
@a2cfrancisfortes137
@a2cfrancisfortes137 3 жыл бұрын
hello you blog is so awesom i owe you.. but one thing how can users display the only data that they have entered
@sandeep-rai07
@sandeep-rai07 4 жыл бұрын
I'm getting below error : Hidden field author select a valid choice.That choice is not one of the available choice
@randhirgupta9518
@randhirgupta9518 4 жыл бұрын
use id in place of name
@thenextlevel1228
@thenextlevel1228 4 жыл бұрын
I also got the same error. What did you do to fix it?
@sandeep-rai07
@sandeep-rai07 4 жыл бұрын
@@thenextlevel1228 i have developed this app after watcing this video series . www.beginnerspython.com/blog
@gkulk007
@gkulk007 4 жыл бұрын
Hello Sir, Facing the issue mentioned below (Hidden field author) Select a valid choice. That choice is not one of the available choices. plz help
@Codemycom
@Codemycom 4 жыл бұрын
Check your code for typos...
@gkulk007
@gkulk007 4 жыл бұрын
@@Codemycom No Typo, The value is also correctly rendered by js and shown in the box but after clicking on submit the error still remains.
@gkulk007
@gkulk007 4 жыл бұрын
@@Codemycom I found out the way sir, Thanks for help
@sebastiannin655
@sebastiannin655 4 жыл бұрын
@@gkulk007 How did you fix it??
@zubin1677
@zubin1677 4 жыл бұрын
@@sebastiannin655 change the username field back to id in the var name field
@freekeys
@freekeys 4 жыл бұрын
Sir this should be in views.py like,🤔 If post_form.is_valid(): post=post_form.save(commit=False) post.author = request.user post.save()
@leo-sona
@leo-sona 4 жыл бұрын
This worked for me using author as ForeignKey and CBV AddPostView : def form_valid(self, form): form.instance.author = self.request.user return super(AddPostView, self).form_valid(form)
@cnslpsbly
@cnslpsbly 4 жыл бұрын
@@leo-sona this solution worked for me, and saves the issue of hijacking the html.
@youssefelotmani4206
@youssefelotmani4206 4 жыл бұрын
pls how can i integrate it in this example: class InvoiceCreate(CreateView): form_class = InvoiceForm model = Invoice template_name = "sales/invoice_form.html" def get_success_url(self): return reverse_lazy('invoice_details', kwargs={'pk' : self.object.pk}) def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) formset = InvoiceItemFormSet() products = list(Product.objects.values()) return self.render_to_response( self.get_context_data(form=form,formset=formset, products=products)) def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) formset = InvoiceItemFormSet(self.request.POST) if (form.is_valid() and formset.is_valid()): return self.form_valid(form, formset) else: return self.form_invalid(form, formset) def form_valid(self, form, formset): self.object = form.save() formset.instance = self.object formset.save() try: addmore = self.request.GET["addmore"] if addmore == "True": return redirect("update_invoice", pk=self.object.id) except Exception as e: pass return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form, formset): return self.render_to_response(self.get_context_data(form=form, formset=formset))
@youssefelotmani4206
@youssefelotmani4206 4 жыл бұрын
@@leo-sona pls how can i integrate it in this example: class InvoiceCreate(CreateView): form_class = InvoiceForm model = Invoice template_name = "sales/invoice_form.html" def get_success_url(self): return reverse_lazy('invoice_details', kwargs={'pk' : self.object.pk}) def get(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) formset = InvoiceItemFormSet() products = list(Product.objects.values()) return self.render_to_response( self.get_context_data(form=form,formset=formset, products=products)) def post(self, request, *args, **kwargs): self.object = None form_class = self.get_form_class() form = self.get_form(form_class) formset = InvoiceItemFormSet(self.request.POST) if (form.is_valid() and formset.is_valid()): return self.form_valid(form, formset) else: return self.form_invalid(form, formset) def form_valid(self, form, formset): self.object = form.save() formset.instance = self.object formset.save() try: addmore = self.request.GET["addmore"] if addmore == "True": return redirect("update_invoice", pk=self.object.id) except Exception as e: pass return HttpResponseRedirect(self.get_success_url()) def form_invalid(self, form, formset): return self.render_to_response(self.get_context_data(form=form, formset=formset))
@tvrtkokaurinovic7370
@tvrtkokaurinovic7370 2 жыл бұрын
this gives me an error - Cannot assign "2": "Post.profile" must be a "Profile" instance. cana you help please?
@misovnick
@misovnick 2 жыл бұрын
Hi guys, I have noticed that this function is not working anymore after I applied John's solution def get_absolute_url(self): return reverse('article-detail', args=(str(self.id))) I am getting this error: Reverse for 'article-detail' with arguments '('2', '0')' not found. 1 pattern(s) tried: ['article/(?P[0-9]+)\\Z'] any idea why?
@misovnick
@misovnick 2 жыл бұрын
It looks like it has nothing to do with the applied function. I am getting this error for all the articles with IDs 10 and above
@jamwithtina29
@jamwithtina29 4 жыл бұрын
"Select a valid choice. That choice is not one of the available choices." Because we change Select to TextInput, it shows error like that. How? Please help
@Codemycom
@Codemycom 4 жыл бұрын
Sorry, don't know what you did or how to fix it.
@jamwithtina29
@jamwithtina29 4 жыл бұрын
@@Codemycom I think when we changed into textinput they become a string, not object of Users. Meanwhile in select they acted as object of User
@Andremzsptm
@Andremzsptm 3 жыл бұрын
I used django template tags on this: {% if user.is_authenticated %} {% if perms.blog.add_post %} i've also checked for change_post and del_post on the other pages
@СвятославЛитвин-л9й
@СвятославЛитвин-л9й 3 жыл бұрын
I also thought about it and tried to do it myself and I just with forms.py took the field to select the author and the author was selected automatically relative to the current author I don't know if it's right but it works
@Codemycom
@Codemycom 3 жыл бұрын
It's always right if it works ;-)
@sairamsr7131
@sairamsr7131 3 жыл бұрын
hey shift can you please explain me how to do that are help with source code
@СвятославЛитвин-л9й
@СвятославЛитвин-л9й 3 жыл бұрын
@@sairamsr7131 I am replace fields "author" in "forms.py" . And when we add the post, fields of athor does not appear, but in html we show the author and django will show automatically author (sorry for my english..)
@matheuslisboa8059
@matheuslisboa8059 3 жыл бұрын
Nice tip!!!
@Codemycom
@Codemycom 3 жыл бұрын
Thanks!
@mohammadhyari142
@mohammadhyari142 4 жыл бұрын
why the author stays multiple choice even if i make it 'author': forms.TextInput(attrs={'class':'form-control'}),
@mohammadhyari142
@mohammadhyari142 4 жыл бұрын
i finally found the solution! it was an indentation error! the widgets should be inside the meta class
@mhood82
@mhood82 3 жыл бұрын
@@mohammadhyari142 Thank you for sharing! Had a lot of problems earlier on because my widgets weren't indented properly.
@heroCode20
@heroCode20 5 ай бұрын
❤❤thank you
@Codemycom
@Codemycom 5 ай бұрын
welcome
@hariharanbalasubramanianpr4243
@hariharanbalasubramanianpr4243 4 жыл бұрын
If anyone wants only the admin( superuser or staff ) to add post, categories and other stuffs, they can make use this condition {% if user.is_authenticated %} {% if user.is_staff %} Add Post Add Category {% endif %} {% else %} // html statement {% endif %}
@AngelusPax
@AngelusPax 2 жыл бұрын
Thanks, you safe me!
@007rahulb
@007rahulb 4 жыл бұрын
Sir, can You please make some videos on JavaScript? I think no-one can teach me coding better than you. Really appreciate your work sir. Please give it a thought.
@Codemycom
@Codemycom 4 жыл бұрын
I have a course on Javascript called "Javascript For Everyone" at codemy and udemy.
@007rahulb
@007rahulb 4 жыл бұрын
@@Codemycom Thank You sir, badly needed that. :) Can't thanku enough for your work.
@f.christaintanghanwaye3113
@f.christaintanghanwaye3113 4 жыл бұрын
Very nice
@Codemycom
@Codemycom 4 жыл бұрын
Thanks
@wiki-infodevelopment3369
@wiki-infodevelopment3369 4 жыл бұрын
Hi Mr. could you make a tutorial that show: Group of Users: (Admin, Elder, Smail, Bob….) Group of Categories: (sport, coding, ….) and what if every user is allowed to post in one specified cotegorie for example, Elder is allowed to post in sport only. And Smail post in coding only. And Bob can’t post in coding but he can read.
@Codemycom
@Codemycom 4 жыл бұрын
Sort of doubt I'll do that.
@redmibk9724
@redmibk9724 4 жыл бұрын
Add form widgets attr readonly :readonly Then set name in js script to user.username
@randhirgupta9518
@randhirgupta9518 4 жыл бұрын
Thanks man
@Codemycom
@Codemycom 4 жыл бұрын
You're welcome
@shawnbeans7389
@shawnbeans7389 4 жыл бұрын
Cool.
@deki90to
@deki90to 4 жыл бұрын
Btw, it would be great if you show us, how we can upload photos
@Codemycom
@Codemycom 4 жыл бұрын
Will likely do that
@Morimove
@Morimove Жыл бұрын
i used a differenct method wihout js
@kerryliu4979
@kerryliu4979 4 жыл бұрын
Kerry LIU 1 second ago Hi, is it possible for you to show us how to view every user's own post on the separate page
@Codemycom
@Codemycom 4 жыл бұрын
Sure.
@papan101
@papan101 4 жыл бұрын
Why it's showing this...? (Hidden field author) Select a valid choice. That choice is not one of the available choices.
@brinaskoda2141
@brinaskoda2141 4 жыл бұрын
What worked for me was in JS code to change username to id. So: var name = "{{ user.username }}"; into ----> var name = "{{user.id}}";
@papan101
@papan101 4 жыл бұрын
@@brinaskoda2141 Thanks for the reply...I got that earlier 😄
@plusk343
@plusk343 4 жыл бұрын
make a video on the backend and frontend technologies used to make codemy.com or johnelder.org
@Codemycom
@Codemycom 4 жыл бұрын
codemy is a wordpress site and johnelder.com is a simple html css site
@arjavsethics4339
@arjavsethics4339 3 жыл бұрын
NoReverseMatch at /add_post/ helpppppp
@kelvinmacharia3715
@kelvinmacharia3715 Жыл бұрын
So bob makes a post but it is owned by admin🤣, the admin get all the credit. This episode is about protecting bob and make sure he gets all the credit.
@Codemycom
@Codemycom Жыл бұрын
No, you misunderstand
@Master-ls2op
@Master-ls2op 3 жыл бұрын
and the new version of Django has blocked this for security reasons....
@Codemycom
@Codemycom 3 жыл бұрын
No, it hasn't...you are mistaken.
@thenextlevel1228
@thenextlevel1228 4 жыл бұрын
I get this error (Hidden field author) Select a valid choice. That choice is not one of the available choices. I posted the question on stackoverflow: stackoverflow.com/questions/64926263/hidden-field-author-this-field-is-required
@sandeep-rai07
@sandeep-rai07 4 жыл бұрын
User.id in your js function -- add_post.html
@Kennerdoll
@Kennerdoll Жыл бұрын
@@sandeep-rai07 var name = '{{ user.id }}' document.getElementById("client_id").value = name; still getting the same error
@arjavsethics4339
@arjavsethics4339 3 жыл бұрын
source code
@Codemycom
@Codemycom 3 жыл бұрын
github.com/flatplanet/djangoblog
@thenextlevel1228
@thenextlevel1228 4 жыл бұрын
If you only want superusers to post you can use this {% if user.is_superuser %}
Create Blog Like Button - Django Blog #18
19:35
Codemy.com
Рет қаралды 54 М.
How To Add Fields To Registration Form - Django Blog #20
14:37
Codemy.com
Рет қаралды 25 М.
BAYGUYSTAN | 1 СЕРИЯ | bayGUYS
36:55
bayGUYS
Рет қаралды 1,9 МЛН
coco在求救? #小丑 #天使 #shorts
00:29
好人小丑
Рет қаралды 120 МЛН
IL'HAN - Qalqam | Official Music Video
03:17
Ilhan Ihsanov
Рет қаралды 700 М.
Writing Code That Runs FAST on a GPU
15:32
Low Level
Рет қаралды 584 М.
How To Create an Unlike Blog Button - Django Blog #19
11:41
Codemy.com
Рет қаралды 17 М.
I Spent 100 Hours Inside The Pyramids!
21:43
MrBeast
Рет қаралды 30 МЛН
40 APIs Every Developer Should Use (in 12 minutes)
12:23
Coding with Lewis
Рет қаралды 412 М.
Creating Blog User Logins With Authentication - Django Blog #9
19:14
Python Logging: How to Write Logs Like a Pro!
11:02
ArjanCodes
Рет қаралды 190 М.
Blog Category Pages - Django Blog #13
16:13
Codemy.com
Рет қаралды 29 М.
Django & HTMX - Dynamic Form Creation and Submission
24:36
BugBytes
Рет қаралды 33 М.
BAYGUYSTAN | 1 СЕРИЯ | bayGUYS
36:55
bayGUYS
Рет қаралды 1,9 МЛН