允许用户使用django表单创建“约会”

时间:2015-09-26 16:41:26

标签: python django django-forms

我正在尝试使用django webapp;该应用程序有几个由用户提交的表单,我想知道是否有办法告诉哪个用户提交了表单,以便我可以将表单输入绑定到该特定用户。该表格用于“预约”,就像登录的患者正在预约去看医生一样。 型号:

     class Appointment(models.Model):
         user = models.OneToOneField(User)
         schedule = models.ForeignKey(Schedule)
         doctorName = models.CharField(max_length=50)
         date = models.DateTimeField(auto_now_add=True)

形式:

     class CreateAppointment(forms.ModelForm):
         class Meta:
             model = Appointment
             fields = ("doctorName", "date")

查看:

    def create_appointment(request):
        if request.POST:
            form = CreateAppointmentForm(request.POST, instance=request.user.profile)
            if form.is_valid():
               form.save()
            return render_to_response('index.html', context_instance=RequestContext(request))
        else:
           form = CreateAppointmentForm()

        args = {}
        args.update(csrf(request))

        args['form'] = form

       return render_to_response('create_appointment.html', args, context_instance=RequestContext(request))

2 个答案:

答案 0 :(得分:1)

您正在使用不正确的实例,它适用于您想要更新数据库中的特定行的时间。您需要创建没有用户字段的表单(将exclude = ['user',]添加到f.ex.形式的元)然后更改if request.method =“POST”的内容:

form_obj = CreateAppointmentForm(request.POST).save(commit=False)
form_obj.user = request.user
form_obj.save()

答案 1 :(得分:1)

如果用户已登录,则只需使用此功能:

 array(5) { ["headers"]=> array(8) { ["connection"]=> string(5) "close" ["date"]=> string(29) "Sat, 26 Sep 2015 18:12:23 GMT" ["server"]=> string(17) "Microsoft-IIS/6.0" ["x-powered-by"]=> string(7) "ASP.NET" ["x-aspnet-version"]=> string(9) "4.0.30319" ["cache-control"]=> string(18) "private, max-age=0" ["content-type"]=> string(35) "application/soap+xml; charset=utf-8" ["content-length"]=> string(3) "401" } ["body"]=> string(401) "
<soap:envelope xmlns:xsd="http://www.w3.org/2001/XMLSchema" xmlns:xsi="http://www.w3.org/2001/XMLSchema-instance" xmlns:soap="http://www.w3.org/2003/05/soap-envelope">
<soap:body>
<sendtransactionsactionresponse xmlns="http://tempuri.org/">
<sendtransactionsactionresult>113</sendtransactionsactionresult>
</sendtransactionsactionresponse>
</soap:body>
</soap:envelope>
" ["response"]=> array(2) { ["code"]=> int(200) ["message"]=> string(2) "OK" } ["cookies"]=> array(0) { } ["filename"]=> NULL } 

在views.py中。如果用户未登录,它将返回AnonymousUser,因此首先要确保用户已通过身份验证。

user=request.user