Django:在OneToOneField上保存id

时间:2013-03-20 19:04:59

标签: django foreign-keys models

模型:

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']

我只需要一种方法来在UserSurvey上设置UserDataUpdate id(已经创建)。

我在generate_survey request.POST上收到此消息:

user_data_update_app_usersurvey.user_data_update_id may not be NULL

1 个答案:

答案 0 :(得分:0)

您应该清楚,您获得了user_data_update值,但之后却没有做任何事情。我想你想把它设置在由表单创建的对象上:

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

(我不明白表格的__init__方法中的所有内容应该是什么。无论如何,你的表单中只有一个字段。)