我正在使用我在互联网上找到的ColorField,当我从管理站点设置颜色时,它正常工作,但是当我创建自己的表单时,我收到此错误:
'ColorField' object has no attribute 'model'
在模板渲染过程中说"错误",并显示错误在此行中:
<div class="form-group form-group-lg">
<label class="control-label" for="formGroupInputLarge">Color: </label>
{{ form.color }}
</div>
这是我的models.py:
class Event(models.Model):
name = models.CharField(blank = False, max_length = 100)
beggining_time= models.DateTimeField(blank = True)
ending_time = models.DateTimeField(blank = True)
color = ColorField(default='#FF0000')
manager = models.ForeignKey(Manager, on_delete=models.CASCADE)
slug = models.SlugField(unique = True)
这是我的views.py文件:
def calendar(request, pYear, pMonth, id):
"""
Show calendar of events for specified month and year
"""
lYear = int(pYear)
lMonth = int(pMonth)
lContestEvents = Smena.objects.filter(manager= Manager.objects.filter(user= User.objects.filter(id = id)))
lCalendar = WorkoutCalendar(lContestEvents).formatmonth(lYear, lMonth)
lPreviousYear = lYear
lPreviousMonth = lMonth - 1
if lPreviousMonth == 0:
lPreviousMonth = 12
lPreviousYear = lYear - 1
lNextYear = lYear
lNextMonth = lMonth + 1
if lNextMonth == 13:
lNextMonth = 1
lNextYear = lYear + 1
lYearAfterThis = lYear + 1
lYearBeforeThis = lYear - 1
form = AddEvent(request.POST or None)
if form.is_valid():
instance = form.save(commit = False)
instance.manager= Manager.objects.filter(user= User.objects.filter(id = id))
instance.save()
return render(request, 'template.html', {'Calendar' : mark_safe(lCalendar),
'Month' : lMonth,
'MonthName' : named_month(lMonth),
'Year' : lYear,
'PreviousMonth' : lPreviousMonth,
'PreviousMonthName' : named_month(lPreviousMonth),
'PreviousYear' : lPreviousYear,
'NextMonth' : lNextMonth,
'NextMonthName' : named_month(lNextMonth),
'NextYear' : lNextYear,
'YearBeforeThis' : lYearBeforeThis,
'YearAfterThis' : lYearAfterThis,
'form' : form,
})
这是我的forms.py文件:
class AddEvent(forms.Form):
name= forms.CharField()
beggining_time= forms.DateTimeField()
ending_time= forms.DateTimeField()
color = ColorField()
class Meta:
fields = ['name', 'beggining_time', 'ending_time', 'color']
正如我所说,我可以从管理页面添加事件,但我无法在我的网站上显示该表单。我得到了上面提到的错误。谢谢你的帮助。
答案 0 :(得分:1)
您在表单中使用模型 ColorField
,但这些是两个完全不同的上下文。看起来您还试图将常规表单用作ModelForm
。
将表单更改为以下内容:
class EventForm(forms.ModelForm):
class Meta:
model = Event
fields = ['name', 'beggining_time', 'ending_time', 'color']
这会在渲染时自动使用ColorWidget
表单字段小部件。