Why doesn’t the debug output in my views.py file get printed when there is a database constraint violation in Django?

I have three forms which have one submit button. The three forms represent employers, job listings and job listing categories.

When a user enters the employer name in the form, I want to check if it already exists in the database. If it does, I want to use that employer database row and have it tied to the newly added job listing.

Here are the relevant parts of my forms.py file:

from django.forms import modelform_factory
from .models import Employer, JobListing, Category_JobListing

EmployerForm = modelform_factory(Employer, fields=["name", "location", "short_bio", "website", "profile_picture"])
JobListingForm = modelform_factory(JobListing, fields=["job_title", "job_description", "job_requirements", "what_we_offer",
                                                        "due_date", "job_application_url"])
Category_JobListingForm = modelform_factory(Category_JobListing, fields=["category"])

models.py file:

class Employer(models.Model):
    # user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE)
    name = models.CharField(max_length=100, unique=True)
    location = models.CharField(max_length=MAXIMUM_LOCATION_LENGTH, choices=COUNTRY_CITY_CHOICES)
    short_bio = models.TextField(blank=True, null=True)
    website = models.URLField()
    profile_picture = models.ImageField(upload_to=get_upload_path_profile_picture, blank=True, null=True)

    def __str__(self):
        return self.name

class JobListing(models.Model):
    employer = models.ForeignKey(Employer, on_delete=models.CASCADE)
    job_title = models.CharField(max_length=100)
    job_description = models.TextField()
    job_requirements = models.TextField();
    what_we_offer = models.TextField();
    due_date = models.DateField();
    job_application_url = models.URLField()
    admin_approved = models.BooleanField(default=False)

    def __str__(self):
        return self.job_title

class Category_JobListing(models.Model):
    job_listing = models.ForeignKey(JobListing, on_delete=models.CASCADE)
    category = models.CharField(max_length=MAXIMUM_INTEREST_LENGTH, choices=INTEREST_CHOICES)

views.py file:

def submitJobListing(request):
    if request.method == "POST":
        employer_form = EmployerForm(request.POST, request.FILES)
        job_listing_form = JobListingForm(request.POST, request.FILES)
        category_job_listing_form = Category_JobListingForm(request.POST, request.FILES)

        if employer_form.is_valid() and job_listing_form.is_valid():
            #check if employer with that name already exists
            employer_name = str(request.POST.get("name", ""))
            print("Employer name is \"" + employer_name + "\"")
            employer_with_the_same_name = Employer.objects.filter(name=employer_name)
            print("Length of the employer with the same name is " + str(len(employer_with_the_same_name)))
            employer = None
            if (len(employer_with_the_same_name) != 0):
                employer = employer_with_the_same_name
            else:
                employer = employer_form.save()
            job_listing = job_listing_form.save(commit=False)
            job_listing.employer = employer
            job_listing.save()
            category_job_listing = category_job_listing_form.save(commit=False)
            category_job_listing.job_listing = job_listing
            category_job_listing.save()
            #return HttpResponseRedirect(reverse("employers:thank_you")) # TODO: Add this URL and template
            return HttpResponse("Your form has been successfully submitted.")
    else:
        employer_form = EmployerForm()
        job_listing_form = JobListingForm()
        category_job_listing_form = Category_JobListingForm()

    context = {
        "employer_form": employer_form,
        "job_listing_form": job_listing_form,
        "category_job_listing_form": category_job_listing_form
    }

    return render(request, 'employers/submit_job_listing.html', context)

submit_job_listing.html file:

<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ job_listing_form }}
{{ employer_form }}
{{ category_job_listing_form }}
<input type="submit" value= "Submit">
</form>

You can see that in my views.py file I have two print statements, which tell me the employer name from the POST request and the length of the QuerySet returned by the query with which I check for employers with that name.

Below is the output from my server when I added an employer "Test employer 2" (who didn't exist in the database at the time) and "Test Employer" (who did exist in the database at that point in time):

Watching for file changes with StatReloader
Performing system checks...

System check identified no issues (0 silenced).
October 17, 2020 - 16:32:14
Django version 3.1.2, using settings 'jobsforjuniorseu.settings'
Starting development server at http://127.0.0.1:8000/
Quit the server with CONTROL-C.
[17/Oct/2020 16:32:17] "GET / HTTP/1.1" 200 75
[17/Oct/2020 16:32:27] "GET /submit-job-listing/ HTTP/1.1" 200 5895945
[17/Oct/2020 16:34:02] "GET /submit-job-listing/ HTTP/1.1" 200 5895945
Employer name is "Test Employer 2"
Length of the employer with the same name is 0
[17/Oct/2020 16:35:01] "POST /submit-job-listing/ HTTP/1.1" 200 42
[17/Oct/2020 16:35:29] "GET /admin/ HTTP/1.1" 200 7534
[17/Oct/2020 16:35:32] "GET /admin/employers/employer/ HTTP/1.1" 200 7020
[17/Oct/2020 16:35:32] "GET /admin/jsi18n/ HTTP/1.1" 200 3187
[17/Oct/2020 16:35:36] "POST /admin/employers/employer/ HTTP/1.1" 200 6067
[17/Oct/2020 16:35:36] "GET /static/admin/js/cancel.js HTTP/1.1" 200 857
[17/Oct/2020 16:35:38] "POST /admin/employers/employer/ HTTP/1.1" 302 0
[17/Oct/2020 16:35:38] "GET /admin/employers/employer/ HTTP/1.1" 200 6937
[17/Oct/2020 16:35:38] "GET /admin/jsi18n/ HTTP/1.1" 200 3187
[17/Oct/2020 16:35:52] "GET /submit-job-listing/ HTTP/1.1" 200 5895945
[17/Oct/2020 16:37:03] "POST /submit-job-listing/ HTTP/1.1" 200 5896193
[17/Oct/2020 16:37:20] "POST /submit-job-listing/ HTTP/1.1" 200 5896193

You can see that the last two output lines are related to the POST request, but I don't get any of my print lines printed! This is strange to me. I do get the message "Employer with this Name already exists." printed out on the web page itself when I try to add "Test Employer" (the employer that's already in the database), but I don't understand why the print lines don't get printed. I tried using the shell and in the shell I get the correct objects from my query:

Python 3.8.3 (default, Jul  2 2020, 16:21:59) 
Type 'copyright', 'credits' or 'license' for more information
IPython 7.16.1 -- An enhanced Interactive Python. Type '?' for help.

In [1]: from employers.models import Employer                                   

In [2]: employer = Employer.objects.filter(name="Test Employer")                

In [3]: len(employer)                                                           
Out[3]: 1

In [4]: employer                                                                
Out[4]: <QuerySet [<Employer: Test Employer>]>

In [5]:                                                                         
Do you really want to exit ([y]/n)? y

Can someone shed some light on what is going on here, and, more importantly, how do I fix it?



Read more here: https://stackoverflow.com/questions/64405174/why-doesnt-the-debug-output-in-my-views-py-file-get-printed-when-there-is-a-dat

Content Attribution

This content was originally published by Eternal_Ether at Recent Questions - Stack Overflow, and is syndicated here via their RSS feed. You can read the original post over there.

%d bloggers like this: