title: How to save a Model Form with a foreign key of User to django models
body: <p>I am trying to save user API keys to a Django Model with a foreign key of User such that each set of unique API keys has a unique User associated with them in the database.
  I want a api keys input form to appear when a user who clicks "account" if the user has no associated API keys and a message saying " Your keys have already been entered" if the user does have associated API keys.</p>
  
  <p>I am using the built in Django User Model and I have created my own Model Form in forms.py.</p>
  
  <p>I have tried including user in the Model form and Meta class to no avail.
  I have tried passing the keys and password as parameters to the model and form before saving.
  I have tried using instances of the form with commit set to False before adding the User to form.user.
  I've tried looking up the latest Django documentation but its fragmented and hard to follow.</p>
  
  <p>I'm purposefully leaving out imports unnecessary to this problem.</p>
  
  <p>This is my <strong>Models.py</strong>:</p>
  
  <pre><code>from django.db import models
  from django.contrib.auth.models import User
  from django.conf import settings
  
  # Create your models here.
  
  class UserApiDetails(models.Model):
      user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, default=None)
      key = models.CharField(max_length=32)
      password = models.CharField(max_length=32)
  
      def __str__(self):
          out = "key: " + str(self.key) + '\n' + "Password: " + str(self.password)
          return out
  
       # this is the method that checks if the user has existing API keys
      def keys_exist(self): 
          if UserApiDetails.objects.filter(pk=User).exists():
              return True
          else:
              return False
  
  </code></pre>
  
  <p>This is my <strong>forms.py</strong>:</p>
  
  <pre><code>from django import forms
  from .models import UserApiDetails
  
  class ApiKeysForm(forms.ModelForm):
      key = forms.CharField(max_length=200, label="Api Key")
      password = forms.CharField(max_length=200, widget=forms.PasswordInput, label="Api password")
  
      class Meta:
          model = UserApiDetails
          fields = {'password', 'key', }
  
  </code></pre>
  
  <p>This is my <strong>views.py</strong>:</p>
  
  <pre><code>from django.shortcuts import render, redirect
  from .models import UserApiDetails  # tables in database from models.py
  from django.http import JsonResponse, HttpResponse
  from django.contrib.auth.models import User
  from . import forms
  from .forms import ApiKeysForm  # the forms that will get data &amp; pass to views
  from django.template.loader import render_to_string
  
  import sys
  
  sys.path.insert(1, '/Development applications/python dev/TradingBot')
  # backend imports
  from Main import update, trade # methods in bot
  from API_comm import ConnAPI  # conn API class used to set keys &amp; session AUTH
  
  
  # Create your views here.
  
  def account_request(request):
      if request.method == 'POST':
  
          form = forms.ApiKeysForm(request.POST)
          if form.is_valid():
              key = form.cleaned_data.get('key')
              password = form.cleaned_data.get('password')
              instance = form.save(commit=False)
              instance.user = request.user
              instance.save()
              c = {
                  "key": key,
                  "password": password
              }
  
              result = ConnAPI.set_keys(key, password)  # gets the return from the set keys method
              messages.success(request, result)  # a toast to display if the api conn was successful or not
              return redirect("main:homepage")
      else:
          form = forms.ApiKeysForm(request.POST)
  
      context = {
          "form": form,
      }
  
      return render(request,
                    "main/account.html",
                    context)
  
  </code></pre>
  
  <p>This is my <strong>account.html template</strong>:</p>
  
  <pre><code>{% extends "main/header.html" %}
  {% block content%}
  
  {% if UserApiDetails.keys_exist %}
  
  &lt;div class="row1"&gt;
      &lt;h2&gt;Your Api Keys have already been entered.&lt;/h2&gt;
      &lt;div class="col s12 m8 14"&gt;
          &lt;p&gt;&lt;/p&gt;
      &lt;/div&gt;
  
  &lt;/div&gt;
  
  {% else %}
  
  &lt;div class="row2"&gt;
      &lt;form class="col s12 " action="/account/" method="POST"&gt;
          {% csrf_token %}
          {{form.as_p}}
  
          &lt;div class="col s12 m6 14"&gt;
              &lt;button class="btn" type="submit"&gt;Submit Api Keys&lt;/button&gt;
          &lt;/div&gt;
  
      &lt;/form&gt;
  &lt;/div&gt;
  
  {% endif %}
  
  {% endblock %}
  
  </code></pre>
  
  <p><em>edit</em> 
  I have managed to save the API details with Unique Users but i'm struggling to ensure that each user enters only 1 set of keys.</p>
  
  <p>When a user who does have API keys associated to their account clicks "account" the form still appears instead of the HTML with div ID of "Row1".</p>