将数据从视图传递到模板的问题?

时间:2018-04-21 09:36:33

标签: python django python-3.x

我是Django Python的新手,我正在学习如何使用Django并将数据从视图传递到模板。现在,这是我的情况,我真的需要一些帮助来理解我可能做错的地方。

我正在尝试将数据从视图传递到模板,然后在视图中解析对象,但由于某种原因,模板中没有发生任何事情。我在views.py中打印了注册对象,它工作正常并显示正确的信息。但是当我将注册对象从视图发送到模板时,没有任何事情发生。

models.py

    from django.db import models

    from datetime import datetime
    from django.shortcuts import redirect

    # Create your models here.

    # Create your models here.

    class Registration(models.Model):
        first_name = models.CharField(max_length=255, null=True, blank=True)
        last_name = models.CharField(max_length=255, null=True, blank=True)
        email = models.CharField(max_length=255, null=True, blank=True)
        password = models.CharField(max_length=255, null=True, blank=True)
        mobilenumber = models.CharField(max_length=255, null=True, blank=True)
        created_on = models.DateTimeField(auto_now_add=True, blank=True)

        class Meta:

            ordering = ('first_name',)

views.py

    class Loginview(CreateView):
        model = Registration
        form_class = LoginForm
        template_name = "loginvalentis/valentis_login.html"

        def get(self, request):
            form = LoginForm()

            # returning form
            return render(request, 'loginvalentis/valentis_login.html', {'form': form});

        def form_valid(self,form):
            user_email = form.cleaned_data.get('email')
            user_password = form.cleaned_data.get('password')
            try:
                registration = Registration.objects.get(email=user_email)
                print ("registration",registration.mobilenumber)




                return redirect('/loginvalentis/home/',{'registration':registration})

            except Registration.DoesNotExist:
                user_info = None
                return redirect('/loginvalentis/login/')

模板result.html ---(' / loginvalentis / home /')

<html>
<body>
<form id="form1">
    {% csrf_token %}
<div>
    hello world
    <form id ="form1">
        <ul>
  {% for user in registration %}
    <li>{{ user.mobilenumber }}</li>
  {% endfor %}
</ul>
    </form>
</div>


</form>
</body>
</html>

1 个答案:

答案 0 :(得分:0)

您的问题在于redirect()功能。你试图通过它传递registration对象,但它不支持这个,它的* args和** kwargs只是用于反转url的参数,请参见此处:

https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#django.shortcuts.redirect

您应该使用其他方式将其传递到另一个视图,例如只传递它的id作为该视图的url的参数(你必须适当地更改url conf),另一种方法是使用会话等。

请参阅: https://docs.djangoproject.com/en/2.0/topics/http/sessions/ https://docs.djangoproject.com/en/2.0/topics/http/urls/

但实际上,只要非常仔细地阅读本教程,就会更容易 https://docs.djangoproject.com/en/2.0/intro/tutorial01/相信我,非常值得你花时间,因为从你的问题我可以轻易地告诉你,你只是不明白你在做什么。

相关问题