Django表单保存

时间:2019-04-08 14:37:31

标签: python django django-models django-forms django-views

我想与您分享我的代码,以便找到解决方案。我有一个Django form。我只想在没有另一个具有相同数据的对象的情况下保存数据。换句话说,对象应该是唯一的。

如果该对象不存在,则将其保存,否则显示带有错误消息“该对象已存在且具有此功能”的表单。

这是我的模特

def guide_path(instance, filename):
    # file will be uploaded to MEDIA_ROOT/guides/<guide_id>
    new_filename = f'guides/{instance.site.id}'
    if instance.profile_type:
        new_filename += f'_{instance.profile_type}'
    if instance.profile_level:
        new_filename += f'_{instance.profile_level}'
    if instance.language:
        new_filename += f'_{instance.language}'
    name, ext = os.path.splitext(filename)
    if ext:
        new_filename += ext

    return new_filename


class UserGuide(models.Model):
    """ A class for storing user guides depending on profiles """
    objects = models.Manager()

    site = models.ForeignKey(WebApplication, on_delete=models.PROTECT, related_name='guides',
                             verbose_name=_('application'))
    file = models.FileField(verbose_name='file', upload_to=guide_path)
    profile_type = models.CharField(verbose_name=_('profile type'), choices=UserProfile.USER_TYPES, max_length=2,
                                    null=True, blank=True)
    profile_level = models.CharField(verbose_name=_('profile level'), choices=UserProfile.USER_ROLES, max_length=2,
                                     null=True, blank=True)
    language = models.CharField(verbose_name=_('language'), choices=settings.LANGUAGES, max_length=2, default='en')

    class Meta:
        verbose_name = _('user guide')
        verbose_name_plural = _('user guides')
        unique_together = ('site', 'profile_type', 'profile_level', 'language')

这是我的表格:

class UserGuideForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super().__init__(*args, **kwargs)

    class Meta:
        model = UserGuide
        fields = ['site', 'file', 'profile_type', 'profile_level', 'language']
        widgets = {
            'file': CustomFileInput(attrs={'class': 'clearablefileinput'}),
        }

这是我的观点:

class UserGuideUpdateView(UpdateView):
    """ Display a form to create a userguide

        **Context**

        ``subtitle``
            Title of the page

        **Template:**

        :template:`app/generic_form.html`
    """
    model = UserGuide
    form_class = UserGuideForm
    success_url = reverse_lazy('userguide-list')
    template_name = 'app/form_userguide.html'
    permission_required = 'app.change_userguide'

    def get_object(self, queryset=None):
        pk = self.kwargs.get('pk')
        return get_object_or_404(UserGuide, pk=pk)

    def get_title(self):
        return _('Edit user guide: ')

    def get_context_data(self, **kwargs):
        context = super(UserGuideUpdateView, self).get_context_data(**kwargs)
        context.update({
            'subtitle': self.get_title(),
        })
        return context

    def form_valid(self, form):
        site = form.cleaned_data['site']
        file = form.cleaned_data['file']
        profile_type = form.cleaned_data['profile_type']
        profile_level = form.cleaned_data['profile_level']
        language = form.cleaned_data['language']

        userguide = UserGuide.objects.filter(site=site.id, profile_type=profile_type, profile_level=profile_level, language=language)
        if userguide.exists():
            messages.error(self.request, _('A user guide for that profile and language already exists'))
            HttpResponseRedirect(self.template_name)
        else:
            pass
        return super().form_valid(form)

如果我的对象已经存在,如何添加条件,不保存表单并返回带有错误消息的表单?

谢谢

0 个答案:

没有答案