如何将我当前的Django应用程序转换为restapi?

2024-04-20 07:54:47 发布

您现在位置:Python中文网/ 问答频道 /正文

我需要将我当前的django应用程序转换为restapi,它是一个带有电子邮件和电话号码验证的UserCreationForm。但首先我需要注册的文本字段到django管理网站有电话号码,电子邮件和密码字段。但是在我的管理员.py“在”管理网站注册(UserRegisterForm)”,当我运行python时管理.pymakemigrations时,发生了一个错误,它声明TypeError:“ModelFormMetaclass”对象不可iterable。我不确定管理网站不接受任何用户窗体中的字段,它们只接受模型。 这是我的密码:

/* forms.py */
import re
import phonenumbers
from phonenumbers import carrier
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from validate_email import validate_email
# from django.db import models
# from django_countries.fields import CountryField, countries
# from phonenumber_field.formfields import PhoneNumberField


class UserRegisterForm(UserCreationForm):
    email = forms.EmailField()
    # phone_number = PhoneNumberField()
    phone_number = forms.CharField(max_length=100)
    # country = CountryField(blank_label='Select Country').formfield()
    country = forms.CharField(max_length=2)

    class Meta:
        model = User
        fields = ['username', 'email', 'country', 'phone_number']

    def clean_email(self):
        email = self.cleaned_data.get("email")
        if not validate_email(email, check_mx=True, verify=True):
            raise forms.ValidationError("Invalid email")
        return email

    def clean_phone_number(self):
        phone_number = self.cleaned_data.get("phone_number")
        clean_number = re.sub("[^0-9&^+]", "", phone_number)
        # alpha_2 = self.cleaned_data.get("country")
        alpha_2 = self.cleaned_data.get("country")
        z = phonenumbers.parse(clean_number, "%s" % (alpha_2))
        if len(clean_number) > 15 or len(clean_number) < 3:
            raise forms.ValidationError(
                "Number cannot be more than 15 or less than 3")
        if not phonenumbers.is_valid_number(z):
            raise forms.ValidationError(
                "Number not correct format or non-existent")
        if carrier.name_for_number(z, "en") == '':
            raise forms.ValidationError("Please enter a mobile number")
        return phonenumbers.format_number(
            z, phonenumbers.PhoneNumberFormat.E164)


/* admin.py */
from django.contrib import admin
from .forms import UserRegisterForm

admin.site.register(UserRegisterForm)
# Register your models here.

请告诉我应该对当前代码做什么更改,并告诉我哪里做错了。你知道吗


Tags: djangofromimportselfcleannumberdataget
1条回答
网友
1楼 · 发布于 2024-04-20 07:54:47

恐怕您不能真正地将窗体(前端组件)转换为REST-API(后端接口)。这就像让理发师用剪刀把你的头发剪长一样。你知道吗

但是。。你可以用你的型号.py在一个新的django REST项目中。你知道吗

建议:

  • 启动一个新的django项目并添加所需的应用程序(使用django cli)。你知道吗

安装django rest

  • pip install djangorestframework并将('django\u rest')添加到已安装的应用程序
    (设置.py)你知道吗
  • 从型号.py进入型号.py你的新应用
  • 创建(模型)序列化程序(检查I/O模型中的所有数据)
  • 为每个端点创建视图(这是您的接口)
  • 运行python manage.py makemigrations
  • 运行python manage.py migrate
  • 你现在有了一个工作RESTAPI!!你知道吗

最后:您的管理站点允许您(可视化地)与模型及其数据交互。它是为你的网站管理员,它不做任何其他事情。你知道吗

相关问题 更多 >