How do I filter ForeignKey choices in a Django ModelForm?

前端 未结 7 1721
感情败类
感情败类 2020-11-22 09:07

Say I have the following in my models.py:

class Company(models.Model):
   name = ...

class Rate(models.Model):
   company = models.ForeignKey(C         


        
相关标签:
7条回答
  • 2020-11-22 09:47

    To do this with a generic view, like CreateView...

    class AddPhotoToProject(CreateView):
        """
        a view where a user can associate a photo with a project
        """
        model = Connection
        form_class = CreateConnectionForm
    
    
        def get_context_data(self, **kwargs):
            context = super(AddPhotoToProject, self).get_context_data(**kwargs)
            context['photo'] = self.kwargs['pk']
            context['form'].fields['project'].queryset = Project.objects.for_user(self.request.user)
            return context
        def form_valid(self, form):
            pobj = Photo.objects.get(pk=self.kwargs['pk'])
            obj = form.save(commit=False)
            obj.photo = pobj
            obj.save()
    
            return_json = {'success': True}
    
            if self.request.is_ajax():
    
                final_response = json.dumps(return_json)
                return HttpResponse(final_response)
    
            else:
    
                messages.success(self.request, 'photo was added to project!')
                return HttpResponseRedirect(reverse('MyPhotos'))
    

    the most important part of that...

        context['form'].fields['project'].queryset = Project.objects.for_user(self.request.user)
    

    , read my post here

    0 讨论(0)
提交回复
热议问题