简体   繁体   English

使用form_class的Django CreateView未创建模型

[英]Django CreateView with form_class not creating model

I'm practicing from Two Scoops of Django book and i have a problem with form_class in CreateView. 我正在从Django的两个瓢练习,而CreateView中的form_class有问题。 If i'm using just fields in the CreateView it's saving the model, if i'm using the form_class it's not saving and not redirecting either. 如果我只使用CreateView中的字段,则保存模型,如果我使用form_class,则不保存也不重定向。

I'm using form_class for practicing validators. 我正在使用form_class来练习验证器。

views.py views.py

class FlavorCreateView(LoginRequiredMixin, CreateView):
    model = Flavor
    success_url = '/flavors/list/'
    template_name = 'flavor_create.html'
    success_msg = 'Flavor created.'
    form_class = FlavorForm
    # fields = ['title', 'slug', 'scoops_remaining']

    def form_valid(self, form):
        form.instance.created_by = self.request.user
        return super(FlavorCreateView, self).form_valid(form)

forms.py forms.py

class FlavorForm(forms.ModelForm):

    def __init__(self, *args, **kwargs):
        super(FlavorForm, self).__init__(*args, **kwargs)
        self.fields['title'].validators.append(validate_tasty)
        self.fields['slug'].validators.append(validate_tasty)

    class Meta:
        model = Flavor
        fields = ['title', 'slug', 'scoops_remaining']

validators.py validators.py

def validate_tasty(value):
    """
    Raise a ValidationError if the value doesn't start with the word 'Tasty'.
    """
    if not value.startswith('Tasty'):
        msg = 'Must start with Tasty'
        raise ValidationError(msg)

flavor_create.html flavor_create.html

{% extends 'base_flavor.html' %}

{% block content %}

<form action="" method="POST">{% csrf_token %}
    <p style="color: red;">{{ form.title.errors.as_text }}</p>
    {% for field in form  %}
        <p>{{ field.label }}: {{ field }}</p>
    {% endfor %}
    <button type="Submit">Salveaza</button>

</form>

    <a href="{% url 'flavors:list_flavor' %}">Return home</a>
{% endblock %}

Your code probably just works as expected (it looks that way): 您的代码可能像预期的那样工作(看起来像这样):

"it's not saving and not redirecting" := that is what happens when there is a validation error. “它不保存也不重定向”:=这是发生验证错误时发生的情况。

Override form_invalid as well and print some log output. 也覆盖form_invalid并打印一些日志输出。 Or just output the form errors in the template. 或者只是在模板中输出表单错误。

What happens in case of validation errors in Django is that the form is reloaded and the errors are added to the template context so that they can be rendered for the user. 在Django中发生验证错误的情况是,重新加载表单并将错误添加到模板上下文中,以便可以为用户呈现它们。


Just a side note: 附带说明:

As alternative to 作为替代

self.fields['title'].validators.append(validate_tasty)

You can simply add the validate_tasty method directly to your FlavorForm under the name clean_title and clean_slug . 你可以简单地添加validate_tasty直接的方法你FlavorForm名下clean_titleclean_slug This is a Django standard way for adding custom validation logic. 这是添加自定义验证逻辑的Django标准方法。

class FlavorForm(forms.ModelForm):

    def clean_title(self):
        # even if this is a required field, it might be missing
        # Django will check for required fields, no need to raise
        # that error here, but check for existence
        title = self.cleaned_data.get('title', None)
        if title and not value.startswith('Tasty'):
            msg = 'Must start with Tasty'
            raise ValidationError(msg):
        return title

    class Meta:
        model = Flavor
        fields = ['title', 'slug', 'scoops_remaining']

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM