1

I created a django form (IssueForm) which is meant to be used to register an object which is instance of one of my models (Issue). Following are the model:

model.py

class Issue(models.Model):

TYPE_FIELDS = [
    ("Math", "Math"),
    ("Physics", "Physics"),
    ("Programming", "Programming"),
    ("Arts", "Arts")
]

issue_text = models.TextField(default="Please insert text")
issue_description = models.TextField(default="Newly created")
issue_deadline = models.DateField()
issue_field = models.CharField(max_length=30, choices=TYPE_FIELDS)
published_by = models.ForeignKey(User, on_delete=models.CASCADE, default=None)

def __str__(self):
    return self.issue_description  

the form used:

forms.py

class IssueForm(forms.ModelForm):

def __init__(self, user, *args, **kwargs):
    self.user = user
    super(IssueForm, self).__init__(*args, **kwargs)

TYPE_FIELDS = [
    ("Math", "Math"),
    ("Physics", "Physics"),
    ("Programming", "Programming"),
    ("Arts", "Arts")
]

issue_text = forms.CharField(widget=forms.Textarea, required=True)
issue_description = forms.CharField(widget=forms.Textarea, required=True)
issue_deadline = forms.DateField(required=True)
issue_fields = forms.ChoiceField(choices=TYPE_FIELDS, required=True)

class Meta:
    model = Issue
    fields = [
        'issue_text',
        'issue_description',
        'issue_deadline',
        'issue_fields'
    ]

def save(self, commit=True):
    issue = super(IssueForm, self).save(commit=False)
    issue.issue_text = self.cleaned_data['issue_text']
    issue.issue_description = self.cleaned_data['issue_description']
    issue.issue_deadline = self.cleaned_data['issue_deadline']
    issue.issue_fields = self.cleaned_data['issue_fields']

    if commit:
        issue.published_by = self.user
        issue.save()

    return issue  

and the related view:

views.py

def create_issue(request):
if ExtendedUser.objects.filter(user=request.user).exists():
    if request.method == 'POST':
        form = IssueForm(request.user, request.POST)
        if form.is_valid():
            form.save()
        return redirect("/issues")
    else:
        form = IssueForm(request.user)
        args = {'form': form}
        return render(request, "issues/create_issue.html", args)
else:
    raise Http404("You are not allowed to perform this action")  

The forms works for every field in the model, they are all registered right, except for issue_fields. If i try giving a default value to the field in the model, that is the value that is saved on the database, otherwise I just get an empty field. Also I believe the problem comes from the form used, because if i try to create a new issue from the django admin interface it works just fine.
I feel like it's one of those silly mistakes, but I'm just starting with django and python in general and cannot figure it out on my own.
Thank you for your time!!

Giacomo Casoni
  • 387
  • 2
  • 16

2 Answers2

0

The field on your model is called issue_field, but you set issue_fields.

Note that also you are doing far more work here than necessary. Your save method completely duplicates what the superclass does already; you should remove all that code except for the setting of the user value.

Daniel Roseman
  • 588,541
  • 66
  • 880
  • 895
0

enter code hereIf you want to use Choices, you haven't to write one more time list of choices in your forms.py file.

This is an example :

#In your models.py file

LIST_CHOICE = (('A','A'), ('B','B'))

class Test(models.Model) :

    foo = models.CharField(choices=LIST_CHOICE, verbose_name="foo")

and

#In your form.py file

TestForm(forms.Modelform) :

    class Meta :
        model = Test
        fields = ['foo'] 

It's not necessary to overwrite LIST_CHOICE in your form file ;)

So, dont touch to your model.py file, but in your form.py file, just write :

class IssueForm(forms.ModelForm):

    issue_text = forms.CharField(widget=forms.Textarea)
    issue_description = forms.CharField(widget=forms.Textarea)

    def __init__(self, user, *args, **kwargs):
        self.user = user
        super(IssueForm, self).__init__(*args, **kwargs)


    class Meta:
        model = Issue
        fields = [
            'issue_text',
            'issue_description',
            'issue_deadline',
            'issue_fields'
        ]

Don't forget to remove s in issue_field ;)

Essex
  • 6,042
  • 11
  • 67
  • 139