Django Tutorial #27 - Foreign Keys

แชร์
ฝัง
  • เผยแพร่เมื่อ 24 ส.ค. 2024
  • Hey gang, in this Django tutorial I'll explain the concept of foreign keys, which allow us to associate one model with another. In our example, we'll associate an article with a user.
    DONATE :) - www.paypal.me/...
    ----- COURSE LINKS:
    + Python tutorials - goo.gl/xD2AvX
    + Course files - github.com/iam...
    + Django docs - docs.djangopro...
    + Atom editor - atom.io/a
    + CMDER - cmder.net/
    ======== Other Tutorials =========
    ----- NODE.JS TUTORIALS
    • Node JS Tutorial for B...
    ----- MONGODB TUTORIALS
    • MongoDB Tutorial for B...
    ----- SUBSCRIBE TO CHANNEL - / @netninja
    ======== Social Links ==========
    Twitter - @TheNetNinja - / thenetninjauk
    Patreon - / thenetninja

ความคิดเห็น • 94

  • @toctoc4964
    @toctoc4964 5 หลายเดือนก่อน +1

    Truly thank you, 2024 and this is still the most useful Django video series I've seen

  • @wisamkhalid5663
    @wisamkhalid5663 6 ปีที่แล้ว +53

    Thanks a lot ..another great video .....just a quick hint for others...in django2 this will give an error(Foreignkey requires 2 arguments not 1 as django 1.9 used to) . just edit the author field line to: author = models.ForeignKey(User,on_delete=models.CASCADE,default=None) or . author = models.ForeignKey(User,on_delete=models.PROTECT,default=None)

    • @DenizBazan
      @DenizBazan 6 ปีที่แล้ว +1

      thanks for hint but what is actualy on_delete=models.CASCADE

    • @wisamkhalid5663
      @wisamkhalid5663 6 ปีที่แล้ว +21

      CASCADE means when the referenced object is deleted(User in this case), also delete the objects that have references to it (Articles in this case). because each user has articles that he/she created, so if this user doesn't exist anymore then for sure there should not be articles that belong to this user .
      remember this is a Foreign key so it is related to a primary key in another table (this is something more related to Database). I hope this will help..thanks

    • @anshuljaiswal1998
      @anshuljaiswal1998 6 ปีที่แล้ว +2

      I found this helpful -
      stackoverflow.com/questions/38388423/what-does-on-delete-do-on-django-models

    • @michaelkarithu4546
      @michaelkarithu4546 6 ปีที่แล้ว +1

      Thanks

    • @majorrooster1357
      @majorrooster1357 6 ปีที่แล้ว +1

      Thanks, dude

  • @jimmyjimmy64
    @jimmyjimmy64 6 ปีที่แล้ว +62

    When I makemigrations, I get this error in cmd - TypeError: __init__() missing 1 required positional argument: 'on_delete'. This is an issue if you have django 2.0 installed.
    Resolution: pass the following perameters for author as on_delete is a required perameter in 2.0 ---- author = models.ForeignKey(User, on_delete=models.CASCADE, default=None)

    • @haripalful
      @haripalful 6 ปีที่แล้ว +2

      thanks, I had the same error

    • @NiralShakya
      @NiralShakya 5 ปีที่แล้ว

      thanks it was helpful too

    • @Commonaadmi768
      @Commonaadmi768 5 ปีที่แล้ว

      One year but no solution to this problem??

    • @matthewamstutz8889
      @matthewamstutz8889 5 ปีที่แล้ว +1

      @@Commonaadmi768 He says how to resolve it.... " Resolution: pass the following perameters for author as on_delete is a required perameter in 2.0 ---- author = models.ForeignKey(User, on_delete=models.CASCADE, default=None)" ..... But to figure out a problem we need ALOT more information. Realize how many connections there are just to make a view. right now my form isn't posting to my page for some reason and research is failing me so I have to read the docs and attempt to teach myself exactly how everything works to find the error.

    • @Vayvess
      @Vayvess 5 ปีที่แล้ว +1

      thanks a lot

  • @tasnimzia4499
    @tasnimzia4499 4 ปีที่แล้ว +5

    For django 3.0, use this:
    author = models.ForeignKey(User, on_delete=models.CASCADE, default=None)

  • @jdevcast6527
    @jdevcast6527 6 ปีที่แล้ว +5

    Thanks so much for this series. I have learned a ton, and it has been really interesting. Plus, your explanations are really clear, and so it is easy to follow. I will recommend it to friends and colleagues. I look forward to the next one.

  • @givansot4581
    @givansot4581 2 ปีที่แล้ว +2

    I love this tutorial. It has helped me a lot in 2022.....

  • @dlshapiro
    @dlshapiro 3 ปีที่แล้ว

    Thank you! Spent hours trying to figure out how to pass an instance of the user into the foreign key field.

  • @amongdoomers9464
    @amongdoomers9464 4 ปีที่แล้ว +3

    Hey guys if this still doesn't save your blog add two more parameters to the author field like author=models.Foreignkey(User,default=None,blank=True,null=True,on_delete=models.CASCADE)
    this should probably work!

  • @Vengen007
    @Vengen007 5 ปีที่แล้ว +1

    Nice ! ...
    tips
    -Add on_delete thing to foreign key
    -Careful with usage of User and user
    -there is nothing to check if an article with same name/slug exists .. So if you do .. You'll get the GET error saying it got 2 things

    • @syedmdharris8814
      @syedmdharris8814 4 ปีที่แล้ว

      sir,on_delete =''', what value we should give on this field

  • @altair6616
    @altair6616 6 ปีที่แล้ว +3

  • @almuntasirabir4511
    @almuntasirabir4511 6 ปีที่แล้ว +1

    One heads up guys , if you are working in pycharm it automatically saves all the changes in code and you won't be able to migrate before you delete all your articles. so if this shows up comment out the code in models and delete all the articles.

  • @emiktra7929
    @emiktra7929 2 ปีที่แล้ว

    you just saved me hours of work, thank you very much mate

  • @sparklingtwilight4312
    @sparklingtwilight4312 5 ปีที่แล้ว +1

    Thank you very much! Going to reach 300K subscribers soon! I am sooo glad! CONGRATULATIONS!

    • @NetNinja
      @NetNinja  5 ปีที่แล้ว

      Thank you :D

  • @mhmmdmustafayev8216
    @mhmmdmustafayev8216 3 ปีที่แล้ว +1

    You Are AWESOME thank you

  • @pascalezeama7409
    @pascalezeama7409 3 ปีที่แล้ว

    Exactly what I was searching for

  • @likjou
    @likjou 2 ปีที่แล้ว

    Omg big help on solving my error. Thank you

    • @NetNinja
      @NetNinja  2 ปีที่แล้ว

      Awesome, glad I could help! :)

  • @nosnibornek1
    @nosnibornek1 5 ปีที่แล้ว

    Thanks for a great video! I've been trying to figure this out and finally I saw your video after searching and searching. Works like a charm! Thank You!

  • @ssu1782
    @ssu1782 ปีที่แล้ว

    thanks nicely explained

  • @chimerablack4913
    @chimerablack4913 5 ปีที่แล้ว

    you don't have to delete your old articles when you change the model. You can just set null=true for the new field.

  • @bsmaheshkumar5328
    @bsmaheshkumar5328 3 ปีที่แล้ว

    Oh, man thanks a ton🙏🙏🙏.
    This was Much needed for me tbh.

  • @santoshnegalur6837
    @santoshnegalur6837 2 ปีที่แล้ว

    Thanks It helped me a lot😀

  • @abhishekfredrick
    @abhishekfredrick 2 ปีที่แล้ว

    Helped a lot! Thanks

  • @kirankumaruppuganti
    @kirankumaruppuganti 4 ปีที่แล้ว +1

    if anyone getting " TypeError: Field 'id' expected a number but got None " error then try Delete all files except 'init' in migrations folder and do makemigrations, migrate again... that worked for me

  • @lerafml
    @lerafml 6 ปีที่แล้ว +1

    thanks a lot for your videos! very useful.)

  • @alexissuarezalvarez5622
    @alexissuarezalvarez5622 3 ปีที่แล้ว

    I like this way of carrying out the transaction and passing to the user, but is it the best practice? or is there a better one

  • @magickaito
    @magickaito ปีที่แล้ว

    There is an error when I make the migration: ForeignKey.__init__() missing 1 required positional argument: 'on_delete', perhaps it caused due to the version and to fix this just add another parameter on_delete like this:
    author = models.ForeignKey(User,on_delete=models.CASCADE)
    Hope this can be helpful.

  • @GrumpyOldMan9
    @GrumpyOldMan9 ปีที่แล้ว

    In the admin page, in "articles", in the drop-down menu for "author", how does Django know what field of the author to show (id, first_name, last_name etc.)?

  • @dhrutijoshi3701
    @dhrutijoshi3701 2 ปีที่แล้ว

    In my case migrations always failed ...with error no migrations need to apply
    After running server I am getting no such column
    PLEASE PLEASE HELP

  • @DuongTran-zh6td
    @DuongTran-zh6td ปีที่แล้ว

    1:35 tao foreign key trong model (articles) de luu article moi vao trong user
    4:58 them code vao ham de luu form do client tao

  • @michaelkissel8350
    @michaelkissel8350 4 ปีที่แล้ว

    Thanks a lot, great explanation. Searched hours for this topic.

  • @biophilic23
    @biophilic23 ปีที่แล้ว

    As Simplified As Butter

  • @rangabharath4253
    @rangabharath4253 4 ปีที่แล้ว

    Awesome. Thank you

  • @egehurturk6209
    @egehurturk6209 4 ปีที่แล้ว

    great content!

  • @vitalysoff9850
    @vitalysoff9850 4 ปีที่แล้ว

    Thanks so much!!!!

  • @humbertoy.9817
    @humbertoy.9817 2 ปีที่แล้ว

    is there any way to get the foreignkey In ascending order of table instead of default=none ?

  • @devansh._.bhardwaj
    @devansh._.bhardwaj 5 ปีที่แล้ว

    thanks a lot

  • @egehurturk6209
    @egehurturk6209 4 ปีที่แล้ว

    I have a question, where do 'instance' know that it is related to the model Article?

  • @arihanthirawat6574
    @arihanthirawat6574 4 ปีที่แล้ว +1

    delete all articles and
    add this line to models.py
    author = models.ForeignKey(User, on_delete=models.CASCADE,default=None)

    • @MayurPardeshi1
      @MayurPardeshi1 4 ปีที่แล้ว

      Its not working for me. I am getting an error 'django.db.utils.OperationalError: no such column: sign_up_post.author_id'
      sign_up = my moduke name
      post = class name in models.py
      author = field name

  • @564151199
    @564151199 5 ปีที่แล้ว

    TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime',im getting such type error ,can somebody fix this problems please

  • @ahbarahad3203
    @ahbarahad3203 4 ปีที่แล้ว +1

    are you from Howgwaarts?

  • @theone4159
    @theone4159 5 ปีที่แล้ว

    Thank you very much your greate

  • @meiyuncao8426
    @meiyuncao8426 3 ปีที่แล้ว

    what if I cannot use the superuser I created before? I am not sure why, but just say it not authenticated to admin page, how can I log in the admin page again?

    • @doomzy9790
      @doomzy9790 3 ปีที่แล้ว

      create another superuser

  • @MMKhan-tk4ir
    @MMKhan-tk4ir 3 ปีที่แล้ว

    user can save multiple artical or just one?

  • @jaimeenriquechachapizarro9397
    @jaimeenriquechachapizarro9397 3 ปีที่แล้ว

    Can someone give me the code please ..love you courses

  • @mrheimatschanke2987
    @mrheimatschanke2987 3 ปีที่แล้ว

    But what if I don't have any form in views.py?

  • @eliasmontsh
    @eliasmontsh 5 ปีที่แล้ว

    How do we implement search functionality on this app?

  • @panathinaikoscy
    @panathinaikoscy 6 ปีที่แล้ว

    What if I wanted to show the id of a user instead of the username, inside the select box of the backend? So instead of having mario etc as options, it would show the user id and use that as the foreign key, is it possible?

  • @Lbmaniak
    @Lbmaniak 5 ปีที่แล้ว

    thx

  • @AkashChatterjee
    @AkashChatterjee 4 ปีที่แล้ว

    its showing return Database.Cursor.execute(self, query, params)
    django.db.utils.IntegrityError: NOT NULL constraint failed: new__articles_article.author_id
    what should i do?

    • @687r45dfg
      @687r45dfg 4 ปีที่แล้ว

      I don't think you still have a problem. but if have the go-to migrations folder and delete the last migrations with name 000_autho_blah manually and the go-to the admin site and delete all the articles i had the problem cause i thought i am genius and not deleted all the articles from database get more help here:
      stackoverflow.com/questions/42733221/django-db-utils-integrityerror-not-null-constraint-failed-products-product-ima

  • @rangabharath4253
    @rangabharath4253 4 ปีที่แล้ว

    awesome

  • @matthewamstutz8889
    @matthewamstutz8889 5 ปีที่แล้ว

    Having such a difficult time with getting the damn thing to post to the page. Did you remove Django's built in Permission system for your users? I'm wondering if that is why I can't get the users stuff to post. I have an admin_posts app and it can only be posted to from the admin site BUT the posts actually show up as expected. So I've narrowed it down to something not getting sent (via the view) properly. Earlier I got the publish date to show up but no text. All the while the posts show up in the admin page (when you go to your page posts) Text and all. I cannot find a single thing on this everyone.....I'm not even joking when I say I've been reading docs and researching this for 18 hours yesterday (a good portion was spent on making sure users can register and such) and 10 the day before. This is going to be a large project and I can tell I'm gonnna have to redo it so many times. Thank god for backups right? (I even have backups hidden on my hard drive in case I accidentally modify a back up or get drunk and try to save working but fucked up code over top of the backups.......I love programming and this is one reason, this is serious fucking work if you actually want to do this. It's not actually easy because, well look at everything you have to learn. almost a month in and though I understand SO MUCH about how django works and understand waaay better on how python works [I'm using python 3] that I actually think I might be able to get a job in this one day, hopefully soon.)
    Good luck everyone, keep your heads about you when an error comes up and you can't figure it out. It will come eventually and don't let yourself get burnt out, if you start dreading working on your project, stop for a day or two. DO NOT LET YOURSELF GO BACK TO IT until you actually want to and the thought of attempting to fix the errors doesn't piss you off or upset you (you can be upset because Errors fucking suck but try not to actually get mad)... WELL THAT WAS A NICE BREAK FROM FUCK UP CITY lmao Wish me luck y'all
    print("Good luck and happy coding!
    ")
    print("P.S PYTHON IS GREAT")

  • @jondyason336
    @jondyason336 6 ปีที่แล้ว

    Wizardry!

  • @shuvo-d-4839
    @shuvo-d-4839 2 ปีที่แล้ว

    6:03

  • @sntshkmr60
    @sntshkmr60 5 ปีที่แล้ว

    From where is the user coming to the request?

  • @shuvo-d-4839
    @shuvo-d-4839 2 ปีที่แล้ว

    2:29

  • @souliphon_test3005
    @souliphon_test3005 4 ปีที่แล้ว +2

    Can you do this in Class Based View?
    In CreateView?
    I have been trying to figure out but I can't. If you don't mind, please give me the way I can work this out.

    • @thanatos2288
      @thanatos2288 4 ปีที่แล้ว

      I'm stuck there as well. Let me know if you have found any solutions, I hope you did.

  • @hiteshchoudhary3412
    @hiteshchoudhary3412 6 ปีที่แล้ว +2

    Hi Shaun, please complete this series fast, it's almost so late for django, looking for next series egarly

  • @SiddharthaJuluru
    @SiddharthaJuluru 6 ปีที่แล้ว

    Can you please do a vid on jsonwebtoken by making it require a token to post and also being able to reset the token

  • @bhargavibelavadi
    @bhargavibelavadi 6 ปีที่แล้ว

    how to save the user entered data in database... u have not written code for saving..

  • @sameerpatil1022
    @sameerpatil1022 3 ปีที่แล้ว

    That sounds like British.............