将数据从视图传递到模板时出现问题?

2024-09-28 23:20:16 发布

您现在位置:Python中文网/ 问答频道 /正文

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

我试图将数据从一个视图传递到另一个模板,然后在视图中解析对象,但是由于某些原因,模板中没有发生任何事情。我已将注册对象打印在我的视图.py它工作正常,显示的信息正确无误。但是当我将注册对象从视图发送到模板时,什么也没有发生。你知道吗

型号.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',)

视图.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/')

模板结果.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>

Tags: form视图模板truemodelsemailhtmlregistration
1条回答
网友
1楼 · 发布于 2024-09-28 23:20:16

您的问题在于redirect()函数。您试图将registration对象传递给它,但它不支持这一点,它的*args和**kwargs只是用于反转url的参数,请参见此处:

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

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

请参见: 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/相信我,这将是非常值得你花时间的,因为从你的问题我可以很容易地看出你只是不明白你在做什么。你知道吗

相关问题 更多 >