我希望从用户导入的标题自动生成slug,或者如果标题为空,则生成随机整数。我目前拥有它的方式,slug应该从表单标题填充,但是我得到一个错误,表示表单没有标题字段。
所以,我需要:
有人可以帮帮我吗?
提前谢谢!我感谢任何帮助!
forms.py:
class PhotoUploadForm(forms.ModelForm):
title = forms.CharField(
widget=forms.TextInput(attrs={"placeholder": "Title of photo", "size": "30"})
)
description = forms.CharField(
widget=forms.Textarea(attrs={"placeholder": "Description of photo"})
)
class Meta:
model = Photo
fields = ('category', 'title', 'description', 'image')
models.py:
class Photo(models.Model):
creator = models.ForeignKey(MyUser, null=False, blank=False)
title = models.CharField(max_length=30, null=True, blank=True)
description = models.TextField(max_length=120, null=True, blank=True)
image = models.ImageField(upload_to='user/photos/', null=True, blank=True)
slug = models.SlugField(null=False, blank=False)
active = models.BooleanField(default=True)
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
class Meta:
ordering = ['-timestamp']
def __unicode__(self):
return "%s" %(self.creator)
views.py:
def photo_upload_view(request, username):
u = MyUser.objects.get(username=username)
form = PhotoUploadForm()
if request.method == 'POST':
form = PhotoUploadForm(request.POST or None, request.FILES)
new_slug = Photo.objects.get(slug=form.title)
if form.is_valid():
obj = form.save(commit=False)
obj.creator = request.user
obj.slug = slugify(new_slug)
obj.save()
messages.success(request, "Thank you! You have successfully posted your picture!")
return HttpResponseRedirect('/')
else:
form = PhotoUploadForm()
submit_btn = "Upload Post"
context = {
"submit_btn": submit_btn,
"form": form
}
return render(request, "photos/photo_upload.html", context)
答案 0 :(得分:0)
这一行是你的问题:
new_slug = Photo.objects.get(slug=form.title)
您将new_slug
的值设置为检索到的对象,而不是字符串。那不会贬值。你可能只是想要这个:
new_slug = form.title
但是如果你真的想从Photo中检索一个值,那么最后引用那个属性,所以:
new_slug = Photo.objects.get(slug=form.title).slug
至于生成随机整数:
from random import randint
randint(0,100)
将返回0到100之间的随机整数(包括)。