有没有更好的方法来检查Django形式的外键关系是否存在?

时间:2019-05-09 22:14:56

标签: django django-models django-forms

我在表单的发布功能中进行了一次当前检查,以检查所选的货车是否已经在使用中。我想知道是否有更好的方法?我正在检查其他对象的字段是“ van_used”,而van_used从相关模型存储的属性(它是外键)是“ vanName”

这是我班上的帖子功能:

def post(self, request):
    """Take in user data, clean it, and then post it to the database."""
    form = self.form_class(request.POST) # pass in the user's that was submitted in form 

    if form.is_valid():
        trip = form.save(commit=False) # create an object so we can clean the data before saving it

        first_name = form.cleaned_data['first_name']
        last_name = form.cleaned_data['last_name']
        trip_start = form.cleaned_data['trip_start']
        trip_end = form.cleaned_data['trip_end']
        van_used = form.cleaned_data['van_used']

        if trips.objects.filter(van_used = form.cleaned_data['van_used']).exists():
            messages.warning(request, van_used.vanName + ' is currently in use. Pick another vehicle.' )
            return render(request, self.template_name, {'form': form})

请让我知道任何改进建议,目前,只有用户单击“提交”时,我进行的检查才开始。它将拒绝该表格并使它们重新开始。如果可能的话,我想对用户进行更多的警告。预先感谢。

0 个答案:

没有答案