Django创建了字段

时间:2014-07-25 10:32:17

标签: python django

我有一个模型'已创建'领域。我只想在创建新对象时存储日期,但是当我更改模型中的其他字段时不要更新此字段。在同步之前,我有auto_now,但我在第一个回答Automatic creation date for django model form objects?中更改了它。我的问题是当我更新我的实体时

IntegrityError at /rhyme/15/
null value in column "created" violates not-null constraint
DETAIL:  Failing row contains (15, LORE, <p>LORE</p>
<p>LORE</p>
<p>LORE</p>
<p>LORE</p>
<p>LORE</p>
<p>L..., null, 1, 1).

我的模特:

class Rhyme(models.Model):
    title = models.CharField(max_length=255)
    content = models.TextField()
    created = models.DateTimeField(auto_now_add=True)
    author = models.ForeignKey(UserProfile, related_name='created_rhymes')
    profiles = models.ManyToManyField(UserProfile, related_name='stored_rhymes')
    category = models.ForeignKey(Category, null=True, blank=True, related_name='rhymes')

更新 视图:

form = RhymeForm(data)
form_is_valid = form.is_valid()
if form_is_valid:
    rhyme = form.save(commit=False)
    if self.kwargs.has_key('id'):
        rhyme.id = self.kwargs['id']
    rhyme.author = self.request.user.profile
    rhyme.save()

形式:

class RhymeForm(forms.ModelForm):
    title = forms.CharField(
        widget=forms.TextInput(attrs={'class':'form-control'}),
        label=u'Tytuł'
    )
    content = forms.CharField(
        widget=forms.Textarea(attrs={'class':'form-control'}),
        label=u'Treść'
    )
    category = forms.ModelChoiceField(
        queryset=Category.objects.all(),
        label=u'Kategoria',
        empty_label="     ",
        required=False
    )
    class Meta:
        model = Rhyme
        fields = ('title', 'content', 'category')
    def save(self, commit=True):
        rhyme = super(RhymeForm, self).save(commit=False)
        if commit is True:
            rhyme.save()
        return rhyme

模板(有点奇怪,但json只发送类别,内容和标题):

<form action="{$ formAction $}" role="form" method="post" ng-submit="add($event)">
            {% for field in form.visible_fields %}
                <div class="form-group {% if field.errors %}has-error{% endif %}">
                    {{ field.label_tag }}
                    {{ field|ngmodel }}
                    {% with 'errors.'|add:field.name as error_field %}
                        <div class="text-warning bg bg-danger">
                            {{ field.errors }}{$ {{ error_field }} $}
                        </div>
                    {% endwith %}
                </div>
            {% endfor %}
            {% csrf_token %}
            <div class="row">
                <button ng-click="close($event)" class="btn btn-default col-md-3">Anuluj</button>
                <input class="btn btn-success col-md-offset-1 col-md-8" type="submit" value="Zapisz" />
            </div>
        </form>

我丑陋的解决方案是放

rhyme.created = models.Rhyme.objects.get(pk=self.kwargs['id']).created

但是为什么我的ORM试图将null设置为字段,如何解决这个问题?

0 个答案:

没有答案