如何从用户获取用户名变量以在models.py django

时间:2018-05-05 14:58:59

标签: html django forms

我想获取登录用户的用户名变量,将其用作创建帖子表单的默认值

在html中我可以通过{{ user.username}}来访问它,但是当我在我的models.py中将其作为默认值时,我得到的默认值为{{user.username}},就像文本而不是变量一样当我删除两个花括号时,它表示用户未定义

models.py

class Payment(models.Model):
    Author = models.CharField(max_length=255)
    Product = models.CharField(max_length=255)
    Payment_ID = models.BigIntegerField(default=0)
    Status = models.CharField(max_length=5, default="X")
    Review_result = models.CharField(max_length=255, default="Not yet reviewed")
    created = models.DateTimeField(auto_now_add=True)

    class Meta:
        ordering = ['-created']

        def __unicode__(self):
            return u'%s'% self.Status

    def __str__(self):
        return self.Status

并且对于登录我使用django的默认形式

forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Payment

class RegistrationForm(UserCreationForm):
    email = forms.EmailField(required=True)
    first_name = forms.CharField(required=True)
    last_name = forms.CharField(required=True)

    class Meta:
        model = User
        fields = (
                'username',
                'first_name',
                'last_name',
                'email',
                'password1',
                'password2',
            )

    def save(self, commit=True):
        user = super(RegistrationForm, self).save(commit=False)
        user.first_name = self.cleaned_data['first_name']
        user.last_name = self.cleaned_data['last_name']
        user.email = self.cleaned_data['email']

        if commit:
            user.save()

        return user

class PayForm(forms.ModelForm):

    class Meta:
        model = Payment
        fields = ['Author', 'Product', 'Price', 'Payment_ID']

views.py

from django.shortcuts import render, render_to_response , get_object_or_404, redirect
from .models import Post
from django.contrib.auth import authenticate, login
from .forms import RegistrationForm, PayForm
# Create your views here.
def index(request):
    posts=Post.objects.all()
    return render(request, 'Index.html', {"posts": posts})


def post(request, slug):
    return render(request, 'post.html', {'post': get_object_or_404(Post,         slug=slug)})

def register(request):
    if request.method == 'POST':
        form = RegistrationForm(request.POST)

        if form.is_valid():
            form.save()
            username = form.cleaned_data['username']
            password = form.cleaned_data['password1']
            user = authenticate(username=username, password=password)
            login(request, user)
            return redirect('index')
    else:
        form = RegistrationForm()

    context = {'form' : form}
    return render(request, 'registration/register.html', context)

def new_payment(request):

    template ='payment.html'
    form = PayForm(request.POST or None)


    if form.is_valid():
        form.save()
        return redirect('index')

    else:
        form = PayForm()

    context = {
        'form' : form,
    }
    return render(request, template, context)

1 个答案:

答案 0 :(得分:1)

在您的视图中,您可以覆盖表单的初始值:

def new_payment(request):

    template ='payment.html'
    if request.method == 'POST'
        form = PayForm(request.POST)
        if form.is_valid():
            form.save()
            return redirect('index')
        else:
            print('form invalid')

    else:
        form = PayForm({'Author':request.user.username})

    context = {
        'form' : form,
    }
    return render(request, template, context)