0

I have problem with editing form in django. Pls can someone help me?

I have form with 2 fields: description and image. By this form users can edit currect article data. For example add new several images to article or update/delete one of the currect image. To create image field I used django-multiupload app. Also I load data to server by ajax. I tried next code but it didnt show me currect images in image field. Only descrtiption field works fine and show me currect data. How to fix this problem?

models.py:

class Article(models.Model):
    project = models.ForeignKey(Project, on_delete=models.CASCADE)
    description = models.TextField(_('Description'))

class Image(models.Model):
    article= models.ForeignKey(Article, on_delete=models.CASCADE)
    image = models.FileField(_('Image'), upload_to='images/%Y/%m/%d/')

forms.py:

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

    image = MultiFileField()

    def save(self, commit=True):
        instance = super(ArticleForm, self).save(commit)
        return instance

views.py:

def article_edit(request, article_id):
    data = dict()
    article= get_object_or_404(Article, pk=article_id)
    if request.method == 'POST':
        article_form = ArticleForm(request.POST, request.FILES, instance=article)
        if article_form.is_valid():
            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(instance=article)
    context = {'article_form': article_form}
    data['html_article_form'] = render_to_string('project/article_edit.html', context, request=request)
    return JsonResponse(data)

JS:

$(function () {
    var loadForm = function () {
        var btn = $(this);
        $.ajax({
            url: btn.attr("data-url"),
            type: 'get',
            dataType: 'json',
            beforeSend: function () {
                $("#modal").modal("show");
            },
            success: function (data) {
                $("#modal .modal-content").html(data.html_article_form);
            }
        });
    };

    var saveForm = function () {
        var form = $(this);
        var dataForm = new FormData(form.get(0));
        $.ajax({
            url: form.attr("action"),
            data: dataForm 
            type: form.attr("method"),
            dataType: 'json',
            success: function (data) {
                if (data.form_is_valid) {
                    $("#article-list").html(data.html_article);
                    $("#modal").modal("hide");
                }
                else {
                    $("#modal .modal-content").html(data.html_article_form);
                }
            }
        });
        return false;
    };

    // Create Article
    $("#article-add-button").click(loadForm);
    $("#modal").on("submit", ".js-article-add-form", saveForm);

    // Update Article
    $("#article-list").on("click", "#js-edit-article-button", loadForm);
    $("#modal").on("submit", ".js-article-edit-form", saveForm);
});

article_edit:

{% load widget_tweaks %}

<form method="post" enctype="multipart/form-data" action="{% url 'article_edit' %}" class="js-article-edit-form">
    {% 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>
Nurzhan Nogerbek
  • 4,806
  • 16
  • 87
  • 193
  • It's not clear from this code how the display is done. – e4c5 May 24 '17 at 11:37
  • I add JS/AJAX code and article_edit template but I dont think that they will give you new information. Now its full code. Do you have any ideas? My image field is not Django's standard field. Its a custom field. I think problem because of that. `instance=article` maybe dont see that image field. So I want to know is there any way to field this problem. – Nurzhan Nogerbek May 24 '17 at 11:44
  • Yes, it doesn't shed any light. But what I am reallly confused about is why are you sending a whole form as the json response instead of a simple OK/Fail? wouldn't it be better to have the form as part of the main html template? – e4c5 May 24 '17 at 12:01
  • I too do not understand why ajax is used here – mbieren May 24 '17 at 12:09
  • I have modal window and load different content (in my case different forms) with ajax in different situations. Lets say form to add, form to edit, and some other forms. I hope you understand me. – Nurzhan Nogerbek May 24 '17 at 12:11
  • That's a bit clearer, but simply having all the modals in the main page itself and displaying them as needed based on simple JSON responses is a lot easier – e4c5 May 24 '17 at 12:44

0 Answers0