Yurii Halapup
Yurii Halapup

Reputation: 1362

Avoid repetition between Django ModelForm and Django Model

I'm interested is there a way to avoid repetition between Django ModelForm and Django Model. E.g. I have this simplest Model:

class Category(models.Model):
    name = models.CharField(max_length=128)

and corresponding ModelForm to it

class CategoryForm(forms.ModelForm):
    name = models.CharField(max_length=128)
    class Meta:
        model = Category
        fields = ('name',)

As we can see there is repetition between these entities. This code

max_length=128

- does it violate "Don't repeat yourself" principle?
And if it violates, how can we avoid this duplication of code?

Upvotes: 2

Views: 224

Answers (3)

--Model

class Category(models.Model):
    name = models.CharField(max_length=128)

-Form

class CategoryForm(forms.ModelForm):
  class Meta:
    model = Category
    fields = ('name',)

-View

class CategoryView(request):
    form = CategoryForm()
    if request.method == "POST":
        #code..
        return render(request,'htmlpage.html',{Variables: Variables})
    else: 
        return render(request, "htmlpage.html",{'form':form})

Created 'form', view page loads. Here the request from html page is queried with POST. If the post is not requested, the FORM template is sent to the html page.

Upvotes: 0

e4c5
e4c5

Reputation: 53734

As pointed out in the other answer, you don't need to re declare the fields in the ModelForm. You only need to list them out in the fields attribute of the class Meta. If you feel that is not DRY enough. You can use __all__

Set the fields attribute to the special value 'all' to indicate that all fields in the model should be used. For example:

Ref: https://docs.djangoproject.com/en/1.10/topics/forms/modelforms/

Upvotes: 0

s_mart
s_mart

Reputation: 765

But you do not have to specify name field in Form one more time in your case.

You are using ModelForm, so in Meta just define model, which is referred to this Form and fields, that should be used in form. Django will fetch widgets and build form for you.

So that's enough

class CategoryForm(forms.ModelForm):
    class Meta:
        model = Category
        fields = ('name',)

Upvotes: 1

Related Questions