简体   繁体   English

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

[英]Allow users to create an "appointment" using a django form

I am trying to male a django webapp;我正在尝试使用 django webapp; the app has several forms that are submitted by users and I was wondering if there was a way to tell which user submitted the form so that I could bind the form input to that particular user.该应用程序有几个用户提交的表单,我想知道是否有办法告诉哪个用户提交了表单,以便我可以将表单输入绑定到该特定用户。 The form is for an "appointment" as if the patient that were logged in is making an appointment to go see their doctor.该表格用于“预约”,就好像登录的患者正在预约去看医生一样。 Model:模型:

     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)

Form:形式:

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

View:看法:

    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))

If the user is logged in then you can simply use this:如果用户已登录,则您可以简单地使用:

user=request.user

In your views.py.在您的 views.py 中。 It will return AnonymousUser if the user is not logged in, so first make sure the user is authenticated.如果用户未登录,它将返回 AnonymousUser,因此首先确保用户已通过身份验证。

if request.user.is_authenticated ():
    #Do stuff

You are using instance improperly, it's for when you want to update a specific row in the database.您使用的实例不正确,这是为了更新数据库中的特定行。 You need to create the form without the user field (adding exclude=['user',] to the meta of the form f.ex.) then change the contents of the if request.method="POST" a bit:您需要创建没有用户字段的表单(将 exclude=['user',] 添加到表单 f.ex. 的元数据中)然后稍微更改 if request.method="POST" 的内容:

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

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM