Skip to content
This repository has been archived by the owner on Aug 12, 2020. It is now read-only.

Listing Photos according to my Model with id of an object #76

Open
metinaltinbas opened this issue Sep 28, 2018 · 1 comment
Open

Listing Photos according to my Model with id of an object #76

metinaltinbas opened this issue Sep 28, 2018 · 1 comment

Comments

@metinaltinbas
Copy link

I am able to upload images to my Picture object with portfolio id created earlier.
But i cannot list images according to portfolio id.

I am trying to get Id of an portfolio from my view and i couldn't.

I just want to display images according to my Picture object with portfolio id .

These are my models

class Portfolio(models.Model):
    title = models.CharField(max_length=55)
    description = models.TextField()
    user = models.ForeignKey(User)
class Picture(models.Model):
    """This is a small demo using just two fields. The slug field is really not
    necessary, but makes the code simpler. ImageField depends on PIL or
    pillow (where Pillow is easily installable in a virtualenv. If you have
    problems installing pillow, use a more generic FileField instead.

    """
    # portfolio_id = models.ForeignKey(Portfolio,null=True)
    file = models.ImageField(upload_to="pictures")
    slug = models.SlugField(max_length=50, blank=True)
    # user = models.ForeignKey(User, default=1)
    portfolio = models.ForeignKey(Portfolio, null=True)

    def __str__(self):
        return self.file.name

    @models.permalink
    def get_absolute_url(self):
        return ('upload-basic-plus', )

    def save(self, *args, **kwargs):
        self.slug = self.file.name
        super(Picture, self).save(*args, **kwargs)

    def delete(self, *args, **kwargs):
        """delete -- Remove to leave file."""
        self.file.delete(False)
        super(Picture, self).delete(*args, **kwargs)

These are my urls

urlpatterns = [
    url(r'^basic/(?P<id>\d+)/$', BasicVersionCreateView.as_view(), name='upload-basic'),
    url(r'^basic/plus/(?P<id>\d+)/$', BasicPlusVersionCreateView.as_view(), name='upload-basic-plus'),
    url(r'^new/(?P<id>\d+)/$', PictureCreateView.as_view(), name='upload-new'),
    url(r'^angular/(?P<id>\d+)/$', AngularVersionCreateView.as_view(), name='upload-angular'),
    url(r'^jquery-ui/(?P<id>\d+)/$', jQueryVersionCreateView.as_view(), name='upload-jquery'),
    url(r'^delete/(?P<pk>\d+)/$', PictureDeleteView.as_view(), name='upload-delete'),
    url(r'^view/(?P<id>\d+)/$', PictureListView.as_view(), name='upload-view'),
]

These three also my views


class PictureCreateView(CreateView):
    model = Picture
    fields = ['file']


    def dispatch(self, request, *args, **kwargs):
        """
        Overridden so we can make sure the `Ipsum` instance exists
        before going any further.
        """
        self.portfolio = get_object_or_404(Portfolio, pk=kwargs['id'])
        return super().dispatch(request, *args, **kwargs)

    def form_valid(self, form):
        # user = self.request.user
        # form.instance.user = user
        form.instance.portfolio = self.portfolio
        self.object = form.save()
        files = [ serialize (self.object) ]
        data = {'files': files}
        response = JSONResponse(data, mimetype=response_mimetype(self.request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response

    def form_invalid(self, form):
        data = json.dumps(form.errors)
        print(data)
        return HttpResponse(content=data, status=400, content_type='application/json')

class PictureListView(ListView):
    model = Picture

    # def dispatch(self, request, *args, **kwargs):
    #     """
    #     Overridden so we can make sure the `Ipsum` instance exists
    #     before going any further.
    #     """
    #     self.portfolio = get_object_or_404(Portfolio, pk=kwargs['id'])
    #     return super().dispatch(request, *args, **kwargs)



    def render_to_response(self, context, **response_kwargs):
        print(self.portfolio.id)
        files = [ serialize(p) for p in Picture.objects.filter(portfolio=self.portfolio.id)]
        print("files",files)
        data = {'files': files}
        response = JSONResponse(data, mimetype=response_mimetype(self.request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response

class PictureDeleteView(DeleteView):
    model = Picture

    def delete(self, request, *args, **kwargs):
        self.object = self.get_object()
        self.object.delete()
        response = JSONResponse(True, mimetype=response_mimetype(request))
        response['Content-Disposition'] = 'inline; filename=files.json'
        return response
@sigurdga
Copy link
Owner

Sorry for my late reply. I was hoping you found out of the problem by yourself, since your problem is not directly related to the upload code (your code was storing the portfolio_id to the database) - more like how pictures and portfolios are connected and how you get Django to do what you want.

You posted a lot of details, but I'm not going to try to reproduce your problem, in that case, I would prefer to get a link to a repo with all the code, so I could easily try it by myself.

Also missing in your report is the actual error message if there are any. It is kind of hard to guess what you mean. If I were you, I would start with a new view, to show the portfolio, then get all related pictures using portfolio.get_picture_set.

Sign up for free to subscribe to this conversation on GitHub. Already have an account? Sign in.
Labels
None yet
Projects
None yet
Development

No branches or pull requests

2 participants