我正在 django 中创建一个仪表板视图来显示用户的所有数据,但当我使用基于类的视图时它什么也不显示..?

问题描述 投票:0回答:1

当我使用基于函数的视图时,它工作正常。谁能帮助我吗?

这是模型

class UserProfile(models.Model):
    @property
    def getter_signal_limit(self):
        return self.signal_limit

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    webhook_url = serializers.SerializerMethodField()  # "https://www.tradify.com/api/" + hashlib.sha256(str(User.username).encode()).hexdigest()
    signal_limit = models.IntegerField(default=50, validators=[MinValueValidator(1)])
    signals_used = models.IntegerField(default=0)
    plan = models.CharField(max_length=12, choices=(
        ('Basic', 'Basic'), ('standard', 'Standard'), ('premium', 'Premium'), ('platinum', 'Platinum')),
                            default='Basic')
    created = models.DateTimeField(auto_now_add=True, blank=True)
    timezone = timezone.get_current_timezone()

这是用户序列化器代码

class UserProfileSerializer(serializers.ModelSerializer):
    user = UserSerializer()

    class Meta:
        model = UserProfile
        fields = '__all__'
        # fields = ('user', 'signal_limit', 'signals_used', 'plan', 'created', 'webhook_url')
        # read_only_fields = ('user', 'created')

    def create(self, validated_data):
        user_data = validated_data.pop('user')
        user = UserSerializer.create(**user_data)
        user_profile = UserProfile.objects.create(user=user, **validated_data)
        return user_profile

这是基于函数的视图

login_required
def dashboard(request):
    user_profile = request.user.userprofile
    context = {
        'user_profile': user_profile,
        'signal_limit': user_profile.signal_limit,
        'signals_used': user_profile.signals_used,
        'plan': user_profile.plan,
        'webhook_url': user_profile.get_webhook_url(),
        'timezone': user_profile.timezone,
    }
    return render(request, 'dash.html', context)

这是它的 html 代码

<!-- dashboard.html -->
<h1>Dashboard</h1>

<p>Username: {{ user_profile.user.username }}</p>
<p>Signal Limit: {{ signal_limit }}</p>
<p>Signals Used: {{ signals_used }}</p>
<p>Plan: {{ plan }}</p>
<p>Webhook URL: {{ webhook_url }}</p>
<p>Timezone: {{ timezone }}</p>

虽然此代码未显示用户的任何数据

基于类的视图:

class DashboardView(LoginRequiredMixin, TemplateView):
    template_name = 'dashboard.html'

    def get(self, request, **kwargs):
        user_profile = request.user
        context = {
            # user_profile = self.request.user.userprofile
            'user_profile': user_profile,
            'signal_limit': user_profile.signal_limit,
            'signals_used': user_profile.signals_used,
            'plan': user_profile.plan,
            'webhook_url': user_profile.get_webhook_url(),
            'timezone': user_profile.timezone,
        }
        return render(self.request, self.template_name, context)

这是 html 代码

<!DOCTYPE html>
<html lang="en">
<head>
    <meta charset="UTF-8">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Dashboard</title>
    <!-- Add your CSS stylesheets or links to frameworks here -->
</head>
<body>
    <header>
        <h1>Welcome, {{ user_profile.user.username }}</h1>
        <p>Email: {{ user_profile.user.email }}</p>
        <p>Plan: {{ user_profile.plan }}</p>
        <!-- Add any other user-related information here -->
    </header>

    <section>
        <h2>Wallets</h2>
        <ul>
            {% for wallet in wallets %}
                <li>{{ wallet.exchange_name }} - Type: {{ wallet.wallet_type }}</li>
                <!-- Display other wallet details as needed -->
            {% endfor %}
        </ul>
    </section>

    <section>
        <h2>Signals</h2>
        <ul>
            {% for signal in signals %}
                <li>{{ signal.strategy_name }} - Symbol: {{ signal.symbol }}</li>
                <!-- Display other signal details as needed -->
            {% endfor %}
        </ul>
    </section>

    <!-- Add more sections or elements as necessary -->

    <footer>
        <!-- Add footer content if needed -->
    </footer>

    <!-- Add your JavaScript files or links to frameworks here -->
</body>
</html>
 

请看图片

它应该显示用户在注册时输入的所有数据以及模型中的其余实体。 如果有人提供一些深入学习 django 的链接或来源,这将很有帮助,因为我是初学者

django django-templates
1个回答
0
投票

我很高兴您正在使用 Django,并且您想针对基于类的视图 (CBV) 来试验基于函数的视图。 -:)

下面是基于类的视图代码的更新版本,带有一些注释。


from django.contrib.auth.mixins import LoginRequiredMixin
from django.views import generic

# import your UserProfile from your app <path>

class DashboardView(LoginRequiredMixin, generic.ListView):
    """  returns the list of data for the authorized logged in user profile """

    #  TemplateView only renders a template, so it is of no use here, rather use ListView
    # which is preferred imo 

    template_name = 'dashboard.html'
    queryset = UserProfile.objects.all()

    def get(self, request, **kwargs):
        
        # get each individual userprofile 
        user_profile = self.request.user.userprofile
        print(user_profile) - do some debugging here to make sure that there is indeed a userprofile in your db.

        
        context = {
            # user_profile = self.request.user.userprofile
            'user_profile': user_profile,
            'signal_limit': user_profile.signal_limit,
            'signals_used': user_profile.signals_used,
            'plan': user_profile.plan,
            'webhook_url': user_profile.get_webhook_url(),
            'timezone': user_profile.timezone,
        }
        return render(self.request, self.template_name, context)
       # I see no issue in your HTML but bear in mind that the above context will only be available in your HTML headers tag.

此案例中需要牢记的其他故障排除信息包括:

  • 检查用户身份验证:确保用户在访问仪表板时经过身份验证。如果用户未登录,request.user 对象将没有有效的用户配置文件。

  • 验证用户配置文件数据:确认用户配置文件模型包含预期数据。检查是否为用户正确填充了 signal_limit、signals_used、plan、webhook_url 和 timezone 字段。

有关如何使用 CBV 的更多信息,请查看包含许多示例的文档。 祝你好运!

© www.soinside.com 2019 - 2024. All rights reserved.