Django how to get two models in relation?How to merge two dictionaries in a single expression?How do I check if a list is empty?How do I check whether a file exists without exceptions?How can I safely create a nested directory?How to get the current time in PythonHow do I sort a dictionary by value?Does Django scale?How do I concatenate two lists in Python?How do I list all files of a directory?differentiate null=True, blank=True in django

bash vs. zsh: What are the practical differences?

Do ailerons on opposite wings move together?

I have a problematic assistant manager, but I can't fire him

Printing Pascal’s triangle for n number of rows in Python

Why can my keyboard only digest 6 keypresses at a time?

Is this a bug in plotting step functions?

How to learn Linux system internals

Why is long-term living in Almost-Earth causing severe health problems?

Why are MBA programs closing in the United States?

Increase speed altering column on large table to NON NULL

I've been given a project I can't complete, what should I do?

Does putting salt first make it easier for attacker to bruteforce the hash?

AMPScript SMS InsertDE() function not working in SMS

Return a String containing only alphabets without spaces

What would be the way to say "just saying" in German? (Not the literal translation)

What differences exist between adamantine and adamantite in all editions of D&D?

Did Apple bundle a specific monitor with the Apple II+ for schools?

How to safely destroy (a large quantity of) valid checks?

Why was this person allowed to become Grand Maester?

Why am I Seeing A Weird "Notch" on the Data Line For Some Logical 1s?

Live action TV show where High school Kids go into the virtual world and have to clear levels

Ability To Change Root User Password (Vulnerability?)

UTC timestamp format for launch vehicles

Longest bridge/tunnel that can be cycled over/through?



Django how to get two models in relation?


How to merge two dictionaries in a single expression?How do I check if a list is empty?How do I check whether a file exists without exceptions?How can I safely create a nested directory?How to get the current time in PythonHow do I sort a dictionary by value?Does Django scale?How do I concatenate two lists in Python?How do I list all files of a directory?differentiate null=True, blank=True in django






.everyoneloves__top-leaderboard:empty,.everyoneloves__mid-leaderboard:empty,.everyoneloves__bot-mid-leaderboard:empty height:90px;width:728px;box-sizing:border-box;








1















At my django application users are able to buy specific posted elements. To later-on display a content_preview or the full content of a post i created a "helper_model" -> Post_Paid_Sell_Tut to check if a user has paid for the post or not. My target is that i can later on display the peview or full content accordingly to the paid or unpaid status but i dont clearly understand how to get those two models in relations at my views.py



i created the following two models for this:



PAYMENT_STATUS = (
(0, 'unpaid'),
(1, 'paid')
)

class Post_Paid_Sell_Tut(models.Model):
paying_user = models.ForeignKey(User, on_delete=models.CASCADE)
post_sell_tut = models.ForeignKey(Post_Sell_Tut, on_delete=models.CASCADE)
STATUS = models.IntegerField(choices=PAYMENT_STATUS, default=0)
paid_date = models.DateField(auto_now_add=True)

def publish(self):
self.paid_date = timezone.now()
self.save()

class Meta:
ordering = ['-paid_date']



class Post_Sell_Tut(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE)
title = models.CharField(max_length=40)
content_preview = models.TextField(verbose_name="Tut Content Preview", max_length=500)
content = EncryptedTextField(verbose_name="Tut Content", max_length=10000)
.....


now i want to understand how i can bring those two models in relations at my views.py.
In the end the user will see a form with only a Buy button and some Text. after he hits the button the status should get changed from unpaid to paid for the paying user.



my current views.py (Updated)



def post_sell_tut_buy(request, pk):
post = get_object_or_404(Post_Sell_Tut, pk=pk)
if request.user == post.author:
messages.error(request, 'You cannot buy POst(s) you created by your own!')
return redirect('post_sell_tut_detail', pk=post.pk)
else:
template = 'Post_Sell_Tut/post_sell_tut_buy.html'
context =
'post': post,

return render(request, template, context)


def post_sell_tut_buy_exec(request, pk):
post = get_object_or_404(Post_Sell_Tut, pk=pk)
if request.user == post.author:
messages.error(request, 'You cannot buy Post(s) you created by your own!')
return redirect('post_sell_tut_detail', pk=post.pk)
else:
template = 'Post_Sell_Tut/post_sell_tut_buy.html'
post.STATUS = 1
post.save()
context =
'post': post

return render(request, template, context)


Do i really need a Form at this point?
and if so, how does it have to look like?



Thanks for help in adavance :)










share|improve this question






























    1















    At my django application users are able to buy specific posted elements. To later-on display a content_preview or the full content of a post i created a "helper_model" -> Post_Paid_Sell_Tut to check if a user has paid for the post or not. My target is that i can later on display the peview or full content accordingly to the paid or unpaid status but i dont clearly understand how to get those two models in relations at my views.py



    i created the following two models for this:



    PAYMENT_STATUS = (
    (0, 'unpaid'),
    (1, 'paid')
    )

    class Post_Paid_Sell_Tut(models.Model):
    paying_user = models.ForeignKey(User, on_delete=models.CASCADE)
    post_sell_tut = models.ForeignKey(Post_Sell_Tut, on_delete=models.CASCADE)
    STATUS = models.IntegerField(choices=PAYMENT_STATUS, default=0)
    paid_date = models.DateField(auto_now_add=True)

    def publish(self):
    self.paid_date = timezone.now()
    self.save()

    class Meta:
    ordering = ['-paid_date']



    class Post_Sell_Tut(models.Model):
    author = models.ForeignKey(User, on_delete=models.CASCADE)
    title = models.CharField(max_length=40)
    content_preview = models.TextField(verbose_name="Tut Content Preview", max_length=500)
    content = EncryptedTextField(verbose_name="Tut Content", max_length=10000)
    .....


    now i want to understand how i can bring those two models in relations at my views.py.
    In the end the user will see a form with only a Buy button and some Text. after he hits the button the status should get changed from unpaid to paid for the paying user.



    my current views.py (Updated)



    def post_sell_tut_buy(request, pk):
    post = get_object_or_404(Post_Sell_Tut, pk=pk)
    if request.user == post.author:
    messages.error(request, 'You cannot buy POst(s) you created by your own!')
    return redirect('post_sell_tut_detail', pk=post.pk)
    else:
    template = 'Post_Sell_Tut/post_sell_tut_buy.html'
    context =
    'post': post,

    return render(request, template, context)


    def post_sell_tut_buy_exec(request, pk):
    post = get_object_or_404(Post_Sell_Tut, pk=pk)
    if request.user == post.author:
    messages.error(request, 'You cannot buy Post(s) you created by your own!')
    return redirect('post_sell_tut_detail', pk=post.pk)
    else:
    template = 'Post_Sell_Tut/post_sell_tut_buy.html'
    post.STATUS = 1
    post.save()
    context =
    'post': post

    return render(request, template, context)


    Do i really need a Form at this point?
    and if so, how does it have to look like?



    Thanks for help in adavance :)










    share|improve this question


























      1












      1








      1








      At my django application users are able to buy specific posted elements. To later-on display a content_preview or the full content of a post i created a "helper_model" -> Post_Paid_Sell_Tut to check if a user has paid for the post or not. My target is that i can later on display the peview or full content accordingly to the paid or unpaid status but i dont clearly understand how to get those two models in relations at my views.py



      i created the following two models for this:



      PAYMENT_STATUS = (
      (0, 'unpaid'),
      (1, 'paid')
      )

      class Post_Paid_Sell_Tut(models.Model):
      paying_user = models.ForeignKey(User, on_delete=models.CASCADE)
      post_sell_tut = models.ForeignKey(Post_Sell_Tut, on_delete=models.CASCADE)
      STATUS = models.IntegerField(choices=PAYMENT_STATUS, default=0)
      paid_date = models.DateField(auto_now_add=True)

      def publish(self):
      self.paid_date = timezone.now()
      self.save()

      class Meta:
      ordering = ['-paid_date']



      class Post_Sell_Tut(models.Model):
      author = models.ForeignKey(User, on_delete=models.CASCADE)
      title = models.CharField(max_length=40)
      content_preview = models.TextField(verbose_name="Tut Content Preview", max_length=500)
      content = EncryptedTextField(verbose_name="Tut Content", max_length=10000)
      .....


      now i want to understand how i can bring those two models in relations at my views.py.
      In the end the user will see a form with only a Buy button and some Text. after he hits the button the status should get changed from unpaid to paid for the paying user.



      my current views.py (Updated)



      def post_sell_tut_buy(request, pk):
      post = get_object_or_404(Post_Sell_Tut, pk=pk)
      if request.user == post.author:
      messages.error(request, 'You cannot buy POst(s) you created by your own!')
      return redirect('post_sell_tut_detail', pk=post.pk)
      else:
      template = 'Post_Sell_Tut/post_sell_tut_buy.html'
      context =
      'post': post,

      return render(request, template, context)


      def post_sell_tut_buy_exec(request, pk):
      post = get_object_or_404(Post_Sell_Tut, pk=pk)
      if request.user == post.author:
      messages.error(request, 'You cannot buy Post(s) you created by your own!')
      return redirect('post_sell_tut_detail', pk=post.pk)
      else:
      template = 'Post_Sell_Tut/post_sell_tut_buy.html'
      post.STATUS = 1
      post.save()
      context =
      'post': post

      return render(request, template, context)


      Do i really need a Form at this point?
      and if so, how does it have to look like?



      Thanks for help in adavance :)










      share|improve this question
















      At my django application users are able to buy specific posted elements. To later-on display a content_preview or the full content of a post i created a "helper_model" -> Post_Paid_Sell_Tut to check if a user has paid for the post or not. My target is that i can later on display the peview or full content accordingly to the paid or unpaid status but i dont clearly understand how to get those two models in relations at my views.py



      i created the following two models for this:



      PAYMENT_STATUS = (
      (0, 'unpaid'),
      (1, 'paid')
      )

      class Post_Paid_Sell_Tut(models.Model):
      paying_user = models.ForeignKey(User, on_delete=models.CASCADE)
      post_sell_tut = models.ForeignKey(Post_Sell_Tut, on_delete=models.CASCADE)
      STATUS = models.IntegerField(choices=PAYMENT_STATUS, default=0)
      paid_date = models.DateField(auto_now_add=True)

      def publish(self):
      self.paid_date = timezone.now()
      self.save()

      class Meta:
      ordering = ['-paid_date']



      class Post_Sell_Tut(models.Model):
      author = models.ForeignKey(User, on_delete=models.CASCADE)
      title = models.CharField(max_length=40)
      content_preview = models.TextField(verbose_name="Tut Content Preview", max_length=500)
      content = EncryptedTextField(verbose_name="Tut Content", max_length=10000)
      .....


      now i want to understand how i can bring those two models in relations at my views.py.
      In the end the user will see a form with only a Buy button and some Text. after he hits the button the status should get changed from unpaid to paid for the paying user.



      my current views.py (Updated)



      def post_sell_tut_buy(request, pk):
      post = get_object_or_404(Post_Sell_Tut, pk=pk)
      if request.user == post.author:
      messages.error(request, 'You cannot buy POst(s) you created by your own!')
      return redirect('post_sell_tut_detail', pk=post.pk)
      else:
      template = 'Post_Sell_Tut/post_sell_tut_buy.html'
      context =
      'post': post,

      return render(request, template, context)


      def post_sell_tut_buy_exec(request, pk):
      post = get_object_or_404(Post_Sell_Tut, pk=pk)
      if request.user == post.author:
      messages.error(request, 'You cannot buy Post(s) you created by your own!')
      return redirect('post_sell_tut_detail', pk=post.pk)
      else:
      template = 'Post_Sell_Tut/post_sell_tut_buy.html'
      post.STATUS = 1
      post.save()
      context =
      'post': post

      return render(request, template, context)


      Do i really need a Form at this point?
      and if so, how does it have to look like?



      Thanks for help in adavance :)







      python django django-models






      share|improve this question















      share|improve this question













      share|improve this question




      share|improve this question








      edited Mar 25 at 13:12







      Venom

















      asked Mar 24 at 19:51









      VenomVenom

      114110




      114110






















          2 Answers
          2






          active

          oldest

          votes


















          0














          First of all, you should change your status choices a little bit.



          STATUSES = (
          (0, 'unpaid'),
          (1, 'paid')
          )

          class Post_Paid_Sell_Tut(models.Model):
          paying_user = models.ForeignKey(User, on_delete=models.CASCADE)
          post_sell_tut = models.ForeignKey(Post_Sell_Tut, on_delete=models.CASCADE)
          STATUS = models.IntegerField(choices=STATUSES, default=0)


          This will ease later database searches and will clarify the issues. Then if you are just updating the status then there is no need for any form.



          def post_sell_tut_buy(request, pk):
          post = get_object_or_404(Post_Sell_Tut, pk=pk)
          if request.user == post.author:
          messages.error(request, 'You cant buy your own Post!')
          return redirect('post_sell_tut_detail', pk=pk)
          else:
          template = 'Post_Sell_Tut/post_sell_tut_buy.html'
          post.STATUS = 1 # You are updating the STATUS
          post.save() # you are writing the change to database
          context =
          'post': post

          return render(request, template, context)


          In addition by passing post instance to the template you are desired to view the informations you should follow this:



          def post_sell_tut_buy(request, pk):
          post = Post_Paid_Sell_Tut.objects.select_related('post_sell_tut').filter(pk=pk)
          if request.user == post.author:
          messages.error(request, 'You cant buy your own Post!')
          return redirect('post_sell_tut_detail', pk=pk)
          else:
          template = 'Post_Sell_Tut/post_sell_tut_buy.html'
          post.STATUS = 1 # You are updating the STATUS
          post.save() # you are writing the change to database
          context =
          'post': post

          return render(request, template, context)


          I added select_related because when you try to fetch information by the foreign key in from post it will not cause an extra DB request.



          UPDATE



          def post_sell_tut_buy(request, pk):
          post = Post_Sell_Tut.objects.select_related('author).filter(pk=pk)
          if request.user == post.author:
          messages.error(request, 'You cannot buy POst(s) you created by your own!')
          return redirect('post_sell_tut_detail', pk=post.pk)
          else:
          template = 'Post_Sell_Tut/post_sell_tut_buy.html'
          context =
          'post': post,

          return render(request, template, context)


          You cannot access STATUS from Post_Sell_Tut model. It does not have that field.



          def post_sell_tut_buy_exec(request, pk):
          post_sell_tut = get_object_or_404(Post_Sell_Tut, pk=pk)
          post_paid_sell_tut = Post_Paid_Sell_Tut.objects.filter(post_sell_tut=post_sell_tut)
          if request.user == post.author:
          messages.error(request, 'You cannot buy Post(s) you created by your own!')
          return redirect('post_sell_tut_detail', pk=post.pk)
          else:
          template = 'Post_Sell_Tut/post_sell_tut_buy.html'
          post_paid_sell_tut.STATUS = 1
          post_paid_sell_tut.save()
          context =
          'post': post

          return render(request, template, context)





          share|improve this answer

























          • Hello thanks for your help so far but if i use your last block of code i get "'QuerySet' object has no attribute 'author' "

            – Venom
            Mar 25 at 12:53











          • I just updated my question. I need to have the first view to show a overview of the actual item the user buys and the second to trigger the actuall action at the DB

            – Venom
            Mar 25 at 13:13











          • You should really be sure what will be viewed in the template. If you just will view post_sell_tut model then this is fine but with this mechanism, you will not be able to view other models data except the author.

            – Rarblack
            Mar 25 at 14:59











          • Also got on that now ;) i guess i will re-think about this workflow. I also found out that im forced to use a form due to that the user needs to select a currency he want to pay with USD, EUR etc... ...

            – Venom
            Mar 25 at 15:29











          • I would suggest you re-think in naming too. After a selected amount of time, you will have bad times with names. Also, your mechanism needs improvements in the name of programming. In addition, if this question is done for you please consider of accepting an answer and upvoting it in order to make it easy for others to find and giving credit to the effort.

            – Rarblack
            Mar 25 at 18:10


















          0














          just create a "Post_Paid_Sell_Tut" object when a user requests to buy a post



           def post_sell_tut_buy(request, pk):
          post = get_object_or_404(Post_Sell_Tut, pk=pk)
          if request.user == post.author:
          messages.error(request, 'You cant buy your own Post!')
          return redirect('post_sell_tut_detail', pk=post.pk)
          else:
          try:
          # throws an exception if not bought yet
          Post_Paid_Sell_Tut.get(paying_user=request.user, post_sell_tut=post)
          messages.success(request, 'you allready have this post!')
          # ... other stuff

          except Post_Paid_Sell_Tut.DoesNotExist:
          # create Post_Paid_Sell_Tut object indicating that the user bought the post
          ppst = Post_Paid_Sell_Tut(paying_user=request.user,
          post_sell_tut=post, status="paid")
          ppst.save()
          messages.success(request, 'post is yours :)!')
          # ... other stuff





          share|improve this answer























            Your Answer






            StackExchange.ifUsing("editor", function ()
            StackExchange.using("externalEditor", function ()
            StackExchange.using("snippets", function ()
            StackExchange.snippets.init();
            );
            );
            , "code-snippets");

            StackExchange.ready(function()
            var channelOptions =
            tags: "".split(" "),
            id: "1"
            ;
            initTagRenderer("".split(" "), "".split(" "), channelOptions);

            StackExchange.using("externalEditor", function()
            // Have to fire editor after snippets, if snippets enabled
            if (StackExchange.settings.snippets.snippetsEnabled)
            StackExchange.using("snippets", function()
            createEditor();
            );

            else
            createEditor();

            );

            function createEditor()
            StackExchange.prepareEditor(
            heartbeatType: 'answer',
            autoActivateHeartbeat: false,
            convertImagesToLinks: true,
            noModals: true,
            showLowRepImageUploadWarning: true,
            reputationToPostImages: 10,
            bindNavPrevention: true,
            postfix: "",
            imageUploader:
            brandingHtml: "Powered by u003ca class="icon-imgur-white" href="https://imgur.com/"u003eu003c/au003e",
            contentPolicyHtml: "User contributions licensed under u003ca href="https://creativecommons.org/licenses/by-sa/3.0/"u003ecc by-sa 3.0 with attribution requiredu003c/au003e u003ca href="https://stackoverflow.com/legal/content-policy"u003e(content policy)u003c/au003e",
            allowUrls: true
            ,
            onDemand: true,
            discardSelector: ".discard-answer"
            ,immediatelyShowMarkdownHelp:true
            );



            );













            draft saved

            draft discarded


















            StackExchange.ready(
            function ()
            StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55327918%2fdjango-how-to-get-two-models-in-relation%23new-answer', 'question_page');

            );

            Post as a guest















            Required, but never shown

























            2 Answers
            2






            active

            oldest

            votes








            2 Answers
            2






            active

            oldest

            votes









            active

            oldest

            votes






            active

            oldest

            votes









            0














            First of all, you should change your status choices a little bit.



            STATUSES = (
            (0, 'unpaid'),
            (1, 'paid')
            )

            class Post_Paid_Sell_Tut(models.Model):
            paying_user = models.ForeignKey(User, on_delete=models.CASCADE)
            post_sell_tut = models.ForeignKey(Post_Sell_Tut, on_delete=models.CASCADE)
            STATUS = models.IntegerField(choices=STATUSES, default=0)


            This will ease later database searches and will clarify the issues. Then if you are just updating the status then there is no need for any form.



            def post_sell_tut_buy(request, pk):
            post = get_object_or_404(Post_Sell_Tut, pk=pk)
            if request.user == post.author:
            messages.error(request, 'You cant buy your own Post!')
            return redirect('post_sell_tut_detail', pk=pk)
            else:
            template = 'Post_Sell_Tut/post_sell_tut_buy.html'
            post.STATUS = 1 # You are updating the STATUS
            post.save() # you are writing the change to database
            context =
            'post': post

            return render(request, template, context)


            In addition by passing post instance to the template you are desired to view the informations you should follow this:



            def post_sell_tut_buy(request, pk):
            post = Post_Paid_Sell_Tut.objects.select_related('post_sell_tut').filter(pk=pk)
            if request.user == post.author:
            messages.error(request, 'You cant buy your own Post!')
            return redirect('post_sell_tut_detail', pk=pk)
            else:
            template = 'Post_Sell_Tut/post_sell_tut_buy.html'
            post.STATUS = 1 # You are updating the STATUS
            post.save() # you are writing the change to database
            context =
            'post': post

            return render(request, template, context)


            I added select_related because when you try to fetch information by the foreign key in from post it will not cause an extra DB request.



            UPDATE



            def post_sell_tut_buy(request, pk):
            post = Post_Sell_Tut.objects.select_related('author).filter(pk=pk)
            if request.user == post.author:
            messages.error(request, 'You cannot buy POst(s) you created by your own!')
            return redirect('post_sell_tut_detail', pk=post.pk)
            else:
            template = 'Post_Sell_Tut/post_sell_tut_buy.html'
            context =
            'post': post,

            return render(request, template, context)


            You cannot access STATUS from Post_Sell_Tut model. It does not have that field.



            def post_sell_tut_buy_exec(request, pk):
            post_sell_tut = get_object_or_404(Post_Sell_Tut, pk=pk)
            post_paid_sell_tut = Post_Paid_Sell_Tut.objects.filter(post_sell_tut=post_sell_tut)
            if request.user == post.author:
            messages.error(request, 'You cannot buy Post(s) you created by your own!')
            return redirect('post_sell_tut_detail', pk=post.pk)
            else:
            template = 'Post_Sell_Tut/post_sell_tut_buy.html'
            post_paid_sell_tut.STATUS = 1
            post_paid_sell_tut.save()
            context =
            'post': post

            return render(request, template, context)





            share|improve this answer

























            • Hello thanks for your help so far but if i use your last block of code i get "'QuerySet' object has no attribute 'author' "

              – Venom
              Mar 25 at 12:53











            • I just updated my question. I need to have the first view to show a overview of the actual item the user buys and the second to trigger the actuall action at the DB

              – Venom
              Mar 25 at 13:13











            • You should really be sure what will be viewed in the template. If you just will view post_sell_tut model then this is fine but with this mechanism, you will not be able to view other models data except the author.

              – Rarblack
              Mar 25 at 14:59











            • Also got on that now ;) i guess i will re-think about this workflow. I also found out that im forced to use a form due to that the user needs to select a currency he want to pay with USD, EUR etc... ...

              – Venom
              Mar 25 at 15:29











            • I would suggest you re-think in naming too. After a selected amount of time, you will have bad times with names. Also, your mechanism needs improvements in the name of programming. In addition, if this question is done for you please consider of accepting an answer and upvoting it in order to make it easy for others to find and giving credit to the effort.

              – Rarblack
              Mar 25 at 18:10















            0














            First of all, you should change your status choices a little bit.



            STATUSES = (
            (0, 'unpaid'),
            (1, 'paid')
            )

            class Post_Paid_Sell_Tut(models.Model):
            paying_user = models.ForeignKey(User, on_delete=models.CASCADE)
            post_sell_tut = models.ForeignKey(Post_Sell_Tut, on_delete=models.CASCADE)
            STATUS = models.IntegerField(choices=STATUSES, default=0)


            This will ease later database searches and will clarify the issues. Then if you are just updating the status then there is no need for any form.



            def post_sell_tut_buy(request, pk):
            post = get_object_or_404(Post_Sell_Tut, pk=pk)
            if request.user == post.author:
            messages.error(request, 'You cant buy your own Post!')
            return redirect('post_sell_tut_detail', pk=pk)
            else:
            template = 'Post_Sell_Tut/post_sell_tut_buy.html'
            post.STATUS = 1 # You are updating the STATUS
            post.save() # you are writing the change to database
            context =
            'post': post

            return render(request, template, context)


            In addition by passing post instance to the template you are desired to view the informations you should follow this:



            def post_sell_tut_buy(request, pk):
            post = Post_Paid_Sell_Tut.objects.select_related('post_sell_tut').filter(pk=pk)
            if request.user == post.author:
            messages.error(request, 'You cant buy your own Post!')
            return redirect('post_sell_tut_detail', pk=pk)
            else:
            template = 'Post_Sell_Tut/post_sell_tut_buy.html'
            post.STATUS = 1 # You are updating the STATUS
            post.save() # you are writing the change to database
            context =
            'post': post

            return render(request, template, context)


            I added select_related because when you try to fetch information by the foreign key in from post it will not cause an extra DB request.



            UPDATE



            def post_sell_tut_buy(request, pk):
            post = Post_Sell_Tut.objects.select_related('author).filter(pk=pk)
            if request.user == post.author:
            messages.error(request, 'You cannot buy POst(s) you created by your own!')
            return redirect('post_sell_tut_detail', pk=post.pk)
            else:
            template = 'Post_Sell_Tut/post_sell_tut_buy.html'
            context =
            'post': post,

            return render(request, template, context)


            You cannot access STATUS from Post_Sell_Tut model. It does not have that field.



            def post_sell_tut_buy_exec(request, pk):
            post_sell_tut = get_object_or_404(Post_Sell_Tut, pk=pk)
            post_paid_sell_tut = Post_Paid_Sell_Tut.objects.filter(post_sell_tut=post_sell_tut)
            if request.user == post.author:
            messages.error(request, 'You cannot buy Post(s) you created by your own!')
            return redirect('post_sell_tut_detail', pk=post.pk)
            else:
            template = 'Post_Sell_Tut/post_sell_tut_buy.html'
            post_paid_sell_tut.STATUS = 1
            post_paid_sell_tut.save()
            context =
            'post': post

            return render(request, template, context)





            share|improve this answer

























            • Hello thanks for your help so far but if i use your last block of code i get "'QuerySet' object has no attribute 'author' "

              – Venom
              Mar 25 at 12:53











            • I just updated my question. I need to have the first view to show a overview of the actual item the user buys and the second to trigger the actuall action at the DB

              – Venom
              Mar 25 at 13:13











            • You should really be sure what will be viewed in the template. If you just will view post_sell_tut model then this is fine but with this mechanism, you will not be able to view other models data except the author.

              – Rarblack
              Mar 25 at 14:59











            • Also got on that now ;) i guess i will re-think about this workflow. I also found out that im forced to use a form due to that the user needs to select a currency he want to pay with USD, EUR etc... ...

              – Venom
              Mar 25 at 15:29











            • I would suggest you re-think in naming too. After a selected amount of time, you will have bad times with names. Also, your mechanism needs improvements in the name of programming. In addition, if this question is done for you please consider of accepting an answer and upvoting it in order to make it easy for others to find and giving credit to the effort.

              – Rarblack
              Mar 25 at 18:10













            0












            0








            0







            First of all, you should change your status choices a little bit.



            STATUSES = (
            (0, 'unpaid'),
            (1, 'paid')
            )

            class Post_Paid_Sell_Tut(models.Model):
            paying_user = models.ForeignKey(User, on_delete=models.CASCADE)
            post_sell_tut = models.ForeignKey(Post_Sell_Tut, on_delete=models.CASCADE)
            STATUS = models.IntegerField(choices=STATUSES, default=0)


            This will ease later database searches and will clarify the issues. Then if you are just updating the status then there is no need for any form.



            def post_sell_tut_buy(request, pk):
            post = get_object_or_404(Post_Sell_Tut, pk=pk)
            if request.user == post.author:
            messages.error(request, 'You cant buy your own Post!')
            return redirect('post_sell_tut_detail', pk=pk)
            else:
            template = 'Post_Sell_Tut/post_sell_tut_buy.html'
            post.STATUS = 1 # You are updating the STATUS
            post.save() # you are writing the change to database
            context =
            'post': post

            return render(request, template, context)


            In addition by passing post instance to the template you are desired to view the informations you should follow this:



            def post_sell_tut_buy(request, pk):
            post = Post_Paid_Sell_Tut.objects.select_related('post_sell_tut').filter(pk=pk)
            if request.user == post.author:
            messages.error(request, 'You cant buy your own Post!')
            return redirect('post_sell_tut_detail', pk=pk)
            else:
            template = 'Post_Sell_Tut/post_sell_tut_buy.html'
            post.STATUS = 1 # You are updating the STATUS
            post.save() # you are writing the change to database
            context =
            'post': post

            return render(request, template, context)


            I added select_related because when you try to fetch information by the foreign key in from post it will not cause an extra DB request.



            UPDATE



            def post_sell_tut_buy(request, pk):
            post = Post_Sell_Tut.objects.select_related('author).filter(pk=pk)
            if request.user == post.author:
            messages.error(request, 'You cannot buy POst(s) you created by your own!')
            return redirect('post_sell_tut_detail', pk=post.pk)
            else:
            template = 'Post_Sell_Tut/post_sell_tut_buy.html'
            context =
            'post': post,

            return render(request, template, context)


            You cannot access STATUS from Post_Sell_Tut model. It does not have that field.



            def post_sell_tut_buy_exec(request, pk):
            post_sell_tut = get_object_or_404(Post_Sell_Tut, pk=pk)
            post_paid_sell_tut = Post_Paid_Sell_Tut.objects.filter(post_sell_tut=post_sell_tut)
            if request.user == post.author:
            messages.error(request, 'You cannot buy Post(s) you created by your own!')
            return redirect('post_sell_tut_detail', pk=post.pk)
            else:
            template = 'Post_Sell_Tut/post_sell_tut_buy.html'
            post_paid_sell_tut.STATUS = 1
            post_paid_sell_tut.save()
            context =
            'post': post

            return render(request, template, context)





            share|improve this answer















            First of all, you should change your status choices a little bit.



            STATUSES = (
            (0, 'unpaid'),
            (1, 'paid')
            )

            class Post_Paid_Sell_Tut(models.Model):
            paying_user = models.ForeignKey(User, on_delete=models.CASCADE)
            post_sell_tut = models.ForeignKey(Post_Sell_Tut, on_delete=models.CASCADE)
            STATUS = models.IntegerField(choices=STATUSES, default=0)


            This will ease later database searches and will clarify the issues. Then if you are just updating the status then there is no need for any form.



            def post_sell_tut_buy(request, pk):
            post = get_object_or_404(Post_Sell_Tut, pk=pk)
            if request.user == post.author:
            messages.error(request, 'You cant buy your own Post!')
            return redirect('post_sell_tut_detail', pk=pk)
            else:
            template = 'Post_Sell_Tut/post_sell_tut_buy.html'
            post.STATUS = 1 # You are updating the STATUS
            post.save() # you are writing the change to database
            context =
            'post': post

            return render(request, template, context)


            In addition by passing post instance to the template you are desired to view the informations you should follow this:



            def post_sell_tut_buy(request, pk):
            post = Post_Paid_Sell_Tut.objects.select_related('post_sell_tut').filter(pk=pk)
            if request.user == post.author:
            messages.error(request, 'You cant buy your own Post!')
            return redirect('post_sell_tut_detail', pk=pk)
            else:
            template = 'Post_Sell_Tut/post_sell_tut_buy.html'
            post.STATUS = 1 # You are updating the STATUS
            post.save() # you are writing the change to database
            context =
            'post': post

            return render(request, template, context)


            I added select_related because when you try to fetch information by the foreign key in from post it will not cause an extra DB request.



            UPDATE



            def post_sell_tut_buy(request, pk):
            post = Post_Sell_Tut.objects.select_related('author).filter(pk=pk)
            if request.user == post.author:
            messages.error(request, 'You cannot buy POst(s) you created by your own!')
            return redirect('post_sell_tut_detail', pk=post.pk)
            else:
            template = 'Post_Sell_Tut/post_sell_tut_buy.html'
            context =
            'post': post,

            return render(request, template, context)


            You cannot access STATUS from Post_Sell_Tut model. It does not have that field.



            def post_sell_tut_buy_exec(request, pk):
            post_sell_tut = get_object_or_404(Post_Sell_Tut, pk=pk)
            post_paid_sell_tut = Post_Paid_Sell_Tut.objects.filter(post_sell_tut=post_sell_tut)
            if request.user == post.author:
            messages.error(request, 'You cannot buy Post(s) you created by your own!')
            return redirect('post_sell_tut_detail', pk=post.pk)
            else:
            template = 'Post_Sell_Tut/post_sell_tut_buy.html'
            post_paid_sell_tut.STATUS = 1
            post_paid_sell_tut.save()
            context =
            'post': post

            return render(request, template, context)






            share|improve this answer














            share|improve this answer



            share|improve this answer








            edited Mar 25 at 14:57

























            answered Mar 24 at 20:11









            RarblackRarblack

            3,20041229




            3,20041229












            • Hello thanks for your help so far but if i use your last block of code i get "'QuerySet' object has no attribute 'author' "

              – Venom
              Mar 25 at 12:53











            • I just updated my question. I need to have the first view to show a overview of the actual item the user buys and the second to trigger the actuall action at the DB

              – Venom
              Mar 25 at 13:13











            • You should really be sure what will be viewed in the template. If you just will view post_sell_tut model then this is fine but with this mechanism, you will not be able to view other models data except the author.

              – Rarblack
              Mar 25 at 14:59











            • Also got on that now ;) i guess i will re-think about this workflow. I also found out that im forced to use a form due to that the user needs to select a currency he want to pay with USD, EUR etc... ...

              – Venom
              Mar 25 at 15:29











            • I would suggest you re-think in naming too. After a selected amount of time, you will have bad times with names. Also, your mechanism needs improvements in the name of programming. In addition, if this question is done for you please consider of accepting an answer and upvoting it in order to make it easy for others to find and giving credit to the effort.

              – Rarblack
              Mar 25 at 18:10

















            • Hello thanks for your help so far but if i use your last block of code i get "'QuerySet' object has no attribute 'author' "

              – Venom
              Mar 25 at 12:53











            • I just updated my question. I need to have the first view to show a overview of the actual item the user buys and the second to trigger the actuall action at the DB

              – Venom
              Mar 25 at 13:13











            • You should really be sure what will be viewed in the template. If you just will view post_sell_tut model then this is fine but with this mechanism, you will not be able to view other models data except the author.

              – Rarblack
              Mar 25 at 14:59











            • Also got on that now ;) i guess i will re-think about this workflow. I also found out that im forced to use a form due to that the user needs to select a currency he want to pay with USD, EUR etc... ...

              – Venom
              Mar 25 at 15:29











            • I would suggest you re-think in naming too. After a selected amount of time, you will have bad times with names. Also, your mechanism needs improvements in the name of programming. In addition, if this question is done for you please consider of accepting an answer and upvoting it in order to make it easy for others to find and giving credit to the effort.

              – Rarblack
              Mar 25 at 18:10
















            Hello thanks for your help so far but if i use your last block of code i get "'QuerySet' object has no attribute 'author' "

            – Venom
            Mar 25 at 12:53





            Hello thanks for your help so far but if i use your last block of code i get "'QuerySet' object has no attribute 'author' "

            – Venom
            Mar 25 at 12:53













            I just updated my question. I need to have the first view to show a overview of the actual item the user buys and the second to trigger the actuall action at the DB

            – Venom
            Mar 25 at 13:13





            I just updated my question. I need to have the first view to show a overview of the actual item the user buys and the second to trigger the actuall action at the DB

            – Venom
            Mar 25 at 13:13













            You should really be sure what will be viewed in the template. If you just will view post_sell_tut model then this is fine but with this mechanism, you will not be able to view other models data except the author.

            – Rarblack
            Mar 25 at 14:59





            You should really be sure what will be viewed in the template. If you just will view post_sell_tut model then this is fine but with this mechanism, you will not be able to view other models data except the author.

            – Rarblack
            Mar 25 at 14:59













            Also got on that now ;) i guess i will re-think about this workflow. I also found out that im forced to use a form due to that the user needs to select a currency he want to pay with USD, EUR etc... ...

            – Venom
            Mar 25 at 15:29





            Also got on that now ;) i guess i will re-think about this workflow. I also found out that im forced to use a form due to that the user needs to select a currency he want to pay with USD, EUR etc... ...

            – Venom
            Mar 25 at 15:29













            I would suggest you re-think in naming too. After a selected amount of time, you will have bad times with names. Also, your mechanism needs improvements in the name of programming. In addition, if this question is done for you please consider of accepting an answer and upvoting it in order to make it easy for others to find and giving credit to the effort.

            – Rarblack
            Mar 25 at 18:10





            I would suggest you re-think in naming too. After a selected amount of time, you will have bad times with names. Also, your mechanism needs improvements in the name of programming. In addition, if this question is done for you please consider of accepting an answer and upvoting it in order to make it easy for others to find and giving credit to the effort.

            – Rarblack
            Mar 25 at 18:10













            0














            just create a "Post_Paid_Sell_Tut" object when a user requests to buy a post



             def post_sell_tut_buy(request, pk):
            post = get_object_or_404(Post_Sell_Tut, pk=pk)
            if request.user == post.author:
            messages.error(request, 'You cant buy your own Post!')
            return redirect('post_sell_tut_detail', pk=post.pk)
            else:
            try:
            # throws an exception if not bought yet
            Post_Paid_Sell_Tut.get(paying_user=request.user, post_sell_tut=post)
            messages.success(request, 'you allready have this post!')
            # ... other stuff

            except Post_Paid_Sell_Tut.DoesNotExist:
            # create Post_Paid_Sell_Tut object indicating that the user bought the post
            ppst = Post_Paid_Sell_Tut(paying_user=request.user,
            post_sell_tut=post, status="paid")
            ppst.save()
            messages.success(request, 'post is yours :)!')
            # ... other stuff





            share|improve this answer



























              0














              just create a "Post_Paid_Sell_Tut" object when a user requests to buy a post



               def post_sell_tut_buy(request, pk):
              post = get_object_or_404(Post_Sell_Tut, pk=pk)
              if request.user == post.author:
              messages.error(request, 'You cant buy your own Post!')
              return redirect('post_sell_tut_detail', pk=post.pk)
              else:
              try:
              # throws an exception if not bought yet
              Post_Paid_Sell_Tut.get(paying_user=request.user, post_sell_tut=post)
              messages.success(request, 'you allready have this post!')
              # ... other stuff

              except Post_Paid_Sell_Tut.DoesNotExist:
              # create Post_Paid_Sell_Tut object indicating that the user bought the post
              ppst = Post_Paid_Sell_Tut(paying_user=request.user,
              post_sell_tut=post, status="paid")
              ppst.save()
              messages.success(request, 'post is yours :)!')
              # ... other stuff





              share|improve this answer

























                0












                0








                0







                just create a "Post_Paid_Sell_Tut" object when a user requests to buy a post



                 def post_sell_tut_buy(request, pk):
                post = get_object_or_404(Post_Sell_Tut, pk=pk)
                if request.user == post.author:
                messages.error(request, 'You cant buy your own Post!')
                return redirect('post_sell_tut_detail', pk=post.pk)
                else:
                try:
                # throws an exception if not bought yet
                Post_Paid_Sell_Tut.get(paying_user=request.user, post_sell_tut=post)
                messages.success(request, 'you allready have this post!')
                # ... other stuff

                except Post_Paid_Sell_Tut.DoesNotExist:
                # create Post_Paid_Sell_Tut object indicating that the user bought the post
                ppst = Post_Paid_Sell_Tut(paying_user=request.user,
                post_sell_tut=post, status="paid")
                ppst.save()
                messages.success(request, 'post is yours :)!')
                # ... other stuff





                share|improve this answer













                just create a "Post_Paid_Sell_Tut" object when a user requests to buy a post



                 def post_sell_tut_buy(request, pk):
                post = get_object_or_404(Post_Sell_Tut, pk=pk)
                if request.user == post.author:
                messages.error(request, 'You cant buy your own Post!')
                return redirect('post_sell_tut_detail', pk=post.pk)
                else:
                try:
                # throws an exception if not bought yet
                Post_Paid_Sell_Tut.get(paying_user=request.user, post_sell_tut=post)
                messages.success(request, 'you allready have this post!')
                # ... other stuff

                except Post_Paid_Sell_Tut.DoesNotExist:
                # create Post_Paid_Sell_Tut object indicating that the user bought the post
                ppst = Post_Paid_Sell_Tut(paying_user=request.user,
                post_sell_tut=post, status="paid")
                ppst.save()
                messages.success(request, 'post is yours :)!')
                # ... other stuff






                share|improve this answer












                share|improve this answer



                share|improve this answer










                answered Mar 24 at 20:14









                Sina ParviziSina Parvizi

                32




                32



























                    draft saved

                    draft discarded
















































                    Thanks for contributing an answer to Stack Overflow!


                    • Please be sure to answer the question. Provide details and share your research!

                    But avoid


                    • Asking for help, clarification, or responding to other answers.

                    • Making statements based on opinion; back them up with references or personal experience.

                    To learn more, see our tips on writing great answers.




                    draft saved


                    draft discarded














                    StackExchange.ready(
                    function ()
                    StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f55327918%2fdjango-how-to-get-two-models-in-relation%23new-answer', 'question_page');

                    );

                    Post as a guest















                    Required, but never shown





















































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown

































                    Required, but never shown














                    Required, but never shown












                    Required, but never shown







                    Required, but never shown







                    Popular posts from this blog

                    Kamusi Yaliyomo Aina za kamusi | Muundo wa kamusi | Faida za kamusi | Dhima ya picha katika kamusi | Marejeo | Tazama pia | Viungo vya nje | UrambazajiKuhusu kamusiGo-SwahiliWiki-KamusiKamusi ya Kiswahili na Kiingerezakuihariri na kuongeza habari

                    SQL error code 1064 with creating Laravel foreign keysForeign key constraints: When to use ON UPDATE and ON DELETEDropping column with foreign key Laravel error: General error: 1025 Error on renameLaravel SQL Can't create tableLaravel Migration foreign key errorLaravel php artisan migrate:refresh giving a syntax errorSQLSTATE[42S01]: Base table or view already exists or Base table or view already exists: 1050 Tableerror in migrating laravel file to xampp serverSyntax error or access violation: 1064:syntax to use near 'unsigned not null, modelName varchar(191) not null, title varchar(191) not nLaravel cannot create new table field in mysqlLaravel 5.7:Last migration creates table but is not registered in the migration table

                    은진 송씨 목차 역사 본관 분파 인물 조선 왕실과의 인척 관계 집성촌 항렬자 인구 같이 보기 각주 둘러보기 메뉴은진 송씨세종실록 149권, 지리지 충청도 공주목 은진현