django1.8,我尝试获取当前登录的用户名。在模板中得到了工作,但在视野中我失败了

时间:2015-09-25 10:42:00

标签: django username

我是django 1.8的新手。

现在,我正在尝试获取当前登录的用户名。 我想这样做。当我发布一些文章时,作者自动保存到数据库并显示在模板表中。

我已经知道了  来自django.contrib.auth.models导入用户  和request.user.get_username()

阅读了很多关于这个主题的文章和QNA以及两天内的各种尝试。但我从来没有找到为什么我只能在模板中获取用户名但不在视图中。

我做了以下事情 python manage.py makemigrations BTS(这是应用程序的名称) python manage.py migrate 它运作良好。

在模板中,Belows一切运作良好:

ggplot(df1, aes(sp, value, fill = variable)) + 
  geom_bar(aes(lty = tr), lwd = 1.2, stat = "identity", colour = "black", width =.8) + 
  scale_linetype_discrete(name = "ja") +
  guides(fill = FALSE,
         lty = guide_legend(override.aes = list(lty = c('dotted', 'dashed', 'solid'),
                                                fill = "white"))) +
  theme_classic() +
  theme(legend.position = "bottom")

在views.py中,我使用这样的get_username方法。没有错误,但它不起作用。:

{{ user.username }}
{{ request.user.username }}
{{ request.user }}

其他一切都很好。但是,只有一行以上才能得到任何关于用户名的空null值,我猜。我需要帮助。

这是我的代码。我跳过一些不必要的def。

views.py

form.username = request.user.get_username()

input.html

from django.shortcuts import render
from django.http import HttpResponse
from django.utils import timezone
from django.template import RequestContext, loader
from django.shortcuts import redirect
from .models import BTSinput
from .models import BTSreply
from .forms import BTSinputForm
from .forms import BTSreplyForm
from django.contrib.auth.models import User

def inputvalidate(request):
    if request.method == 'POST':
        form = BTSinputForm(request.POST or None)
        if form.is_valid():
            hold = form.save(commit=False)
            form.created = timezone.now()
            form.updated = timezone.now()
            form.username = request.user.get_username()
            hold.save()
            return redirect('/BTS/list/')
    else:
        form = BTSinputForm()
        return render(request,'BTS/input.html',{'inputform':form})

    return render(request,'BTS/input.html',{'inputform':form})

models.py

{% block content %}

{% load widget_tweaks %}

<div class="container">
    <div class="starter-template">
     <form method="post" action="/BTS/inputvalidate/">
        {% csrf_token %}
     <div class="form-group">
        <p>subject</p>
        <p>{{inputform.subject|add_class:"form-control"}}</p>
        <p>URLS</p>
        <p>{{inputform.urls|add_class:"form-control"}}</p>        
        <p>text</p>
        <p>{{inputform.text|add_class:"form-control"}}</p>
        <button type="submit" class="btn btn-default">Confirm</button>    
        <a href="/bts/list/"><button type="button" class="btn btn-default">To List</button></a>
     </div>

    </form>
       </div>
    </div>

{% endblock%}

forms.py

class BTSinput(models.Model):
    subject = models.CharField(max_length=100)
    username = models.CharField(max_length=30, blank = True)
    text = models.TextField()
    urls = models.URLField(max_length = 100)        
    created = models.DateTimeField(default = datetime.datetime.now)
    updated = models.DateTimeField(default = datetime.datetime.now)

我一遍又一遍地检查了我的setting.py.但是...... ^^ ;;;

这是我的setting.py

from django import forms
from django.forms import ModelForm
from BTS.models import BTSinput
from BTS.models import BTSreply


# Create your models here.
class BTSinputForm(ModelForm):
    class Meta:
        model = BTSinput
        fields = ['subject','text','urls']


class BTSreplyForm(ModelForm):
    class Meta:
        model = BTSreply
        fields = ['reply']

1 个答案:

答案 0 :(得分:1)

使用save致电commit=False后,您应该更新实例,而不是表单。

    if form.is_valid():
        hold = form.save(commit=False)
        hold.created = timezone.now()
        hold.updated = timezone.now()
        hold.username = request.user.get_username() # or request.user.username
        hold.save()