How to link address model to views

ぃ、小莉子 提交于 2019-12-08 05:04:26

问题


I'm trying to create an address form with multiple address, where the user can choose home or shipping address. I have the current model:

from django.db import models
from django.contrib.auth.models import User
from PIL import Image


class Address(models.Model):
    name = models.CharField(max_length=30)
    address = models.CharField(max_length=50)
    city = models.CharField(max_length=60, default="Miami")
    state = models.CharField(max_length=30, default="Florida")
    zipcode = models.CharField(max_length=5, default="33165")
    country = models.CharField(max_length=50)

    class Meta:
        verbose_name = 'Address'
        verbose_name_plural = 'Address'

    def __str__(self):
        return self.name

So I was wondering if that's correct.

Anyway, I was wondering how with the current model I can create a view so I can have the address form. Using a normal model would be "easy" but how can I do it using the through option in the model?

Could someone lend me a hand please?

Thank you


回答1:


use a foreign key to point to your address model:

class Profile(models.Model):
    user = models.OneToOneField(User, on_delete=models.CASCADE)
    nick_name = models.CharField('Nick name', max_length=30, blank=True, default='')
    bio = models.TextField(max_length=500, blank=True)
    image = models.ImageField(default='default.jpg', upload_to='profile_pics')
    addresses = models.ForeignKey(Address) # <-- fix here

Hope this helps!




回答2:


You should declare ForeignKey with '<app>.<model>' format:

class AddressType(models.Model):   
    address = models.ForeignKey('yourapp.Address', on_delete=models.CASCADE)
    profile = models.ForeignKey('yourapp.Profile', on_delete=models.CASCADE)

or directly give the class:

    address = models.ForeignKey(Address, on_delete=models.CASCADE)
    profile = models.ForeignKey(Profile, on_delete=models.CASCADE)



回答3:


Both of the other answers were incorrect, I ended up modifying everything and also creating a new model, here it is:

class Address(models.Model):
    name = models.CharField(max_length=100, blank=False)
    address1 = models.CharField("Address lines 1", max_length=128)
    address2 = models.CharField("Address lines 2", max_length=128, blank=True)
    city = models.CharField("City", max_length=64)
    # state = USStateField("State", default='FL')
    state = models.CharField("State", max_length=128, default='FL')
    zipcode = models.CharField("Zipcode", max_length=5)
    user = models.ForeignKey(Profile, on_delete=models.CASCADE, blank=False)

    class Meta:
        verbose_name_plural = 'Address'

    def __str__(self):
        return self.name


来源:https://stackoverflow.com/questions/54912928/how-to-link-address-model-to-views

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!