简体   繁体   English

Django如何在创建视图中显示其他模型的字段?

[英]How do I display fields of other models in a create view in Django?

I'm trying to create some entries in the database.我正在尝试在数据库中创建一些条目。 I am not able to input anything for the Address models.我无法为地址模型输入任何内容。 I would like to be able to add the individual fields of the shipping_address.我希望能够添加 shipping_address 的各个字段。 How can I achieve this?我怎样才能做到这一点?

serializer串行器

class UserSerializer(serializers.ModelSerializer):
    """Serializer for the users object"""

    class Meta:
        model = get_user_model()
        fields = ('email', 'password', 'first_name', 'last_name', 'mailing_address', 'shipping_address', 'phone', 'is_active', 'is_staff', 'is_approver')

    def create(self, validated_data):
        """Create a new user with encrypted password and return it"""
        return get_user_model().objects.create_user(**validated_data)

models楷模

   class Address(models.Model):
        first_address = models.CharField(max_length=255, blank=True, default='')
        second_address = models.CharField(max_length=255, blank=True, default='')
        city = models.CharField(max_length=255, blank=True, default='')
        state = models.CharField(max_length=255, blank=True, default='')
        zip = models.CharField(max_length=255, blank=True, default='')
    
    
    class Phone(models.Model):
        phone_number = PhoneField(blank=True, help_text='Contact phone number')
    
    
    class ShippingAddress(models.Model):
        first_address = models.CharField(max_length=255, blank=True, default='')
        second_address = models.CharField(max_length=255, blank=True, default='')
        city = models.CharField(max_length=255, blank=True, default='')
        state = models.CharField(max_length=255, blank=True, default='')
        zip = models.CharField(max_length=255, blank=True, default='')
    
    
    class User(AbstractBaseUser, PermissionsMixin):
        """Custom user model that suppors using email instead of username"""
        email = models.EmailField(max_length=255, unique=True)
        first_name = models.CharField(max_length=255, blank=True, default='')
        last_name = models.CharField(max_length=255, blank=True, default='')
        password = forms.CharField(widget=forms.PasswordInput)
        phone = models.ForeignKey(Phone, on_delete=models.CASCADE, null=True, blank=True)
        mailing_address = models.ForeignKey(Address, on_delete=models.CASCADE, null=True, blank=True)
        shipping_address = models.ForeignKey(ShippingAddress, on_delete=models.CASCADE, null=True, blank=True)
        is_active = models.BooleanField(default=True)
        is_staff = models.BooleanField(default=False)
        is_approver = models.BooleanField(default=False)
    
        objects = UserManager()
    
        USERNAME_FIELD = 'email'

在此处输入图像描述

I think you can use DRF's writable nested serializer .我认为您可以使用 DRF 的可写嵌套序列化程序。

Something like these (haven't tested it yet):像这样的东西(还没有测试过):

  • Add a serializer for the Address model:Address model 添加一个序列化器:

     class AddressSerializer(serializers.ModelSerializer): class Meta: model = Address fields = '__all__'
  • And modify your current serializer for the User model (just like @Code-Apprentice said the comment, you can use the same Address model for both mailing_address and shipping_address ):并为User model 修改您当前的序列化程序(就像@Code-Apprentice 所说的评论,您可以对mailing_addressshipping_address使用相同的Address model):

     class UserSerializer(serializers.ModelSerializer): """Serializer for the users object""" mailing_address = AddressSerializer() shipping_address = AddressSerializer() class Meta: model = get_user_model() fields = ('email', 'password', 'first_name', 'last_name', 'mailing_address', 'shipping_address', 'phone', 'is_active', 'is_staff', 'is_approver') def create(self, validated_data): """Create a new user with encrypted password and return it""" mailing_address = Address.objects.create(**validated_data.pop('mailing_address')) shipping_address = Address.objects.create(**validated_data.pop('shipping_address')) return get_user_model().objects.create_user(mailing_address=mailing_address, shipping_address=shipping_address, **validated_data)

How do I display fields of other models in a create view in Django? Django如何在创建视图中显示其他模型的字段?

One thing to be careful about here: Django Rest Framework provides a convenient Web interface to interact with the REST API you are building.这里需要注意一件事: Django Rest 框架提供了一个方便的 Web 接口来与您正在构建的 REST API 进行交互。 However, this is not the only way, and probably not even the most common way, to interact with your API.然而,这不是与您的 API 交互的唯一方式,甚至可能不是最常用的方式。

In fact, users of your app, SHOULD NOT SEE THIS WEB INTERFACE.事实上,您应用的用户不应该看到这个 WEB 界面。 Instead, you should build your own interface which interacts with your REST API. This gives you the flexibility to create whatever forms in HTML that you want.相反,您应该构建自己的界面,该界面与您的 REST API 交互。这使您可以灵活地在 HTML 中创建您想要的任何 forms。

For example, you can create a single form with all of the user fields along with fields for a shipping address and for a separate billing address.例如,您可以创建一个表单,其中包含所有用户字段以及送货地址字段和单独的账单地址字段。 Then you write JavaScript in the front end to create the Address objects with POST requests to your API. The POST request will return an id of the new address object. Then you make another POST request to create a user, with that id and all of the other user fields.然后你在前端写入 JavaScript 来创建Address对象,并向你的 API 发送 POST 请求。POST 请求将返回新地址 object 的 id。然后你发出另一个 POST 请求来创建一个用户,使用该id和所有的其他用户字段。

On a side note, there is no need for a ShippingAddress model which has the exact same fields as your Address model. Just use Address for all address fields:在旁注中,不需要ShippingAddress model,它与您的Address model 具有完全相同的字段。只需对所有地址字段使用Address

        mailing_address = models.ForeignKey(Address, on_delete=models.CASCADE, null=True, blank=True)
        shipping_address = models.ForeignKey(Address, on_delete=models.CASCADE, null=True, blank=True)

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM