我试着开发一个简单的输入表单来保存渔船的存款。渔船和渔网都是数据库中的表。提交表单时没有错误,但后台没有发生任何事情。我使用PostgreSQL数据库和PgAdmin来获得见解。我有点卡住了,因为这是我第一次使用Django。
我尝试将dep_id字段添加到表单中,但没有任何更改。
[forms.py]
from django import forms
from django.forms import ModelForm
from myapp.models import Deposit
class UploadForm(ModelForm):
dep_date = forms.DateField()
harbour = forms.CharField()
vessel = forms.ModelChoiceField(queryset=Vessel.objects.all())
net = forms.ModelChoiceField(queryset=Net.objects.all())
amount = forms.DecimalField()
class Meta:
model = Deposit
fields = ['dep_date', 'harbour',
'vessel', 'net',
'amount']
[models.py]
from django.db import models
class Vessel(models.Model):
VID = models.IntegerField(primary_key=True, default=None)
vessel_name = models.CharField(max_length=100)
flag = models.CharField(max_length=100)
registration_number = models.CharField(max_length=100)
WIN = models.CharField(max_length=100)
IRCS = models.CharField(max_length=100)
vessel_type = models.CharField(max_length=250)
fishing_methods = models.CharField(max_length=255)
length = models.DecimalField(default=0, max_digits=5, decimal_places=2)
auth_period_from = models.CharField(max_length=100)
auth_period_to = models.CharField(max_length=100)
class Net(models.Model):
net_id = models.IntegerField(primary_key=True, default = None)
prod_date = models.DateField()
weight = models.DecimalField(default=0, max_digits=6, decimal_places=2)
material = models.CharField(max_length=100)
fishing_type = models.CharField(max_length=100, default=None)
class Deposit(models.Model):
dep_id = models.BigAutoField(primary_key=True, default=None)
dep_date = models.DateField()
harbour = models.CharField(max_length=100)
vessel = models.ForeignKey(Vessel, to_field='VID', on_delete=models.CASCADE)
net = models.ForeignKey(Net, to_field='net_id', on_delete=models.CASCADE)
amount = models.DecimalField(default=0, max_digits=5, decimal_places=2)
[views.py]
from django.shortcuts import render, redirect
from .models import Vessel
from .forms import UploadForm
def put_deposit(request):
if request.POST:
form = UploadForm(request.POST)
print(request)
if form.is_valid():
form.save()
redirect(index)
return render(request, 'upload.html', {'form' : UploadForm})
[上传. html]
<p> Upload </p>
<form method="POST" action="{% url 'put_deposit' %}" enctype="multipart/form-data">
{% csrf_token %}
{{form}}
<button> Submit </button>
</form>
也许我有任何类型的依赖性错误或它是一个关键的问题?
2条答案
按热度按时间5sxhfpxr1#
您使用的是ModelForm,但随后将模型中已有的字段添加到表单中,就像它是一个常规的form一样。您 * 可以 * 通过这样做 * 将 * 额外 * 字段添加到ModelForm中,但由于您添加的是 * 相同 * 的字段,这可能就是它没有进行验证的原因。
建议:试试
(1)What @米洛已经建议打印出
form.errors
来查看表单是否确实有效,(2)将表单更改为:
(3)此外,虽然我不认为这是导致错误的原因,但您的视图存在一些问题。请尝试:
yxyvkwin2#
这更多的是一个疑难解答建议,但很难在注解中显示。您的表单可能由于某种原因而未进行验证-添加以下内容以查看是否存在错误: