在基于功能的视图中清理数据 - request.POST

时间:2017-09-27 03:21:36

标签: python python-3.x django-models django-forms

执行POST操作后,我很难清除某些表单的字段

我有以下型号:

class Article(models.Model):
    author = models.ForeignKey(
        settings.AUTH_USER_MODEL,
        on_delete=models.CASCADE
    )

    title = models.CharField(max_length=120)
    content = models.TextField()
    updated = models.DateTimeField(auto_now=True, auto_now_add=False)
    timestamp = models.DateTimeField(auto_now=False, auto_now_add=True)

    image = models.ImageField(
        upload_to='article_images',
        blank=True,
        null=True,
        verbose_name='Image'
    )

    def get_absolute_url(self):
        # return "/articles/%s/" %(self.slug)
        return reverse("articles:detail", kwargs={'id': self.id})

    def __str__(self):
        return self.title

调用我模型的表单是:

class ArticleForm(forms.ModelForm):
    content = forms.CharField(widget=forms.Textarea)
    ad = "Nuevo artículo"
    class Meta:
        model = Article
        fields = ['title', 'content', 'image']

我在视图中创建了以下方式的文章实例:

def article_create(request):
        form = ArticleForm(request.POST or None)
        if form.is_valid():
            instance = form.save(commit=False)
            form.instance.author = request.user
            print(form.cleaned_data.get('title'))
            print(form.cleaned_data.get('content'))
            instance.save()
            # Cleaning?
            form.cleaned_data.get('title')
            form.cleaned_data.get('title')

我的模板是:

{% load bootstrap3 %}
{% bootstrap_css %}
{% bootstrap_javascript %}
{% load staticfiles %}
{% block title_tag %}Crear un artículo en {{ block.super }}{% endblock %}


{% block body_content %}
<div class="offert-form">
    <h1>
    {% if not form.instance.slug %}
        {{ form.ad }}
      {% else %}
      Actualizar artículo
      {% endif %}
    </h1>

    <form class="stayhost" method="POST" enctype="multipart/form-data">
    <div class="head">
        <div class="ofert-icon">
          <img src="{% static 'img/icons/lang.svg' %}" alt="">
          <div class="title">
            <h2>Contenidos</h2>
            <span>Crear un Artículo</span>
          </div>
        </div>
        <div class="submit-button-cont">
            <div>
              <input type="image" src="{% static 'img/icons/ok.png' %}" alt="Submit" width="48" height="48">
              <input type="submit" value="Guardar" class="submit-button">
            </div>
        </div>
    </div>
    {% csrf_token %}
        <div class="formgroup">
        {% bootstrap_field form.title %}
        </div>
         <div class="formgroup">
        {% bootstrap_field form.content %}
        </div>
        <div class="formgroup">
        {% bootstrap_field form.image %}
        </div>
    </form>
</div>
{% endblock %}

当我从表单中进行POST时,字段不会在表单中清除。 如何清除表单中的标题,内容和图像字段?

1 个答案:

答案 0 :(得分:1)

  1. 使用instance.author = request.user代替form.instance.author = request.user
  2. 您可以使用clean_<fild>功能进行清洁。这是an example from documentation