Justin
Justin

Reputation: 1479

How to associate ForeignKey when using ModelForm to create an object?

I am trying to create a job board. I have the following models.py. The user creates a business once(but can create more than one), then posts multiple jobs from that business:

class Business(models.Model):
    user = models.ForeignKey(User, on_delete=models.CASCADE)
    name = models.CharField(max_length = 200)
    address = models.CharField(max_length = 200)
    city = models.CharField(max_length = 100)
    state = models.CharField(max_length = 50)
    zip_code = models.CharField(max_length = 10)
    phone_number = models.CharField(max_length = 10)

class Job(models.Model):
    business = models.ForeignKey(Business, on_delete= models.CASCADE)
    title = models.CharField(max_length = 200)
    description = models.TextField(blank = True)

I am trying to use ModelForm to create a "post job" view. forms.py:

from django.forms import ModelForm
from .models import Job

class JobForm(ModelForm):
    class Meta:
        model = Job
        fields = ['title', 'description']

Now, views.py:

from .models import Business, Job
from .forms import JobForm
def post_job(request):
    if request.method == 'POST':
        form = JobForm(request.POST
        if form.is_valid():
            # how do I associate a business with an instance of a job before saving the object?
            form.save()
    else:
        form = JobForm()
    return render(request, 'job/post_job.html', {'form':form})

I tried form.business = request.user.business thinking each Business was associated with a User but that did not work. Thanks for any help.

Upvotes: 1

Views: 47

Answers (1)

bmons
bmons

Reputation: 3392

    if request.method == 'POST':
        form = JobForm(request.POST)
        if form.is_valid():
            instance = form.save(commit=False)
            instance.business = Business.objects.get(user=request.user)
            instance.save()
    else:
        form = JobForm()

This way you can assign it.

Upvotes: 1

Related Questions