在将表单数据提交到数据库之前,在视图django中更改一些字段数据

时间:2017-08-22 14:00:12

标签: django django-forms django-templates django-views

您好我的表单是这样的,当我提交它去查看我附加时,我想更改例如在提交之前在名称字段中的字符串之间添加短划线。那么在我看来我该如何做到这一点?

  

Form.html

name = models.CharField(max_length=255, help_text='The name of this map.')

subtitle = models.CharField(max_length=255, null=True, blank=True,
                            help_text='If(unbolded)')

当我提交时,它会转到那个视图

  

View.py

def save_form_if_appropriate(self, attr):
        if self.request.method == 'POST':
            if self.site_acl >= self.acl.ADMIN or self.is_modifying_self(attr):
                if self.form.is_valid():
                    if attr == 'user':
                        obj = self.form.save(commit=False)
                        # this way we can keep record of the users creator.
                        obj.parent_id = self.request.user
                        if hasattr(obj, 'user_type') and obj.user_type != 'pro':
                            obj.sub_users_allowed = 0
                        obj.save()
                    else:
                        self.form.save()

                    messages.success(self.request, 'Thing saved.')
                    return True
                else:
                    messages.warning(self.request, self.form.errors)
                    # messages.warning(self.request, 'Thing was invalid, and couldn\'t be saved.')
            else:
                messages.warning(self.request, 'You don\t have permission to save that thing.')
        return False

1 个答案:

答案 0 :(得分:0)

def save_form_if_appropriate(self, attr):
    if not self.request.method == 'POST':
        return False

    if not (self.site_acl >= self.acl.ADMIN or self.is_modifying_self(attr)):
        messages.warning(self.request, 'You don\t have permission to save that thing.')
        return False

    if not self.form.is_valid():
        messages.warning(self.request, self.form.errors)
        return False

    obj = self.form.save(commit=False)
    if attr == 'user':
        # this way we can keep record of the users creator.
        obj.parent_id = self.request.user
        if hasattr(obj, 'user_type') and obj.user_type != 'pro':
            obj.sub_users_allowed = 0

    # Here you can do whatever you want on the object
    # For example joining string in names
    obj.name = '-'.join(obj.name.split(' '))

    obj.save()
    messages.success(self.request, 'Thing saved.')
    return True