2013-03-20 85 views
0

型號:Django的:保存ID在OneToOneField

class UserDataUpdate(models.Model): 
    code = models.CharField(max_length=8) 
    address = models.CharField(max_length=50) 

class UserSurvey(models.Model): 
    about_treatment = models.CharField(max_length=2) 
    user_data_update = OneToOneField(UserDataUpdate) 

觀點:

@login_required 
def generate_survey(request): 
    user_data_update = UserDataUpdate.objects.get(code=request.user.username) 
    if request.method == 'POST': 
     form = SurveyForm(request.POST) 
     if form.is_valid(): 
      form.save() 
      return redirect('/success') 
    else: 
     form = SurveyForm(request.GET) 
    return render_to_response(
     'survey.html', 
     {'form': form }, 
     context_instance = RequestContext(request)) 

形式:

class SurveyForm(forms.ModelForm): 

    def __init__(self, *args, **kwargs): 
     super(SurveyForm, self).__init__(*args, **kwargs) 
     for field in self.fields.values(): 
      field.widget = RadioSelect(choices=SURVEY_CHOICES) 

    class Meta: 
     model = Survey 
     exclude = ['user_data_update'] 

我只是需要一種方法來設置UserDataUpdate ID(即已經已創建)在UserSurvey上。

我對generate_survey request.POST得到這個消息:

user_data_update_app_usersurvey.user_data_update_id may not be NULL 

回答

0

應該清楚你,你得到了user_data_update值,但那就不要用它做任何事情。我猜你要設置的是年代由表單創建的對象:

if form.is_valid(): 
    instance = form.save(commit=False) 
    instance.user_data_update = user_data_update 
    instance.save() 

(我不明白是什麼形式的__init__方法,所有的東西是應該做的,您只需要在一個領域你無論如何。)

+0

它在這個UserSurvey上缺少很多屬性,與原來的相比。這種形式的想法是將所有字段設置爲使用單選擇的RadioSelect渲染。順便說一句,謝謝你的例子,它工作得很好。從未使用(commit = False)來創建可變對象。真棒! – 2013-03-20 19:54:01