• Members 1 post
    Jan. 5, 2020, 11:04 p.m.

    I want to exclude those options from the ChoiceField in the forms that has been already selected and are into the database. Below is the Code.

    models.py

    SEMESTER_CHOICES = (
        ("1", "1"),
        ("2", "2"),
        ("3", "3"),
        ("4", "4"),
        ("5", "5"),
        ("6", "6"),
        ("7", "7"),
        ("8", "8"),
    )
    class Publish(models.Model):
        dates = models.CharField(max_length=255, choices = SEMESTER_CHOICES)
    
        def __str__(self):
            return self.dates
    
    

    form.py

    
    SEMESTER_CHOICES = (
        ("1", "1"),
        ("2", "2"),
        ("3", "3"),
        ("4", "4"),
        ("5", "5"),
        ("6", "6"),
        ("7", "7"),
        ("8", "8"),
    )
    
    class PublishForm(forms.ModelForm):
    
    
        def __init__(self, **kwargs):
            super(PublishForm, self).__init__(self, **kwargs)
            selected_choices = [i.dates for i in Publish.objects.all()]
                    self.fields['dates'].choices = ({(k, v) for k, v in SEMESTER_CHOICES
                                                 if k not in selected_choices})
    
        class Meta:
            model = Publish
            fields = ['dates']
    
    

    view.py

    def add(request):
        if request.method == 'POST':
            form = PublishForm(request.POST)
            if form.is_valid():
                form.save()
                return redirect('mainapp:add')
        else:
            form = PublishForm()
    
        context = {
            'form' : form
        }
        return render(request, 'mainapp/add.html', context)
    
    

    What am I doing wrong? Ive followed these 2 links here. [link1][1] and [link2][2]. Any suggestions please.

    Also I am getting the error : 'PublishForm' object has no attribute 'get'

    Thank you

    [1]: stackoverflow.com/questions/27910922/django-form-exclude-options-in-select-field
    [2]: stackoverflow.com/a/3665999/12280790

  • arrow_forward

    Thread has been moved from Problems and issues.

  • Jan. 7, 2020, 1:37 a.m.

    Moved this thread to "Web design and dev" because it was off-topic for the "Problems and issues".

    At first glance the ({}) syntax looks off, and there's *args missing. This would be better:

    class PublishForm(forms.ModelForm):
        def __init__(self, *args, **kwargs):
            super(PublishForm, self).__init__(self, *args, **kwargs)
            selected_choices = [i.dates for i in Publish.objects.all()]
            self.fields['dates'].choices = (
                (k, v) for k, v in SEMESTER_CHOICES if k not in selected_choices
            )
    

    'PublishForm' object has no attribute 'get'

    Check how you are using your form in template. Without seeing it's code I can't tell for sure what's wrong in it however.