Mohammad Al Blooshi
Mohammad Al Blooshi

Reputation: 109

Query to get foreign key PK

i am trying to carry out a check on the user once he want to go to the next page. the code will do a check on the User and its related model to see if the user has created the data. if it is created he will be redirected to next page else he will redirected to the create page. the similer query function will then be used to assign the other models foreign keys when form is being processed.

     class Startup ( models.Model ) :
         author = models.OneToOneField ( User , on_delete = models.CASCADE )
         startup_name = models.CharField ( 'Startup Name' , max_length = 32 , null = False , blank = False )

     @login_required
     def create_startupform(request) :
         q = User.objects.filter(Startup.startup_name.primary_key)
         if q.exists():
             return redirect ( 'str_detailedview' )
         else:
             form = startupform ( request.POST or None )
                 if form.is_valid ( ) :
                 instance = form.save (commit = False)
                 instance.author = request.user
                 instance.save()
                 return redirect ( 'str_detailedview' )
             else:
                 form = startupform()
             return render ( request , 'str_name.html' , { 'form' : form } )

Upvotes: 0

Views: 463

Answers (1)

Daniel Hepper
Daniel Hepper

Reputation: 29977

This line doesn't make any sense:

q = User.objects.filter(Startup.startup_name.primary_key)

If you want to check that a Startup object exists for a user, you can do that like this:

q = Startup.objects.filter(author=request.user)

Upvotes: 1

Related Questions