我在数据库名称“ user”中未看到保存的图像未定义

时间:2019-03-10 17:49:59

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

我正在上传图像,它们显示在“静态/媒体”文件夹中 但我无法在perfil.html中显示这些图像 并使用错误的外壳:

错误:  名称“用户”未定义

但我已登录,因为用户在工作时需要登录的其他选项如下:

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():
                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')
        else:
            form = GalleryForm
        return render(request, 'gallery.html', {'form': form})

    def perfil(request):
        usuario = Usuario.objects.all()
        form = UsuarioForm()
        data = {'usuario': usuario, 'form': form}
        gallery = Gallery.objects.all()
        form2 = GalleryForm()
        data2 = {'gallery': gallery, 'form2': form2}
        return render(request, 'perfil.html', data, data2)

models.py

           class Usuario(models.Model):

        nome = models.CharField(max_length=50, blank=False)
        sobrenome = models.CharField(max_length=50, blank=False)
        user = models.OneToOneField(User, on_delete=models.CASCADE)
        email_confirmed = models.BooleanField(default=False)
        email = models.EmailField(blank=False)
        foto = StdImageField( blank=False,  variations={
            'large': (600, 400),
            'thumbnail': (100, 100, True),
            'medium': (300, 200),
        })
        telefone = models.CharField(max_length=20, blank=False, verbose_name="Celular")
        cpf = models.CharField(max_length=19)
        data_nascimento = models.CharField(max_length=8, blank=False, verbose_name="Data de nascimento")
        sexo = models.CharField(default='M', max_length=2, choices=SEXO_CHOICES)
        pet = MultiSelectField( max_length=100, choices=PET_CHOICES, verbose_name="Selecione seus pets")
        endereco = models.CharField(max_length=50)
        numero = models.CharField(max_length=10)
        bairro = models.CharField(max_length=30)
        cep = models.CharField(max_length=25)
        cidade = models.CharField(max_length=30)
        estado = models.CharField(default='RS', max_length=3, choices=STATE_CHOICES)
        password1 = models.CharField(max_length=15, blank=False)
        about = models.TextField(max_length=1000, blank=False, verbose_name="Sobre você")


        def __unicode__(self):
            return self.nome

        @receiver(post_save, sender=User)
        def cadastro_novo(sender, instance, created, **kwargs):
            if created:
                Usuario.objects.create(user=instance)
            instance.usuario.save()

        def __str__(self):
            return str(self.nome) + ' - ' + str(self.email) + ' - ' + str(self.telefone) 


    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=True, null=True)

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 %}


            <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 %}

urls.py

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

perfil.html

  {% for g in user.usuario.gallery_set.all %}
  <img src="{{ g.medium.url}}">
  {% endfor %}

0 个答案:

没有答案