0

I am creating a job board site. Right now I can successfully register an Employer but when I try to create a job listing while logged in as an Employer, the data from the form does not save to the database. I have the following models.py:

from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from django.http import HttpResponse


# Create your models here.
class Employer(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)


    def __str__(self):
        return self.user.first_name


@receiver(post_save, sender=User)
def create_employer(sender, instance, created, **kwargs):
    if created:
        Employer.objects.create(user=instance)

@receiver(post_save, sender=User)
def save_employer(sender, instance, **kwargs):
    instance.employer.save()

class Job(models.Model):
    poster = models.ForeignKey(Employer, on_delete=models.CASCADE)
    job_title = models.CharField(max_length=50)
    establishment_name = models.CharField(max_length = 50)
    details = models.TextField(max_length = 2000)
    salary = models.CharField(max_length = 20)
    address = models.CharField(max_length = 50)
    state = models.CharField(max_length = 20)
    zip_code = models.CharField(max_length = 10)


    def __str__(self):
        return self.job_title + " - " + self.establishment_name \
               + ", " + self.poster.user.first_name + " " +self.poster.user.last_name

A user can register as an employer just fine, but I am having problems getting Jobs to save to the database. Once a user registers/logs in as an employer they are redirected to employer_home.html, where an employer can post a job:

{% extends 'core/base.html' %}


{% block body %}
    <h1>Post a Job</h1>

    <form>
        {% csrf_token %}
        {{ form.as_p }}
        <button type="submit">Post</button>


    </form>
{% endblock %}

Here is my forms.py:

from django.forms import ModelForm
from .models import Job
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm


class EmployerSignupForm(UserCreationForm):
    class Meta:
        model = User
        fields =  ('first_name',
                   'last_name',
                   'email',
                   'username',
                   'password1',
                   'password2',)

class JobPostForm(ModelForm):
    class Meta:
        model = Job
        fields= ('job_title',
               'establishment_name',
               'salary',
               'address',
               'state',
               'zip_code',
               )

and here is my employer_view(view to handle Job form):

def employer_home(request):
    if request.method == 'POST':
        form = JobPostForm(request.POST)
        if form.is_valid():
            form.save()
            return HttpResponse('Working!')
    else:
        form = JobPostForm()
    return render(request, 'core/employer_home.html', {'form': form})

employer_home.html displays a form with no problem, but when the form is submitted none of the data is saved to the database and the return HttpResponse('Working!') is never executed, it simply reloads the empty form. Does anyone know how to fix this?

rajkris
  • 1,775
  • 1
  • 9
  • 16

2 Answers2

0

Try <form method="post"> in your html template. By default, the method is get.

aquaman
  • 1,523
  • 5
  • 20
  • 39
  • I always seem to think the problem is in the wrong file, I was sure there was something wrong with my views.py. Thanks, @aquaman ill accept your answer when I am allowed to. – Justin O'Brien Oct 22 '17 at 16:44
  • do you know how I would set the `poster` value @aquaman, as the form is now submitting properly but I am getting the error: "NOT NULL constraint failed: core_job.poster_id"? – Justin O'Brien Oct 22 '17 at 16:45
0

Add method="POST" in your form. In your view do this:

def employer_home(request):
if request.method == 'POST':
    form = JobPostForm(request.POST)
    if form.is_valid():
        job_object = form.save(commit=False)
        job_object.poster = poster_object
        job_object.save()
        return HttpResponse('Working!')
else:
    form = JobPostForm()
return render(request, 'core/employer_home.html', {'form': form})

A good example is shown here: example

rajkris
  • 1,775
  • 1
  • 9
  • 16
  • Thank you for your answer, but where is the poster_object coming from? – Justin O'Brien Oct 22 '17 at 17:13
  • I think this is the issue which is causing the error. In your "Job" model you have a field "poster " which is a Fkey. So when saving, the form the expects a poster object since it is not set as null=True or blank=True. So in your view you are missing a query to fetch the corresponding poster object. The model does not get saved on calling form.save(commit-=False). The object get only saved when the save is called. – rajkris Oct 22 '17 at 17:16
  • Nevermind, I figured out the poster_object part, thanks for your answer it is working! – Justin O'Brien Oct 22 '17 at 17:17
  • Hope it helped. Thanks – rajkris Oct 22 '17 at 17:18