首页 > 解决方案 > 如何在 Django 中获取特定用户的信息(我想获取现在登录的特定用户的约会历史记录)

问题描述

#for 添加约会

def book_appointment(request):
    if request.method=="POST":
        specialization=request.POST['specialization']
        doctor_name=request.POST['doctor']
        time=request.POST['time']
        app=Appointment(specialization=specialization, doctor_name=doctor_name, time=time)
        app.save()  
    messages.success(request, "Successfully Appointment booked tap on view appointment for status")
    return redirect('home')

#查看约会历史

  def appointmentInfo(request):
    appts= Appointment.objects.all() 
    return render(request,'home/view_appointment.html',{'appoints':appts})     

#登录

def handeLogin(request):
    if request.method=="POST":
        # Get the post parameters
        loginusername=request.POST['loginusername']
        loginpassword=request.POST['loginpassword']
        user=authenticate(username= loginusername, password= loginpassword)
        if user is not None:
            login(request, user)
            messages.success(request, "Successfully Logged In")
            return redirect("home")
        else:
            messages.error(request, "Invalid credentials! Please try again")
            return redirect("home")  
    return HttpResponse("404- Not found") 
    return HttpResponse("login")

标签: pythondjangodjango-rest-frameworkdjango-views

解决方案


如果你想要当前用户的记录,

添加一个将约会模型指向用户模型的关系属性,以便知道谁是正在接受治疗的患者......像这样,

模型.py:

#import for User model
from django.contrib.auth.models import User

class Appointment(models.Model):
    sno= models.AutoField(primary_key=True)
    doctor_name= models.CharField(max_length=255)
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    specialization= models.CharField(max_length=23)
    fee=models.CharField(max_length=20)
    #email= models.CharField(max_length=100)
    #time= models.TextField()
    #timeStamp=models.DateTimeField(auto_now_add=True, blank=True)

视图.py

def appointmentInfo(request):

    appts= Appointment.objects.get(user__id = request.user.id)

    return render(request,'home/view_appointment.html',{'appoints':appts})

推荐阅读