Django默认值未分配! django 1.11 python 3.6

时间:2017-11-23 09:07:03

标签: django django-models django-forms django-class-based-views

我很难找到解决这个问题的方法。我有一个名为' Album'如果未手动指定,则需要为某些字段分配默认值。在完成所有研究之后,感觉就像我的所有代码都是正确的,但是没有分配默认值。此外,这是我第一次在stackoverflow上发布一个问题,所以请忍受我的新手。以下是所有代码:

models.py文件:

class Album(models.Model):
    artist = models.CharField(max_length = 250, blank = True, null = True, default = "some_default_artist_name")
    album_title = models.CharField(max_length = 500, default='some_default_album_name', blank = True, null = True)
    genre = models.CharField(max_length = 100)
    album_logo = models.FileField()
    date_field = models.DateField()
    dt_field = models.DateField(blank = True, null = True, default=date.today().strftime('%d/%m/%Y'))

forms.py文件:

class AlbumForm(forms.ModelForm):
    artist = forms.CharField(required = False)
    album_title = forms.CharField(required = False)
    genre = forms.CharField()
    album_logo = forms.FileField()
    date_field = forms.DateField(widget = forms.DateInput(attrs={'placeholder': 'dd/mm/yyyy'}, format='%d/%m/%Y'))
    dt_field = forms.DateField(required = False, widget = forms.DateInput(attrs={'placeholder': 'dd/mm/yyyy'}, format='%d/%m/%Y'))

    class Meta:
        model = Album
        fields = '__all__'

预计默认值会分配给'艺术家',#39; album_title'和' dt_field'当这些字段在表单中保留为空白时。除非实际初始化,否则没有任何字段被分配默认值并保持为空。

views.py:

class AlbumCreate(LoginRequiredMixin, SuccessMessageMixin, CreateView):
    login_url = 'music:login'
    form_class = AlbumForm
    redirect_field_name = None
    #fields = '__all__'
    model = Album
    success_message = "Album was created successfully"

另外,如果这种方法不正确,那么正确的方法是什么?

2 个答案:

答案 0 :(得分:1)

那是因为你的模型允许blank=True,因此Django没有理由分配默认值。如果您希望模型在未指定时始终包含默认值,请不要将字段设置为blank=True。另外,请勿在{{1​​}}上使用null=True,因为这样可以在数据库中显示两个表示形式。所以你有两个选择:

  1. 更改模型:

    CharField
  2. 在表单验证期间指定默认值:

    artist = models.CharField(max_length=250, default="some_default_artist_name")
    
  3. 另见this SO question

答案 1 :(得分:0)

编辑:(已解决)

因此,出于一些奇怪的未知原因,默认参数不起作用,但dirkgroten的回复确实激励我采用不同于我之前所遵循的方法。

因此,以下是那些陷入类似情况的新工作代码:

models.py :(删除了所有不必要的参数)

class Album(models.Model):
    artist = models.CharField(max_length = 250)
    album_title = models.CharField(max_length = 500)
    genre = models.CharField(max_length = 100)
    album_logo = models.FileField()
    date_field = models.DateField()
    dt_field = models.DateField()

forms.py :(无变化)

class AlbumForm(forms.ModelForm):
    artist = forms.CharField(required = False)
    album_title = forms.CharField(required = False)
    genre = forms.CharField()
    album_logo = forms.FileField()
    date_field = forms.DateField(widget = forms.DateInput(attrs={'placeholder': 'dd/mm/yyyy'}, format='%d/%m/%Y'))
    dt_field = forms.DateField(required = False, widget = forms.DateInput(attrs={'placeholder': 'dd/mm/yyyy'}, format='%d/%m/%Y'))

    class Meta:
        model = Album
        fields = '__all__'

最后是views.py :(从CreateView覆盖def_valid方法)

class AlbumCreate(LoginRequiredMixin, SuccessMessageMixin, CreateView):
    login_url = 'music:login'
    model = Album
    form_class = AlbumForm
    redirect_field_name = None      
    success_message = "Album was created successfully"

    def date_in_range(self, x):    #basic function to check if a date is within a date range. Returns True if date is within the date range else false.
        start = date(2000, 12, 31)
        end = date(2017, 12, 31)
        if start <= end:
            return start <= x <= end
        else:
            return start <= x or x <= end


    def form_valid(self, form):
        obj = form.save(commit = False)
        if not obj.artist:    #if artist field left blank, assign this value
            obj.artist = 'Default_artist_name'
        if not obj.dt_field:    #if dt_field left blank, assign this value
            obj.dt_field = date.today()
        if not self.date_in_range(obj.dt_field):    #if entered date is not in range, then display a field error for dt_field.
            form.add_error('dt_field', 'Date out of range')
            return super(AlbumCreate, self).form_invalid(form)
        self.object = form.save()
        return super(AlbumCreate, self).form_valid(form)

此外,欢迎任何建议或反馈。 Thanx:)