开发者

Django: is it possible to validate and save fields of several forms in one generic view?

开发者 https://www.devze.com 2023-03-07 05:13 出处:网络
I have 2 models: class Person( models.Model ): username = models.CharField name = models.CharField( max_length = 30 )

I have 2 models:

class Person( models.Model ):
  username = models.CharField
  name = models.CharField( max_length = 30 )
  surname = models.CharFields( max_length = 30 )
  ...

class PersonSkills( models.Model ):
  person = models.ForeignKey( Person )
  skill = models.CharField( max_length = 30 )
  ...

I would like to add data to Person and to PersonSkills in one view.

Now I have RegisterView like the next:

class RegisterForm( ModelForm ):
    class Meta:
        model = Person
        fields = ( 'username', 'name', 'surname', 'password', )

class Reg开发者_如何学JAVAisterView( FormView ):
    form_class = RegisterForm
    success_url = "/welcome/"
    template_name = "register.tmpl"
    is_valid = True
    def form_valid( self, form ):       
        form.save()
        self.is_valid = True
        return super( RegisterView, self ).form_valid( form )
    def form_invalid( self, form ):
        self.is_valid = False       
        return super( RegisterView, self).form_invalid( form )
    ...

So how can I add data to Person and to PersonSkills in one view? Inheritance from FormView allows only one form_class.


The best way of achieving what you want is to create a custom form that declares the fields required for both models. Use the save method of the form to save to the individual model classes, by accessing the fields within cleaned_data.

Then your FormView will work as expected. It'll be receiving inputs for two different models, but the logic is contained entirely within the form. As with all custom forms, put validation logic within the various *clean* methods.

0

精彩评论

暂无评论...
验证码 换一张
取 消