如何在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:
ModelChoiceFieldis Django's built-in field for foreign key relationships. It automatically fetches allCategoryobjects from the database and uses the__str__method of theCategorymodel (which returnscategory_name) as the dropdown option labels. - Custom User Model: The form now uses
CustomUserinstead of the defaultUsermodel, which matches your database structure whereCustomUserhas thecidforeign key. - Correct Queryset:
Category.objects.all()retrieves all existing categories from the database, replacing the incorrect attempt to create a single emptyCategoryinstance.
This will populate the "Specialization" dropdown with all category names from your category table.
内容的提问来源于stack exchange,提问作者Sudipta Bhatta
相关产品推荐
相关产品推荐

