I have a model (Letter) with a foreign key, pointing to another model (Company) with a foreign key. Below is a simple schema from models.py
from django.contrib.auth.models import User
class Company (models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, editable=False)
date_created = models.DateField(default=timezone.now, null=True)
company_name = models.CharField(max_length=100, null=True)
class Letter(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='letterhead_user', null=True)
company = models.ForeignKey(Company, related_name = "company_letter", on_delete=models.CASCADE, null=True)
subject = models.CharField(max_length=5000, null=True)
body = models.TextField()
I have created a form where users can create Letters with the model through ModelForm.
class LetterForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
super(LetterForm, self).__init__(*args, **kwargs)
self.fields['company'].widget.attrs = {'class': 'input',}
self.fields['subject'].widget.attrs = {'class': 'input', 'placeholder': 'RE: ...'}
self.fields['body'].widget.attrs = {'class': 'textarea',}
class Meta:
model = Letter
fields = ('company', 'subject', 'body',)
The View:
def letter_form (request):
form = LetterForm()
if request.method == 'POST':
form = LetterForm(request.POST, request.FILES)
form.instance.user = request.user
if form.is_valid():
form.save()
return redirect('letter')
Currently, when the user is presented with a form to create a Letter, on the Company field, all the companies from all the users appear. See the pic below:
I would like only the companies that the User has created to appear in the drop-down, not all companies from all users. Or to be able to select the first company that the User has created.