N
N
nurzhannogerbek2017-05-20 10:22:33
Django
nurzhannogerbek, 2017-05-20 10:22:33

How to attach DropzoneJS to a field in Django?

Hello! Please help to fasten Dropzone JS to the form.
There is a data model Article (Article) with two fields: description and image. Based on this model, I created a form where the user must create an article, specifying descriptions and uploading one or more images. Can't attach dropzonejs to image field.
models.py:

class Article(models.Model):
    description = models.TextField(_('Description'))
    image = models.FileField(upload_to='images//%Y/%m/%d/')

forms.py:
class ArticleForm(forms.ModelForm):
    class Meta:
        model = Article
        fields = ('description', 'image')

views.py:
def article_add(request):
    data = dict()
    if request.method == 'POST':
        article_form = ArticleForm(request.POST, request.FILES)
        if article_form.is_valid():
            article = article_form.save(commit=False)
            ******
            article.save()
            data['form_is_valid'] = True
            articles = Article.objects.all
            context = {'articles': articles}
            context.update(csrf(request))
            data['html_article'] = render_to_string('project/article_list.html', context)
        else:
            data['form_is_valid'] = False
    else:
        article_form = ArticleForm()
    context = {'article_form': article_form}
    data['html_article_form'] = render_to_string('project/article_add.html', context, request=request)
    return JsonResponse(data)

article_add.html:
{% load widget_tweaks %}

<form method="post" action="{% url 'article_add' %}" class="article-add-form dropzone">
    {% csrf_token %}

    {% for field in article_form %}
    <div class="form-group{% if field.errors %} has-danger{% endif %}">
       <label class="form-control-label" for="{{ field.id_for_label }}">{{ field.label }}</label>
       {% render_field field class="form-control" %}
       {% for error in field.errors %}
          <div class="form-control-feedback">{{ error }}</div>
       {% endfor %}
    </div>
    {% endfor %}

    <button type="submit">Submit</button>
</form>

<script type="text/javascript">
    $("#id_image").dropzone({ url: "{% url 'article_add' %}" });
</script>

Answer the question

In order to leave comments, you need to log in

1 answer(s)
L
Lemat, 2017-05-22
@Lemat

Hello.
Are there any js errors in the console?
dropzone.js included on the page?

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question