0

楷模:

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
4

1 回答 1

0

您应该清楚您获得了user_data_update价值,但随后不做任何事情。我猜你想在表单创建的对象上设置它:

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

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

于 2013-03-20T19:37:22.190 回答