如何在django表单的下拉列表中显示mysql数据库表中的类别名称



我正在使用django的文章管理平台webapp。我使用django表单创建了一个注册表单,我想从类别表中显示类别名称。

这是创建类别表的代码,其中我有两列。一个是cid,表示ID,另一个是category_name。这里的类别名称将是例如:技术,软件工程,医学等。

blog.models.py

from django.db import models
# Create your models here.
class Category(models.Model):
cid = models.AutoField(primary_key=True, blank=True)
category_name = models.CharField(max_length=100)
def __str__(self):
return self.category_name

cid是用户表的外键,因为每个用户必须从专门化字段中选择一个类别名称来注册这个应用程序中的帐户在用户表中添加cid作为外键,如下所示

用户/model.py

from django.db import models
from blog.models import Category
from django.contrib.auth.models import AbstractUser
# Create your models here.
class CustomUser(AbstractUser):
cid = models.ForeignKey(Category, on_delete=models.CASCADE)

在forms.py文件的中,我添加了电子邮件和专门化字段,以便在注册表单中显示它们,如下所示。但是,我不确定类别代码部分是否可以。你能调查一下吗?用户/forms.py

from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from blog.models import Category
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
category = Category()

cid = forms.CharField(label='Specialization', widget=forms.Select(choices=category.category_name))

class Meta:
model = User
fields = ['username', 'email', 'password1', 'password2', 'cid']

register.html文件:

register.html文件
{% extends "users/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
{{ form| crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="{% url 'login' %}">Sign In</a>
</small>
</div>
</div>
{% endblock content %}

我想在专门化下拉列表中显示类别名称,该列表将来自分类表,但这些类别名称没有显示在下拉列表中。注册页面UI

我不明白如何解决这个问题。有人能帮我解决这个问题吗?解决这个问题的编码部分是什么呢?

我尝试在专门化下拉列表中添加类别名称,但失败了。我希望任何人都能解决这个问题

首先,category需要是一个字段,而不是一个类。使用ModelChoiceField

最新更新