简体   繁体   English

Django:模型,视图和模板

[英]Django: models, views and templates

I'm trying to do a very simple thing in Django but getting stuck since I'm a newbie. 我正在尝试在Django中做一件非常简单的事情,但是由于我是新手而陷入困境。 Basically, on a doctor page in my website, I'm trying to add a field where a user can enter the waiting time for that doctor. 基本上,在我网站的医生页面上,我试图添加一个字段,用户可以在其中输入该医生的等待时间。 For this, I wrote the following model in my models.py: 为此,我在models.py中编写了以下模型:

class WaitingTime(models.Model):
    doctor = models.ForeignKey(Doctor)
    user = models.OneToOneField(User, unique=True)
    time = models.IntegerField("Waiting Time", max_length=2)

After this I wrote the following view: 在此之后,我编写了以下视图:

def WaitingTime(request):
    if request.method == 'POST': 
        form = WaitingTime(request.POST)
        if form.is_valid():
            doctor = form.cleaned_data['doctor']
            user = form.cleaned_data['user']
            time = form.cleaned_data['time']
            return HttpResponseRedirect('/thanks/') 
    else:
        form = WaitingTime()

This view is the part that I'm most unsure about. 这种观点是我最不确定的部分。 Even though I've done 2 tutorials, I feel like a total noob when I have to write this view. 即使我已经完成了2个教程,但当我不得不编写此视图时,我还是觉得有些笨拙。

And then, I added this code to my template: 然后,我将此代码添加到模板中:

<h4>Please enter the waiting time that you experienced for this doctor.</h4>
<form action="/WaitingTime/" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="hidden" name="doctor" value="{{ doctor.name }}" />
<input type="hidden" name="user" value="{{ user.username }}" />
WaitingTime: <input type="text" name="time"><br>
<input type="submit" value="Submit" />
</form>

So basically, I'm having trouble adding data from the front end to my database, something very trivial and basic. 因此,基本上,我很难将前端的数据添加到数据库中,这是非常琐碎且基本的。 I already ran python manage.py syncdb and checked using the SQLite Database Browser. 我已经运行了python manage.py syncdb并使用SQLite数据库浏览器进行了检查。 The table with the appropriate columns has been added. 已添加具有适当列的表。 Please help. 请帮忙。 Thanks a lot in advance. 非常感谢。

In order to make changes to the database your views needs to be changed to - 为了更改数据库,您的视图需要更改为-

def WaitingTime(request):
    if request.method == 'POST': 
        form = WaitingTimeForm(request.POST) #class specified in forms.py
        if form.is_valid():
            doctor = form.cleaned_data['doctor']
            user = form.cleaned_data['user']
            time = form.cleaned_data['time']
            WaitingTimeObject = WaitingTime(doctor=doctor, user=user, time=time)
            WaitingTimeObject.save()
            return HttpResponseRedirect('/thanks/') 

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

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