如何在django,python上使用'redirect'和'message'(how to use 'redirect' and 

编程入门 行业动态 更新时间:2024-10-26 01:32:02
如何在django,python上使用'redirect'和'message'(how to use 'redirect' and 'message' on django, python)

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

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

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')

我还没有理解'redirect()'里面'成功'是如何进入的

这是我目前正在进行的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")

有什么来源我可以获得有关这些功能的帮助吗?

还有,还有任何教程,涵盖如何实现登录表单?

谢谢。

I am following the following tutorial link in order to create a page where there is login box, as well as a post form.

what im trying to accomplish here is to have only the people who are logged into the site be able to write on the post form, and submit the content.

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

If you go to the link above, Under the 'How to log a user in' section, it basically tells me to use

'redirect to a success page' and 'return a disabled account error message'and 'return an invalid login error message'

the problem here is that, It's been only a few days that I started learning about python and django, and every time such function is necessary, i mostly cannot find any source to learn those functions, or get the codes from.

I already searched on google and stackoverflow for the 'redirection' but the example i was able to get was this:

@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')

and i am yet to understand how the 'success' got in there inside 'redirect ()'

And here is the views.py that im currently working on.

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")

is there any source i can get help regarding these kind of functions?

and also, are there any tutorials that cover how to implement the login form as well?

thank you.

最满意答案

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

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>`

As I understand, in simplest case you need something like this.

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

Now view:

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})

And now you can use login_required decorator for your POST views (create/update/delete), for example:

from django.contrib.auth.decorators import login_required @login_required(login_url='/accounts/login/') def post_delete(request, id=None): ...

Simplest example for login form (template):

<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>`

更多推荐

本文发布于:2023-08-07 21:51:00,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/1466022.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:如何在   django   python   redirect   message

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!