Django 1.1 형태, 모델 및 숨겨진 필드
문제
다음 django 모델을 고려하십시오.
class Host(models.Model):
# This is the hostname only
name = models.CharField(max_length=255)
class Url(models.Model):
# The complete url
url = models.CharField(max_length=255, db_index=True, unique=True)
# A foreign key identifying the host of this url
# (e.g. for http://www.example.com/index.html it will
# point to a record in Host containing 'www.example.com'
host = models.ForeignKey(Host, db_index=True)
나는 또한이 양식을 가지고 있습니다.
class UrlForm(forms.ModelForm):
class Meta:
model = Urls
문제는 다음과 같습니다. 호스트 필드의 값을 자동으로 계산하려고하므로 웹 페이지에 표시된 HTML 양식에 나타나지 않기를 바랍니다.
양식 에서이 필드를 생략하기 위해 '제외'를 사용하는 경우 양식을 사용하여 데이터베이스에 정보를 저장하는 방법 (호스트 필드가 있어야 함)?
해결책
사용 commit=False
:
result = form.save(commit=False)
result.host = calculate_the_host_from(result)
result.save()
다른 팁
"Clean"메소드 양식에서 원하는대로 설정할 수 있습니다.
그래서 당신의 형태로 :
class myform(models.ModelForm):
class Meta:
model=Urls
exclude= ("field_name")
def clean(self):
self.cleaned_data["field_name"] = "whatever"
return self.cleaned_data
제휴하지 않습니다 StackOverflow