2017-01-21 5 views
0

내 장고 프로젝트의 models.py에서 양식이 있습니다Select2를 사용하여 ModelForm의 Django 필드에 대한 유효성 검사를 건너 뛰는 방법은 무엇입니까?

forms.py에서
class Profile(models.Model): 
    choices = (("choice1", "choice1"), ("choice2", "choice2"), ("choice3", "choice3")) 
    field = models.CharField(choices=choices) 

:

class ProfileForm(ModelForm): 
    class Meta: 
     model = Profile 
     fields = ["field"] 
     widgets = {"field": Select2TagWidget} 

나는 내 선택 필드를 잘 보이게하기 위해 Select2TagWidget를 사용하여뿐만 아니라 해요 이론적으로 사용자가 초기 목록에없는 선택 항목을 입력 할 수있게합니다. 이 프론트 엔드는 완벽하게 작동하며 사용자는 다른 값을 입력 할 수 있습니다. 그러나 사용자가 새로운 값을 사용하여 제출하면 Django 양식 유효성 검사가 데이터베이스에 저장을 차단합니다. 그래서 내 문제는 :

Select2 태그를 유지하지만 django가 "error"만 사용자가 새로운 값을 입력 한 경우 is_valid() 호출시 True를 반환하도록하려면 어떻게해야합니까?

많은 수업을 덮어 쓰려고했지만 아무 소용이 없었습니다. 또한 특별한 위젯을 사용하는 몇 가지 해답을 보았지만 Select2 위젯을 사용해야하기 때문에 사용할 수 없습니다.

EDIT : 여기

는 (루프 특히) 나에게 번잡 필드 클래스 내에 장고 검증 코드 :

def validate(self, value, model_instance): 
    """ 
    Validates value and throws ValidationError. Subclasses should override 
    this to provide validation logic. 
    """ 
    if not self.editable: 
     # Skip validation for non-editable fields. 
     return 

    if self.choices and value not in self.empty_values: 
     for option_key, option_value in self.choices: 
      if isinstance(option_value, (list, tuple)): 
       # This is an optgroup, so look inside the group for 
       # options. 
       for optgroup_key, optgroup_value in option_value: 
        if value == optgroup_key: 
         return 
      elif value == option_key: 
       return 
     raise exceptions.ValidationError(
      self.error_messages['invalid_choice'], 
      code='invalid_choice', 
      params={'value': value}, 
     ) 

    if value is None and not self.null: 
     raise exceptions.ValidationError(self.error_messages['null'], code='null') 

    if not self.blank and value in self.empty_values: 
     raise exceptions.ValidationError(self.error_messages['blank'], code='blank') 

을 그러나, 이런 식으로 덮어 :

class NoValidationCharField(models.CharField): 
    def validate(self, value, model_instance): 
     return 

CharField 대신 해당 문제를 수정해도 문제가 해결되지 않습니다.

답변

-2

구체적으로 Django 유효성 검사 오류의 원인은 무엇입니까?

또한 Django의 유효성 검사를 건너 뛰지 마십시오. 그것은 이유가 있습니다. 이것에 대한 대답은 위젯 데이터의 위생을 포함 할 것 같지만 확실하지 않습니다.

+0

Django 오류는 값이 선택 목록에 있는지 확인하는 유효성 검사로 인해 발생합니다. 이 유효성 검사는 나에게 실제 목적이 아닙니다. 데이터베이스 또는 유형 무결성을 검사하지 않습니다. 내 질문에 특별히 발생하는 코드를 게시했습니다. – TheRuler