Django重定向到上一页不起作用

时间:2016-06-30 18:02:52

标签: html django url-redirection

您好我想在django中提交表单后重定向到上一个。它成功重定向到上一页但没有发生后期操作。如果删除action属性,我可以成功发布数据。

这是我的表单模板。

if (Build.VERSION.SDK_INT>=Build.VERSION_CODES.M) {
  // call that method
}

这是views.py文件

{% extends 'musicapp/base.html' %} {% block content %}
<!-- <h1>New post</h1> -->
<form method="POST" action={{ request.META.HTTP_REFERER }} class="post-form">{% csrf_token %}



<div class="add_track_form" >

  <div class="col-sm-6">
      <section class="panel panel-default">
          <header class="panel-heading font-bold">Add Genre</header>
          <div class="panel-body">
              <form action="{% url 'post_list' %}" role="form">
                  <div class="form-group">

                      <label>Title</label>
                       {{ form.name }}
                  </div>
                  <input type="hidden" name="next" value="{{ request.path }}">
                  <button type="submit" class="btn btn-sm btn-default">Submit</button>
              </form>
          </div>
      </section>
  </div>

</div>


</form>

{% endblock %}

这些是URL路由。

from django.shortcuts import render, get_object_or_404, redirect, render_to_response
from django.http import HttpResponseRedirect
from .forms import AddTrackForm, AddGenreForm
from django.http import HttpResponse
from .models import Track, Genre
from . import getAlbumArt

# Create your views here.
def home(request):
    tracks = Track.objects.all().order_by('created_date')
    return render(request, 'musicapp/post_list.html', {'tracks': tracks})

def post_detail(request, pk):
    track = get_object_or_404(Track, pk=pk)
    # print post
    return render(request, 'musicapp/post_detail.html', {'track': track})
# def post_new(request):
#     form = AddTrackForm()
#     return render(request, 'musicapp/post_edit.html', {'form': form})

def post_new(request):
    if request.method == "POST":
        form = AddTrackForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            artist = request.POST.get("artist", "")
            album = request.POST.get("album", "")
            # print artist, album
            urlArt = getAlbumArt.getAlbumArtURL(album, artist)
            print urlArt
            if urlArt:
                post.cover_image_url = urlArt
            if post.album == '*':
                post.album = 'Unknown'
            post.save()
            tracks = Track.objects.all().order_by('created_date')
            return render(request, 'musicapp/post_list.html', {'tracks': tracks})
    else:
        form = AddTrackForm()
    return render(request, 'musicapp/post_edit.html', {'form': form})

def post_edit(request, pk):
    post = get_object_or_404(Track, pk=pk)
    if request.method == "POST":
        form = AddTrackForm(request.POST, instance=post)
        if form.is_valid():
            post = form.save(commit=False)
            artist = request.POST.get("artist", "")
            album = request.POST.get("album", "")
            # print artist, album
            urlArt = getAlbumArt.getAlbumArtURL(album, artist)
            print urlArt
            if urlArt:
                post.cover_image_url = urlArt
            if post.album == '*':
                post.album = 'Unknown'
            post.save()
            tracks = Track.objects.all().order_by('created_date')
            return redirect('post_detail', pk=post.pk)
    else:
        form = AddTrackForm(instance=post)
    return render(request, 'musicapp/post_edit.html', {'form': form})

def genre(request):
    tracks = Track.objects.all().order_by('created_date')
    genres = Genre.objects.all()
    return render(request, 'musicapp/genre.html', {'genres': genres, 'tracks': tracks})

def genre_songs(request, pk):
    genres = Genre.objects.all()
    genre_obj = get_object_or_404(Genre, pk=pk)
    tracks = genre_obj.track_set.all()
    # print post
    return render(request, 'musicapp/genre_songs.html', {'genres': genres, 'genre' : genre_obj, 'tracks': tracks})

def genre_new(request):
    if request.method == "POST":
        form = AddGenreForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            post.save()
            genres = Genre.objects.all()
            print request.META.HTTP_REFERER
            next = request.POST.get('next', '/')
            # return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
            # print next
            # return HttpResponseRedirect(next)
            # return HttpResponseRedirect('/')
            return render_to_response('musicapp/post_edit.html', {'form': AddTrackForm()})
    else:
        form = AddGenreForm()
    return render(request, 'musicapp/genre_edit.html', {'form': form})

6 个答案:

答案 0 :(得分:2)

看看这个:

<input type="hidden" name="next" value="{{ request.path }}" />

request.path提供当前页面的路径,而不是之前的路径。因此,您当前正在提交表单提交的同一页面的下一个值。

{{ request.META.HTTP_REFERER }}提供引荐页面。那么为什么要将表单发布到上一页呢?但应注意,这可能具有值None(或引用页面可能来自另一个域)。

我假设您有表单的动作参数,并且您的“下一个”隐藏输入的值已切换。否则,您可能会有不必要的复杂逻辑。

答案 1 :(得分:1)

你有两种形式,它们是嵌套的。内部表单使用GET(如果没有指定,则默认使用GET),外部表单使用POST。这纯粹是混乱,你不应该这样做。如果你解决了这个问题,我相信这个bug也会得到解决。

{{ request.META.HTTP_REFERER }}不一定是您考虑的上一页。你不应该这样使用它。我会使用GET(例如使用'?prev=/url/before/form/')来记住用户来自哪个页面。

答案 2 :(得分:0)

替换你的urls.py

 url(r'^$', views.home, name='post_list'),

 url(r'^postlist/$',views.home, name='post_list'),

并以您的形式

<form action="{% url 'post_list' %}" role="form">

<form action="/postlist" role="form" method="POST">

答案 3 :(得分:0)

所以我通过比较我们点击链接的URL然后根据之前的设置隐藏字段来解决我的问题 URL (request.META.HTTP_REFERER)并根据我从模板中获取的标志值重定向。

这是我的模板

{% extends 'musicapp/base.html' %} {% block content %}
<!-- <h1>New post</h1> -->
<form method="POST" class="post-form">{% csrf_token %}



<div class="add_track_form" >

  <div class="col-sm-6">
      <section class="panel panel-default">
          <header class="panel-heading font-bold">Add Genre</header>
          <div class="panel-body">

                  <div class="form-group">

                      <label>Title</label>
                       {{ form.name }}
                  </div>

                  {% if 'track/new/' in request.META.HTTP_REFERER %}
                    <input class="form-control" type="hidden" value = 0 id="flag" maxlength="50" name="flag" type="text">
                  {% else %}
                    <input class="form-control" type="hidden" value = 1 id="flag" maxlength="50" name="flag" type="text">
                  {% endif %}
                  <button type="submit" class="btn btn-sm btn-default">Submit</button>

          </div>
      </section>
  </div>

</div>


</form>

{% endblock %}

这是观点功能:

def genre_new(request):
    if request.method == "POST":
        form = AddGenreForm(request.POST)
        if form.is_valid():
            post = form.save(commit=False)
            redirect_flag = request.POST.get("flag", "")  # redirect to different places depending upon where it was clicked
            post.save()
            genres = Genre.objects.all()
            print redirect_flag
            if redirect_flag == '0':
                return HttpResponseRedirect(reverse('post_new'))
            elif redirect_flag == '1':
                return HttpResponseRedirect(reverse('genre_list'))
            else:
                return HttpResponseRedirect('/')

    else:
        form = AddGenreForm()
    return render(request, 'musicapp/genre_edit.html', {'form': form})

有更简单的方法吗?

答案 4 :(得分:0)

我认为我有一个更简单的方法。

模板:

<div hidden>
     <input name="url_get" value={{ url_ref }}>
</div>

查看:

url_get = request.POST.get('url_get')
if url_get:
   url_ref = url_get
else:
   url_ref = request.META.get('HTTP_REFERER')
args['url_ref'] = url_ref

所以,我们总是有第一个网址

答案 5 :(得分:0)

这似乎很长一段时间了,但应用了伊恩·普林斯(Ian Prince)的推理。请注意所做的一些更改。

{% extends 'musicapp/base.html' %} {% block content %}
<!-- <h1>New post</h1> -->
<form method="POST" class="post-form">{% csrf_token %}



<div class="add_track_form" >

  <div class="col-sm-6">
      <section class="panel panel-default">
          <header class="panel-heading font-bold">Add Genre</header>
          <div class="panel-body">
              <form action="{% url 'post_list' %}" role="form">
                  <div class="form-group">

                      <label>Title</label>
                       {{ form.name }}
                  </div>
                  <input type="hidden" name="next" value="{{ request.META.HTTP_REFERER }}">
                  <button type="submit" class="btn btn-sm btn-default">Submit</button>
              </form>
          </div>
      </section>
  </div>

</div>


</form>

{% endblock %}

这些更改包括:

action='{{ request.META.HTTP_REFERER }}'
<!-- although this was posted as: action={{ request.META.HTTP_REFERER }} -->

和以下内容的更改:

value="{{ request.path }}"

收件人:

value="{{ request.META.HTTP_REFERER }}"

那解决了我的问题。我希望它能解决您的问题