我在 django 中有一个仪表板视图,其中必须显示用户的数据以及与其链接的其他模型。它没有显示其他模型的数据

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

我希望当用户登录应用程序时,它应该在添加详细信息后获取所有详细信息。比如钱包名称、API 密钥、用户名等,但它既不显示错误也不打印数据。 这是钱包(第二个)型号代码

class Wallet(models.Model):

    EXCHANGES = (
        ('Binance', 'Binance'),
        ('ByBit', 'ByBit'),
        ('Coinbase', 'Coinbase'),
        ('OKX', 'OKX'),
        ('Bitfinex', 'Bitfinex'),
        ('Gemini', 'Gemini'),
    )
    owner = models.ForeignKey('auth.User', related_name='wallets', on_delete=models.CASCADE)
    exchange_name = models.CharField(max_length=30, choices=EXCHANGES, null=True)
    api_key = models.CharField(max_length=255, null=True, blank=False, validators=[MinLengthValidator(64)])
    secret_key = models.CharField(max_length=255, null=True, blank=False, validators=[MinLengthValidator(64)])
    wallet_type = models.CharField(max_length=30,
                                   choices=(('spot', 'Spot'), ('futures', 'Futures'), ('margin', 'Margin')),
                                   default='Futures')
    date_connected = models.DateTimeField(auto_now_add=True, null=True)

    def __str__(self):
        return self.wallet_type

这是用户的模型

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

    user = models.OneToOneField(User, on_delete=models.CASCADE)
    # phone_number = models.CharField(max_length=20, blank=True, null=True)
    # username = models.ForeignKey(Users.username, on_delete=models.CASCADE, null=False)
    # wallet = models.ForeignKey('Wallet', on_delete=models.SET_NULL, null=True, blank=True)
    # Telegram = models.ForeignKey('Telegram', on_delete=models.SET_NULL, null=True, blank=True)
    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 DashboardView1(LoginRequiredMixin, TemplateView):
    template_name = 'dashboard.html'

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # Fetch the User instance based on the username
        user = User.objects.get(username='hasnain')

        # Fetch the UserProfile associated with the user
        user_profile = UserProfile.objects.get(user=user)

        # Fetch wallets and signals associated with the user
        wallets = Wallet.objects.filter(owner=user_profile)
        signals = Signal.objects.filter(owner=user_profile)

        context['user_profile'] = user_profile
        context['wallets'] = wallets
        context['signals'] = signals
        return context

这是序列化器的代码

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

这是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>
        <h1>Email: {{ user_profile.user.email }}</h1>
        
        <!-- Add any other user-related information here -->
    </header>

    <section>
        <h2>Plan:</h2>
        <p> {{ user_profile.plan }}</p>
        <br>
        <h2>Wallets1</h2>
        <ul>
            
            {% for wallets in wallet %}
            <li> wallet name {{ wallet.exchange_name }} - Type: {{ wallet.wallet_type }}</li>
            <li> api key {{ wallet.api_key }}</li>
            <li> secret key {{ wallet.secret_key }}</li>
            <li> date connected {{ wallet.date_connected }}</li>
            <!-- Display other wallet details as needed -->
            {% endfor %}
        </ul>
    </section>
    
    <section>
    <h2>Wallets</h2>
    <ul>
        {% for wallet in wallets %}
            <li> Wallet name {{ wallet.exchange_name }} - Type: {{ wallet.wallet_type }}</li>
            <li> API key {{ wallet.api_key }}</li>
            <li> Date connected {{ wallet.date_connected }}</li>
            <!-- Display other wallet details as needed -->
        {% endfor %}
    </ul>
</section>
    
        <br>
        <br>
        
    <!-- 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>

这是结果的图像。 (数据模糊) 图片

我尝试过使用

Wallet.objects.filter(owner=user_profile)
Wallet.objects.get(owner=user_profile)
但它们都不起作用

django django-templates
1个回答
0
投票

仔细查看您的代码,我相信错误来自您的模板文件,基于您在

wallets
dict
中调用时从
context["wallets"]
迭代查询集循环的方式,请确保您使用 ListView 而不是 TemplateView。

更正代码的模板部分

更新模板中的“Wallets1”部分,如下所示:

   <section>
       <h2>Wallets1</h2>
       <ul>
           {% for wallet in wallets %} # not for wallets in wallet
               <li>Wallet name {{ wallet.exchange_name }} - Type: {{ wallet.wallet_type }}</li>
               <li>API key {{ wallet.api_key }}</li>
               <li>Secret key {{ wallet.secret_key }}</li>
               <li>Date connected {{ wallet.date_connected }}</li>
               <!-- Display other wallet details as needed -->
           {% endfor %}
       </ul>
   </section>

但是,为了使您的用户配置文件过滤更加动态,而不是像您那样过滤名为 hasnain 的静态用户名实例 这里=>

user = User.objects.get(username='hasnain')
,直接从
request user.username
获取登录的用户名参数。

所以,这是您的查看代码的更新版本:
    template_name = 'dashboard.html'
    queryset = Wallet.objects.all()

    def get_context_data(self, **kwargs):
        context = super().get_context_data(**kwargs)

        # Fetch the User instance based on the username
        user = self.request.user
        user = User.objects.get(user=user)
        # You can actually get the username from user.username in your template if you want, again I discovered that you commented out username instance (field) in your userprofile, so using user.username here makes no sense.

        # Fetch the UserProfile associated with the user
 
        user_profile = UserProfile.objects.get(user=user)

        # Fetch wallets and signals associated with the user
        wallets = Wallet.objects.filter(owner=user_profile)
        signals = Signal.objects.filter(owner=user_profile)

        context['user_profile'] = user_profile
        context['wallets'] = wallets
        context['signals'] = signals
        return context

祝你好运

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