You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

如何在Django注册表单下拉框中显示MySQL分类表的分类名称

Solution

First, fix the users/forms.py file. The key issues were using the wrong user model, incorrect field type for the foreign key, and not querying existing categories. Here's the corrected code:

from django import forms
from django.contrib.auth.forms import UserCreationForm
from blog.models import Category
from .models import CustomUser  # Import your custom user model

class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()

    # Use ModelChoiceField to populate dropdown with Category instances
    cid = forms.ModelChoiceField(
        queryset=Category.objects.all(),
        label='Specialization',
        empty_label=None  # Remove this line if you want an empty default option
    )

    class Meta:
        model = CustomUser  # Set model to your CustomUser instead of default User
        fields = ['username', 'email', 'password1', 'password2', 'cid']

Additional Required Step

Ensure your project's settings.py is configured to use your custom user model. Add or update this line:

AUTH_USER_MODEL = 'users.CustomUser'

Explanation of Changes

  • Model Choice Field: ModelChoiceField is Django's built-in field for foreign key relationships. It automatically fetches all Category objects from the database and uses the __str__ method of the Category model (which returns category_name) as the dropdown option labels.
  • Custom User Model: The form now uses CustomUser instead of the default User model, which matches your database structure where CustomUser has the cid foreign key.
  • Correct Queryset: Category.objects.all() retrieves all existing categories from the database, replacing the incorrect attempt to create a single empty Category instance.

This will populate the "Specialization" dropdown with all category names from your category table.

内容的提问来源于stack exchange,提问作者Sudipta Bhatta

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.08.09 17:35:27