A] 요약 :얻거나 많은 장고 모델과 modelforms
얻거나 기록 또는 관계가 새로운를 추가하기 전에 존재 여부를 확인, 많은 장고 모델 하나에 기능을 삽입하여 하나.
B] 세부 :
1] (많은)시에 다음 장고 모델 구조의 국가 (하나)가
2] 나는 HTML 페이지에있는 양식을 표시 ModelForm를 사용하고 . 양식은 템플릿 값으로 전달되고 템플릿 값은 html 페이지에서 렌더링됩니다.
3] 게시물 요청이 들어 오면 코드는 국가 및 도시 양식 데이터를 추출하고 유효성을 검사 한 다음 저장합니다.이
1] 내가
2] 기본적으로, 나는이 있는지 여부를 확인하려면 내 국가 및 도시 관계로 get_or_insert 기능을 사용하려면 :
C] 문제/상품 나는 도움이 필요
2.1] 사용자가 선택한 국가의 데이터베이스에있는 기존 국가 레코드가있는 경우 선택한 국가에 대한 도시 레코드가 있는지 확인하십시오.
2.1.1] 도시의 기록이 존재하는 경우, 우리는 좋은, 다른 레코드
2.1.2] 도시의 기록이 존재하지 않는 경우, 도시 레코드를 생성을 추가로 국가를 연결 할 필요가 없습니다 it
2.2] 국가가 없으면 국가 레코드를 만들고 도시 레코드를 만들고 국가 레코드와 도시 레코드를 연결하십시오.
C] 부호 발췌 :
1] 모델 및 형태 -
class UserReportedCountry(db.Model):
country_name = db.StringProperty(required=True,
choices=['Afghanistan','Aring land Islands']
)
class UserReportedCity(db.Model):
country = db.ReferenceProperty(UserReportedCountry, collection_name='cities')
city_name = db.StringProperty(required=True)
class UserCountryForm(djangoforms.ModelForm):
class Meta:
model = UserReportedCountry
class UserCityForm(djangoforms.ModelForm):
class Meta:
model = UserReportedCity
exclude = ('country',)
forms-- user_country_form 및 user_city_form는 인쇄
2 코드 파이썬 코드에서 템플릿 값으로 전달
__TEMPLATE_USER_COUNTRY_FORM = 'user_country_form'
__TEMPLATE_USER_CITY_FORM = 'user_city_form'
def get(self):
template_values = {
self.__TEMPLATE_USER_COUNTRY_FORM: UserCountryForm(),
self.__TEMPLATE_USER_CITY_FORM: UserCityForm()
}
#rendering the html page and passing the template_values
self.response.out.write(template.render(self.__MAIN_HTML_PAGE, template_values))
HTML 페이지에 템플릿 값을 표시 3] HTML 코드 발췌
<div id="userDataForm">
<form method="POST" action="/UserReporting">
<table>
<!-- Printing the forms for users country, city -->
{{ user_country_form }}
{{ user_city_form }}
</table>
<input type="submit" name="submit" value= "submit">
</form>
</div>
데이터 저장을위한 3] 코드 발췌 - 읽기
def post(self):
self.store_user_data()
self.redirect('/')
#method to save users data in the models UserReportedCountry, UserReportedCity
def store_user_data(self):
#getting user's country and city
user_reported_country = UserCountryForm(self.request.POST)
user_reported_city = UserCityForm(self.request.POST)
if (user_reported_country.is_valid() and user_reported_city.is_valid()):
#save the country data
country_entity = user_reported_country.save()
#save the city data, and relate county with city
city_entity = user_reported_city.save(commit=False)
city_entity.country = country_entity
city_entity.put()
return
else:
return
감사합니다를 .
[편집 # 1] 스텐 @
, 후 나에게 get_or_insert에 대한 포인터를했다, 나는 그 http://stackoverflow.com/questions/4812832/get-or-create-matching (StackOverflow의 게시물을 통해 온
def store_user_data(self):
#getting user's country and city
user_reported_country = UserCountryForm(self.request.POST)
user_reported_city = UserCityForm(self.request.POST)
if (user_reported_country.is_valid() and user_reported_city.is_valid()):
#save the country and city data
country_record = self.store_country_data()
city_record = self.store_city_data(country_record)
return
else:
return
def store_country_data(self):
user_reported_country_name = self.request.POST['country_name']
key_name = self.sanitize_key_name(user_reported_country_name)
country_entity = UserReportedCountry.get_or_insert(key_name, country_name = user_reported_country_name)
country_entity.put()
return country_entity
def store_city_data(self, country_record):
user_reported_city_name = self.request.POST['city_name']
key_name = self.sanitize_key_name("%s:%s" % (country_record.country_name, str(user_reported_city_name)))
city_entity = UserReportedCity.get_or_insert(key_name,
city_name = user_reported_city_name,
country= country_record)
city_entity.put()
return city_entity
def sanitize_key_name(self,key_name):
return re.sub(r'\s', '', key_name.lower())
요청 : 누군가가 빠른 코드를 할시겠습니까 다음과 같은 - 키 - 및 - 사용자 - 파이썬 앱 엔진)와 기록을 저장하는 사용자 get_or_insert
코드에 KEY_NAME 기능을 구현 보인다 내가 뭔가 잘못하고 있거나 일을하고 있는지 검토하고 알려줘. 오메 신참 실수?
모든. 귀하의 질문은 무엇인가? 무슨 문제가 있습니까? –
죄송합니다 @ 닉 존슨. 질문이 매우 상세했기 때문에 섹션 이름을 "Issue/Item i need help with"로 변경했습니다. – bhavesh