如何使用'重定向'和'消息'在django,python

时间:2016-07-17 05:03:47

标签: python django

我正在按照以下教程链接创建一个有登录框的页面,以及一个帖子表单。

我想在这里尝试完成的是,只有登录该网站的人才能在帖子表单上书写,并提交内容。

https://docs.djangoproject.com/en/1.9/topics/auth/default/

如果您转到上面的链接,请在'如何将用户登录到'部分, 它基本上告诉我使用

'重定向到成功页面' 并且'返回已停用的帐户错误消息'和 '返回无效的登录错误消息'

这里的问题是,我开始学习python和django只有几天了,每次这样的功能都是必要的,我几乎找不到任何来源来学习这些功能,或者得到代码来自。

我已经在google和stackoverflow上搜索了'重定向'但我能得到的例子是:

@app.route('/success/<int:result_id>')
def success(result_id):
 # replace this with a query from whatever database you're using
 result = get_result_from_database(result_id)
 # access the result in the tempalte, for example {{ result.name }}
 return render_template('success.html', result=result)
@app.route('/survey')
def survey():
if request.method == 'POST':
    # replace this with an insert into whatever database you're using
    result = store_result_in_database(request.args)
    return redirect(url_for('success', result_id=result.id))

# don't need to test request.method == 'GET'
return render_template('survey.html')

我还没有理解&#39;成功&#39;进入里面&#39; redirect()&#39;

这是我目前正在进行的views.py.

from django.contrib import messages
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render, get_object_or_404, redirect


from.forms import PostForm
from .models import Post


from django.contrib.auth import authenticate, login



def post_detail(request, id=None):
    #instance = Post.objects.get(id=1)
    instance = get_object_or_404(Post, id=id)
    context = {
        "title": instance.title,
        "instance": instance,
    }
    return render(request, "post_detail.html", context)

def post_list(request):

    username = request.POST['username']
    password = request.POST['password']
    user = authenticate(username=username, password=password)
    if user is not None:
        if user.is_active:
            login(request, user)
            # Redirect to a success page.
        else:
            # Return a 'disabled account' error message
        else:
        # Return an 'invalid login' error message.

    form = PostForm(request.POST or None)

    if form.is_valid():
        instance = form.save(commit=False)
        print (form.cleaned_data.get("title"))
        instance.save()
        # message success
        messages.success(request, "Successfully Created")
        return HttpResponseRedirect(instance.get())
    #else:
        #messages.error(request, "Not Successfully Created")
    queryset = Post.objects.all()#.order_by("-timestamp")
    context = {
        "object_list": queryset,
        "title": "List",
        "form": form,
    }
    return render(request, "post_list.html", context)
    #return HttpResponse("<h1>List</h1>")

def post_update(request, id=None):
    instance = get_object_or_404(Post, id=id)
    form = PostForm(request.POST or None, instance=instance)
    if form.is_valid():
        instance = form.save(commit=False)
        instance.save()
        # message success
        messages.success(request, "Saved")
        return HttpResponseRedirect(instance.get_absolute_url())
    context = {
        "title": instance.title,
        "instance": instance,
        "form":form,
    }
    return render(request, "post_form.html", context)


def post_delete(request, id=None):
    instance = get_object_or_404(Post, id=id)
    instance.delete()
    messages.success(request, "Successfully deleted")
    return redirect("posts:list")

有没有任何消息来源可以获得有关这类功能的帮助?

并且,是否有任何教程也包含如何实现登录表单?

谢谢。

1 个答案:

答案 0 :(得分:1)

据我所知,在最简单的情况下,你需要这样的东西。

from django import forms
from django.contrib.auth import authenticate

class AuthenticationForm(forms.Form):
    username = forms.CharField(max_length=254)
    password = forms.CharField(widget=forms.PasswordInput)

    def clean(self):
        username = self.cleaned_data['username']
        password = self.cleaned_data['password']
        user = authenticate(username=username, password=password)
        if user is None:
            raise forms.ValidationError('invalid_login')

        return self.cleaned_data

现在查看:

from django.contrib.auth import login
from django.http import HttpResponseRedirect
from django.template.response import TemplateResponse

def user_login(request):
    if request.method == "POST":
        form = AuthenticationForm(request, data=request.POST)
        if form.is_valid():
            login(request, form.get_user())

            # if you use named views you can use reverse here:
            # redirect_url = reverse('post_list')
            # Or even if you want to return back to previous url:
            # referrer = request.META['HTTP_REFERER']
            # if referrer:
            #     redirect_url =  referrer.split('/', 3)[3]
            redirect_url = '/post-list/'  # it's 'success page'
            return HttpResponseRedirect(redirect_url)  

    else:
        form = AuthenticationForm(request)

    return TemplateResponse(request, 'login.html', {'form': form})

现在您可以使用login_required装饰器来进行POST视图(创建/更新/删除),例如:

from django.contrib.auth.decorators import login_required

@login_required(login_url='/accounts/login/')
def post_delete(request, id=None):
    ...

登录表单(模板)的最简单示例:

<form method="post" action="{% url 'login' %}">
    {% csrf_token %}
    Username: {{ form.username }} {{ form.username.errors }}<br> 
    Password: {{ form.password }} {{ form.password.errors }}<br>
    {{ form.errors }}<br>
    <input type="submit" value="login" />
</form>`