Django 表单未从模板提交
Posted
技术标签:
【中文标题】Django 表单未从模板提交【英文标题】:Django Form Not Submitting From Template 【发布时间】:2020-11-09 05:56:37 【问题描述】:我在提交此表单时遇到问题。我可以从管理仪表板提交表单,但不能从模板提交。我可能做错了什么?
models.py 文件:
from teamprofile.models import TeamProfile
from django.utils import timezone
from competition.models import CompetitionProfile
from datetime import datetime
from django.contrib.auth.models import User
class MatchProfile(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
competition = models.ManyToManyField(CompetitionProfile)
home_team = models.ForeignKey(TeamProfile, on_delete=models.CASCADE, related_name = 'home_team')
away_team = models.ForeignKey(TeamProfile, on_delete=models.CASCADE, related_name = 'away_team')
# start_time = models.DateField(blank=True, null=True)
def __str__(self):
return " vs ".format(self.home_team, self.away_team)
forms.py 文件:
from .models import MatchProfile
class CreateMatchForm(forms.ModelForm):
class Meta():
model = MatchProfile
fields = ('competition', 'home_team', 'away_team')
widgets =
'competition': forms.Select(attrs='class': 'uk-select'),
'home_team': forms.Select(attrs='class': 'uk-select' ),
'away_team': forms.Select(attrs='class': 'uk-select' ),
# 'start_time': forms.SelectDateWidget(),
views.py 文件:
from .forms import CreateMatchForm
from .models import MatchProfile
class MatchProfileCreateView(CreateView):
model = MatchProfile
success_url = reverse_lazy('home')
form_class = CreateMatchForm
def form_valid(self, form):
form.instance.owner = self.request.user
return super(MatchProfileCreateView, self).form_valid(form)
.html 文件:
<form class="uk-child-width-1-2@s uk-grid-small p-4" uk-grid method="POST">
<div> % csrf_token %
<h5 class="uk-text-bold mb-2"> Competiton Name </h5>
form.competition
<!-- <input type="text" class="uk-input" placeholder="Your name"> -->
</div>
<div>
<h5 class="uk-text-bold mb-2"> Home Teams </h5>
form.home_team
<!-- <input type="text" class="uk-input" placeholder="Your seccond"> -->
</div>
<div>
<h5 class="uk-text-bold mb-2"> Away Team </h5>
form.away_team
<!-- <input type="text" class="uk-input" placeholder="eliedaniels@gmail.com"> -->
</div>
<!-- <div>
<h5 class="uk-text-bold mb-2"> Organizer Contact</h5>
form.organizer_contact -->
<!-- <input type="text" class="uk-input" placeholder="+1 555 623 568 ">
</div> -->
<div class="uk-flex uk-flex-right p-4">
<button class="button soft-primary mr-2">Cancel</button>
<button type="submit" class="button primary">Create Match</button>
</div>
</form>
我肯定做错了事,但我似乎无法弄清楚。使用相同方法和模板构建的其他表单似乎可以正常工作。
我的终端会显示发出了一个 POST 请求,但它仍然不起作用
【问题讨论】:
当您说它不起作用时,您是什么意思?您没有在模板中显示任何表单错误 数据是否保存在后端?尝试在模板中提交表单,看看数据是否保存在管理页面中。 @IainShelvington,你是对的。打印错误后,我会发现小部件类型声明是问题所在。 【参考方案1】:我会发现错误来自 forms.py:
原来 POST 请求发送的字段输入与模型上声明的不同。
我改了
'competition': forms.Select(attrs='class': 'uk-select'),
.
到
'competition': forms.SelectMultiple(attrs='class': 'uk-select'),
不同之处在于 forms.SelectMultiple,因为模型是 ManyToManyField。
【讨论】:
以上是关于Django 表单未从模板提交的主要内容,如果未能解决你的问题,请参考以下文章