Django - 创建图库,然后将照片添加到图库

时间:2015-07-14 21:37:15

标签: django dropzone.js

我正在使用Django 1.8和Dropzone JS文件上传包

我想添加一个图库(我的画廊被称为'喷泉')然后将照片添加到图库。

这是我的工作流程:

  1. 使用模型表单添加图库
  2. 重定向到图库视图
  3. 图库视图有一个自动生成的链接,可转到photo_upload视图,以便用户可以将照片添加到新图库
  4. photo_upload视图/模板使用Dropzone javascript加载项
  5. 照片通过dropzone上传,照片详细信息写入照片模型/表格,包括新图库ID作为外键
  6. 当我没有从图库中传递pk时,我可以使用Dropzone成功上传照片。所以我很确定这不是我的问题。

    但是,当我输入url时,photo_upload视图给出了一个错误,如下所示:

    http://localhost:8000/photo_upload/17/ 
    

    此链接对应于urls.py中的网址,它会找到photo_upload视图,但在解析视图时会产生以下消息。

    NoReverseMatch at /photo_upload/17/
    
    Reverse for 'photo_upload' with arguments '()' and keyword arguments '{}' not found. 1 pattern(s) tried: ['photo_upload/(?P<id>\\d+)/$']
    

    我正在寻找有关为什么photo_upload视图发出此错误的任何见解。任何其他提示,以使这更好地赞赏。

    我的模特:

    class Fountains(models.Model):
        foun_name = models.CharField(max_length=100, blank=True, null=True)
        foun_desc = models.TextField(blank=True, null=True)
        foun_address = models.CharField(max_length = 100, blank=True, null=True)
        foun_lat = models.CharField(max_length=20, blank=True, null=True)
        foun_lon = models.CharField(max_length=20, blank=True, null=True)
        created = models.DateTimeField(auto_now_add=True)
        modified = models.DateTimeField(auto_now=True)
    
        class Meta:
            managed = True
            db_table = 'fountains'
    
    class Photos(models.Model):
        filename = models.ImageField(upload_to='.')
        ext = models.CharField(max_length=5, blank=True, null=True)
        desc = models.TextField(blank=True, null=True)
        fountain_id = models.IntegerField(blank=True, null=True)
        #fountain = models.ForeignKey('Fountains')
        user_id = models.IntegerField(blank=True, null=True)
        tag_count = models.IntegerField(blank=True, null=True)
        photos_tag_count = models.IntegerField(blank=True, null=True)
        comment_count = models.IntegerField(blank=True, null=True)
        created = models.DateTimeField(auto_now_add=True)
        modified = models.DateTimeField(auto_now=True)
    
        class Meta:
            managed = True
            db_table = 'photos'
    

    我的表格:

    class PhotoForm(forms.Form):
        filename = forms.FileField()
        fountain_id = forms.IntegerField('fountain')
        class Meta:
            model = Photos
    
    class FountainForm(ModelForm):
        class Meta:
            model = Fountains
            fields = [
                'foun_name', 
                'foun_desc', 
                'foun_address', 
                'foun_lat',
                'foun_lon'
                ]
            labels = {
                'foun_name': _('name'), 
                'foun_desc': _('description'), 
                'foun_address': _('street address'),
                'foun_lat': _('lat'),
                'foun_lon': _('lon')
                }
    

    我的观点:

    这是添加图库的视图:

    def fountain_add(request):
        if request.method == 'POST':
            form = FountainForm(request.POST)
            if form.is_valid():
                new_fountain = form.save()
                return HttpResponseRedirect(reverse(fountain, args=(new_fountain.pk,)))
        else:        
            form = FountainForm()
    
        return render(request, "app/fountain_add.html", {'form': form})
    

    这是重定向到新图库视图的视图:

    def fountain(request, id):
        assert isinstance(request, HttpRequest)
        fountain = Fountains.objects.get(id=int(id))
        context_dict = {'fountain': fountain}
        return render(
            request,
            'app/fountain.html',
            context_dict,
            context_instance = RequestContext(request)
        )
    

    Photo_upload视图:

    @login_required
    def photo_upload(request, id):
    #def photo_upload(request):
        fountain = Fountains.objects.get(id=int(id))
        if request.method == 'POST':
            form = PhotoUploadForm(request.POST, request.FILES)
            if form.is_valid():         
                new_photo = Photos(filename = request.FILES['filename'])
                new_photo.save()
                return HttpResponse('Image upload succeeded.')
        else:
            form = PhotoUploadForm()
    
        data = {'form': form}
        return render_to_response('app/photo_upload.html', data, context_instance=RequestContext(request))
    

    我的模板:

    这是包含photo_upload链接的图库视图的模板:

    {% extends "app/layout.html" %}
    {% block content %}
        <h1>Fountain Details</h1>
        <div style="width:600px">
            <p>Name: {{ fountain.foun_name }}</p>
            <p>Desc: {{ fountain.foun_desc }}</p>
            <p>Address: {{ fountain.foun_address }}</p>
            <p>Lat: {{ fountain.foun_lat }}</p>
            <p>Lon: {{ fountain.foun_lon }}</p>
            <p><a href="/photo_upload/{{ fountain.id }}/"}>Upload photos</a></p>
        </div>
    {% endblock content %}
    

    我的photo_upload模板。这里面有dropzone.js:

     {% extends "app/layout.html" %}
    
        {% block content %}
    
        <h1>Photo Upload</h1>
        <p>Fountain: {{ fountain.foun_name }}</p>
    
        {% load staticfiles %}
        <link href="{% static 'dropzone/dropzone.css' %}" rel="stylesheet">
    
         <form action="{% url "photo_upload" %}" class="dropzone" id="myDropzone"  method="post" enctype="multipart/form-data">
            {% csrf_token %}
            <div class="fallback">
                <p><input name="fountain" type="hidden" /></p>
                <p><input name="file" type="file" multiple /></p>
                <p><input type="submit" value="Upload" /></p>
            </div>
        </form>
    
        <script src="{% static 'dropzone/dropzone.js' %}"></script>
    
        <script type="text/javascript">
            Dropzone.options.myDropzone = {
                autoProcessQueue: false,
                paramName: "filename",
                addRemoveLinks: true,
    
                //parallelUploads: 1,
                init: function () {
                    var submitButton = document.querySelector("#submit_photos")
                    myDropzone = this;
                    submitButton.addEventListener("click", function () {
                        myDropzone.processQueue();
                    });
                    myDropzone.on("complete", function (file) {
                        myDropzone.removeFile(file);
                    });
                }
            };
        </script>
    
        <button id="submit_photos">
            Submit all files
        </button>
    
    {% endblock content %}
    

    这些是相关的网址:

    url(r'^fountain_add', 'app.views.fountain_add', name='fountain_add'),
    url(r'^fountain/(?P<id>\d+)/$', 'app.views.fountain', name='fountain'),
    url(r'^photo_upload/(?P<id>\d+)/$', 'app.views.photo_upload', name='photo_upload'),
    

1 个答案:

答案 0 :(得分:1)

如果您未附加id,请将视图写为

def photo_upload(request, id=None):

OR

"{% url 'photo_upload' id %}" #id if you are attaching /id in url.

您的photo_upload视图需要参数id