Сбой ограничения NOT NULL: projects_property_applications.landlord - PullRequest
0 голосов
/ 08 апреля 2020

Мое приложение позволяет Tenants подать заявку на Properties, которые указаны на сайте Landlords. Когда я пытаюсь подать заявку, я получаю следующую ошибку

Traceback (most recent call last):
  File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner
    response = get_response(request)
  File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response
    response = self.process_exception_by_middleware(e, request)
  File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response
    response = wrapped_callback(request, *callback_args, **callback_kwargs)
  File "C:\Users\Maksims\Desktop\RentSpot\2020-ca472-template-repo\src\projects\views.py", line 22, in property_apply
    link.save()
  File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 746, in save
    force_update=force_update, update_fields=update_fields)
  File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 784, in save_base
    force_update, using, update_fields,
  File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 887, in _save_table
    results = self._do_insert(cls._base_manager, using, fields, returning_fields, raw)
  File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\base.py", line 926, in _do_insert
    using=using, raw=raw,
  File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\manager.py", line 82, in manager_method
    return getattr(self.get_queryset(), name)(*args, **kwargs)
  File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\query.py", line 1204, in _insert
    return query.get_compiler(using=using).execute_sql(returning_fields)
  File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\models\sql\compiler.py", line 1384, in execute_sql
    cursor.execute(sql, params)
  File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 100, in execute
    return super().execute(sql, params)
  File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 68, in execute
    return self._execute_with_wrappers(sql, params, many=False, executor=self._execute)
  File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 77, in _execute_with_wrappers
    return executor(sql, params, many, context)
  File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\utils.py", line 90, in __exit__
    raise dj_exc_value.with_traceback(traceback) from exc_value
  File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\utils.py", line 86, in _execute
    return self.cursor.execute(sql, params)
  File "C:\Users\Maksims\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute
    return Database.Cursor.execute(self, query, params)
django.db.utils.IntegrityError: NOT NULL constraint failed: projects_property_applications.landlord
[08/Apr/2020 14:42:39] "POST /projects/application_submit/2/ HTTP/1.1" 500 147389

models.py - пользователи

from django.db import models
from django.contrib.auth.models import User
from PIL import Image

usertypechoices = [(True,'Landlord'),(False,'Tenant')]


class Landlord_Profile(models.Model):
    landlord = models.OneToOneField(User, on_delete=models.CASCADE)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    is_landlord = models.BooleanField(choices=usertypechoices,default=True)


    def __str__(self):
        return f'{self.landlord.username} Landlord Profile'

models.py - проекты

from django.db import models
from PIL import Image
from django.contrib.auth.models import User
from django.contrib.auth import get_user_model
from django.conf import settings
from users.models import Landlord_Profile, Tenant_Profile


class Property_Applications(models.Model):
    property_owner = models.OneToOneField(Landlord_Profile,db_column='landlord', on_delete=models.CASCADE )
    tenant = models.ForeignKey(User, on_delete=models.CASCADE)
    listing = models.ForeignKey('Properties', on_delete=models.CASCADE)
    app_description = models.TextField(null=True)

просмотров. py - проекты

from django.shortcuts import render, redirect
from projects.models import Properties, Property_Applications, Property_Reviews
from django.contrib.auth.decorators import login_required
from django.contrib import messages
from .forms import CreatingListingForm, ListingApplicationForm

def property_apply(request, pk):
    project = Properties.objects.get(pk=pk)
    applyButton = ListingApplicationForm(request.POST)
    propertyReview = Property_Reviews.objects.filter(property=project)
    if request.method == "POST":
        link = applyButton.save(commit=False)
        link.tenant=request.user
        link.listing=project
        link.save()
        messages.success(request, f'You have applied!')
        return redirect('/portal/')
    else:
        link = applyButton
    context = {'project': project, 'applyButton': link, 'propertyReview': propertyReview}
    return render(request, 'application_submit.html', context)

forms.py - проекты

from .models import Properties, Property_Applications
from django.forms import ModelForm
from django import forms
from django.contrib.auth.models import User

# class to allow user update their own data
class CreatingListingForm(forms.ModelForm):
    class Meta:
        model = Properties
        fields = ['address', 'rentPrice','description','bedRooms','bathRoom','tenantCondtions','image']

class ListingApplicationForm(forms.ModelForm):
    class Meta:
        model = Property_Applications
        fields = ['app_description']

1 Ответ

0 голосов
/ 08 апреля 2020

Проблема в том, что вы пытаетесь сохранить экземпляр Property_Applications в базе данных, но вы еще не установили его поле property_owner.

Обновите представление, чтобы назначить property_owner своему экземпляру перед сохранением:

def property_apply(request, pk):
    ...
    if request.method == "POST":
        link = applyButton.save(commit=False)
        ...
        link.property_owner = project.owner  # or where ever you get the property owner/landlord data
        link.save()
    ...

...