我能够将表单呈现到html,输入数据并提交它,但我得到了NOT NULL约束失败。如我在意见中所述,是不是所有者已分配给其各自所有者?我不知道这里有什么问题请帮忙!
<小时/> 的模型
class Car(models.Model):
owner = models.ForeignKey('auth.User', on_delete=models.CASCADE)
name = models.CharField(max_length=100)
model = models.CharField(max_length=100)
description = models.TextField()
image = models.ImageField(upload_to=upload_image_path, null=True, blank=True)
created = models.DateField(auto_now_add=True)
updated = models.DateField(auto_now_add=False)
mileage = models.IntegerField()
open_market_value = models.DecimalField(max_digits=12, decimal_places=2)
depreciation = models.DecimalField(max_digits=10, decimal_places=2)
down_payment = models.DecimalField(max_digits=10, decimal_places=2)
road_tax = models.DecimalField(max_digits=8, decimal_places=2)
installment = models.DecimalField(max_digits=8, decimal_places=2)
objects = models.Manager()
def __str__(self):
return self.name
视图
class CarCreate(CreateView):
model = Car
fields = [
'name', 'model',
'description', 'image',
'updated', 'mileage',
'open_market_value', 'depreciation',
'down_payment', 'road_tax',
'installment']
template_name = 'cars/create_car.html'
def form_valid(self, form):
form.instance.created_by = self.request.user
return super().form_valid(form)
HTML
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<!-- Default form contact -->
<form action="{% url 'cars:create' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{form | crispy}}
<input type="submit" value="save">
</form>
<!-- Default form contact -->
{% endblock %}
答案 0 :(得分:0)
这很可能是因为owner
是模型Car
中的必填字段,但您尚未将其包含在fields
的{{1}}中。
答案 1 :(得分:0)
您的模型具有来自&#39; django.auth&#39;的用户模型的外键。当你试图保存&#39; Car&#39;模型,因为没有提到“&#39;所有者”的对象。模型的字段,它显示错误。所以,您可能希望明确提及它。
你可以这样做。假设您有“CarForm”,那么您的模型表格就是Car&#39; Car&#39;模型。
user = request.user
car_form = CarForm(request.POST)
if car_form.is_valid():
car = car_form.save(False)
car.owner = user
car.save()