Home > Back-end >  querying database to give specific need in Class Base View doesn't work
querying database to give specific need in Class Base View doesn't work

Time:12-29

I created a school database to store student informations, as a school database that can be used in different schools, when user try to create Primary model, it shown every Album that is created by other schools, instead of showing an Album that is created by a particular school. I don't want others school to be able see all the Album that isn't their own.

Here is how I did it, but doesn't work:

Class CreatePrimary(CreateView):
    Model = Primary
    Fields = ['profilePicture', 'first_name', 'last_name', 'year_of_graduation']
    template_name = 'create_primary.html'
    success_url = ('Home')
    
    #trying to use "filter", but it doesn't work
    def get_queryset(self):
        return Album.objects.filter(user=self.request.user)

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super (CreatePrimary, self).form_valid(form)


Class Album(models.Model):
    user = models.ForeignKey(User,
     on_delete=models.CASCADE)
    name = models.charfield(max_length=20)

Class Primary(models.Model):
    profilePicture = models.FilesField(upload_to='image')
    first_name = models.charfield(max_length=20)
    last_name = models.charfield(max_length=20)
    year_of_graduation = models.Foreignkey(Album, on_delete=models.CASCADE)
    ''''

CodePudding user response:

At the first remove the get_queryset method. Then add the following codes into your form_valid method.

def form_valid(self, form):
        self.object = form.save(commit=False)
        self.object.user = self.request.user
        self.object.notes_folder = slugify(self.object.title)
        self.object.save()
        return super(CreatePrimary, self).form_valid(form)

CodePudding user response:

I solve this problem by override the get_form method of the CreatePrimary view and modify the year_of_graduation field to only include the Album instances that belong to the current user:

class CreatePrimary(CreateView):
    model = Primary
    fields = ['profilePicture', 'first_name', 'last_name', 'year_of_graduation']
    template_name = 'create_primary.html'
    success_url = 'Home'

    def get_form(self, form_class=None):
        form = super().get_form(form_class)
        form.fields['year_of_graduation'].queryset = Album.objects.filter(user=self.request.user)
        return form

    def form_valid(self, form):
        form.instance.user = self.request.user
        return super(CreatePrimary, self).form_valid(form)

  • Related