简体   繁体   中英

Allow users to create an "appointment" using a django form

I am trying to male a 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. It will return AnonymousUser if the user is not logged in, so first make sure the user is authenticated.

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:

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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