我创建了一个模型,存储了跟踪信息,mp3,png和slug以及与该模型相关联的用户名。
我可以很好地保存模型,但是当我尝试保存另一个模型时(因此有两个模型具有相同的用户名),django告诉我"跟踪此用户已经存在!&#34 ;
我不想要这个,我希望能够为同一个用户保存我想要的模型。
这是我的models.py(我在管理面板中注册了它)
from django.db import models
from django.core.exceptions import ValidationError
from django.core.files.images import get_image_dimensions
from django.contrib.auth.models import User
# Create your models here.
class Track(models.Model):
def generate_user_folder_tracks(instance, filename):
return "uploads/users/%s/tracks/%s.mp3" % (instance.user, instance.slug)
def is_mp3(self):
if not self.name.endswith('.mp3'):
raise ValidationError(u'You may only upload mp3 files for tracks!')
def generate_user_folder_art(instance, filename):
return "uploads/users/%s/art/%s.png" % (instance.user, instance.slug)
def is_square_png(self):
if not self.name.endswith('.png'):
raise ValidationError("You may only upload png files for album art!")
else:
w, h = get_image_dimensions(self)
if not h == w:
raise ValidationError("This picture is not square! Your picture must be equally wide as its height.")
else:
if not (h + w) >= 1000:
raise ValidationError("This picture is too small! The minimum dimensions are 500 by 500 pixels.")
return self
# Variables
track_type_choices = [
('ORG', 'Original'),
('RMX', 'Remix'),
('CLB', 'Collab'),
('LIV', 'Live'),
]
# Model Fields
user = models.ForeignKey(User, unique=True)
title = models.CharField(max_length=100)
desc = models.TextField(max_length=7500)
track_type = models.CharField(max_length=3,
choices=track_type_choices,
default='ORG')
track_type_content = models.CharField(max_length=100,blank=True)
created = models.TimeField(auto_now=True,auto_now_add=False)
upload = models.FileField(upload_to=generate_user_folder_tracks,validators=[is_mp3])
albumart = models.ImageField(upload_to=generate_user_folder_art,validators=[is_square_png])
slug = models.SlugField(max_length=50)
对这里发生的事情有任何想法吗?
答案 0 :(得分:2)
user = models.ForeignKey(User, unique=True)
unique = true
表示每个模型都需要拥有不同的用户。这类似于Django的OneToOne field。
确保你运行
python manage.py makemigrations
和
python manage.py migrate