在数据库“ NoneType”对象中保存照片时出错,没有属性“用户”

时间:2019-03-10 01:01:13

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

我有一个使用Usuario的模型,照片foto进入了该模型,并且可以完美地保存在数据库中,因此,能够像添加图库一样添加更多图像,我创建了另一个名为Gallery的模型,我复制了相同的规范Usuario模型中已经存在的功能,但是他没有将照片保存在数据库中,而且我不知道我要去哪里。 感谢您的帮助。 并且我需要Gallery模型来接收外来的Usuario密钥

错误: / gallery-novo /的IntegrityError 列“ usuario_id_id”中的空值违反了非空约束 详细信息:失败行包含(3,IMG_20180622_101716179_BURST006.jpg,eu e meu amor,null)。

views.py

    def gallery(request):
        gallery = Gallery.objects.all()
        form = GalleryForm()
        data = {'gallery': gallery, 'form': form}
        return render(request, 'gallery.html', data)   

    def gallery_novo(request):
        if request.method == 'POST':
            form = GalleryForm(request.POST, request.FILES)
            if form.is_valid():
                form.save(user=request.user)
                return redirect('sistema_perfil')
        else:
            form = GalleryForm
        return render(request, 'gallery.html', {'form': form})

models.py

    class Gallery(models.Model):
        gallery = StdImageField( blank=False,  variations={
            'large': (600, 400),
            'thumbnail': (100, 100, True),
            'medium': (300, 200),
        })
        titulo = models.CharField(max_length=50, blank=False)
        usuario_id = models.ForeignKey(User, on_delete=models.CASCADE, blank=False)

forms.py

             class GalleryForm(forms.ModelForm):
          gallery = forms.FileField(
                        widget=forms.ClearableFileInput(attrs={'multiple': 'True'}))
          titulo = forms.CharField()

          class Meta:
                 model = Gallery
                 fields = ( 'gallery', 'titulo')

          def __init__(self, *args, **kwargs):
                 self.request = kwargs.pop('request', None)
                 return super(GalleryForm, self).__init__(*args, **kwargs)


 def save(self, commit=True, user=None):
     form = super(GalleryForm, self).save(commit=False)
     form.usario_id = user
     if commit:
        form.save()
     return form

gallery.html

    {%extends 'bases/base.html' %}
    {% load static %}
    {% load bootstrap %}
    {% load widget_tweaks %}
    {% load crispy_forms_tags %}

    {% block main %}

    <div class="card text-white bg-primary">
        <div class="card-header"><p class="card-text">
            <small class="text-muted">
                <a href="{% url 'sistema_index' %}" class="text-white ">Home /</a>  
                <a  class="text-white">Cadastro</a>

            </small></a></p> Cadastro de Usúario 
        </div>
        <div class="card title  ">
        <div class="card-body text-secondary">  
            <form class="exampleone" action="{%  url 'sistema_gallery_novo'  %}" method="POST" enctype="multipart/form-data" id="form" name="form" validate >
                    {% csrf_token %}

        <div class="form-row"> 
                <div class="form-group col-md-4">


            {{ form.gallery | as_crispy_field }}

        </div>
                <div class="form-group col-md-4">


            {{ form.titulo | as_crispy_field }}

        </div>

        <div class="form-group col-md-4">


        </div>

            </div>


            </div>

                        <button type="submit"  class="btn btn-primary btn-block">Cadastrar</button>

                </form>


        </div>
        </div>
        </div>



    {% endblock %}

    {% block rightcol %}
    {% include 'bases/rightcol.html' %}
    {% endblock %}

    {% block footer %}
    {% include 'bases/footer.html' %}
    {% endblock %}

urls.py

   url(r'gallery/$', gallery, name='sistema_gallery'),
   url(r'gallery-novo/$', gallery_novo, name='sistema_gallery_novo'),

1 个答案:

答案 0 :(得分:2)

我认为,您是在重新发明轮子,Django正确的方法是使用commit=False on save method

def gallery_novo(request):
    if request.method == 'POST':
        form = GalleryForm(request.POST, request.FILES)
        if form.is_valid():
            my_novo_gallery = form.save(commit=False)  #save no commit
            my_novo_gallery.user=request.user          #set user
            my_novo_gallery.save()                     #save to db
            return redirect('sistema_perfil')