Exemple #1
0
    def post(self, request):
        """
         crea una foto en base a la información POST
         :param request: HttpRequest
         :return: HttpResponse
        """

        success_message = ''

        photo_with_owner = Photo()
        photo_with_owner.owner = request.user  #asigno como propietario de la foto al usuario atuenticado
        form = PhotoForm(
            request.POST, instance=photo_with_owner
        )  #especificar instancia de foto a utilizar por el formulario
        if form.is_valid():
            new_photo = form.save()  #guarda el objeto Photo y me lo devuelves
            form = PhotoForm()
            success_message = '¡Guardado con éxito!'
            success_message += '<a href="{0}">'.format(
                reverse('photo_detail', args=[new_photo.pk]))
            success_message += 'Ver foto'
            success_message += '</a>'
        context = {'form': form, 'success_message': success_message}

        return render(request, 'photos/new_photo.html', context)
Exemple #2
0
def helper(category, request):
    form = None
    result = False
    if category == 'Photos':
        form = PhotoForm(data=request.POST, files=request.FILES)
    elif category == 'Story':
        form = StoryForm(data=request.POST, files=request.FILES)
    current_category = Categories.objects.filter(category=category)
    if form.is_valid():
        if category == 'Photos':
            new_photo = form.save(commit=False)
            new_photo.owner = request.user
            new_photo.categoryid = current_category[0]
            new_photo.save()
            result = True
            return result, new_photo
        elif category == 'Story':
            pending_form = form.save(commit=False)
            pending_form.author = request.user
            pending_form.categoryid = current_category[0]
            pending_form.save()
            result = True
            return result, pending_form
        else:
            raise ValueError('category should be among predefined values')
    else:
        return result,
Exemple #3
0
def create(request):
    '''
    Formulario para creacion de de foto (petición POST)
    param request: HttpRequest
    return: HttpResponse
    '''

    success_message = ''
    if request.method == 'GET':
        form = PhotoForm()
    else:
        photo_with_owner = Photo()
        photo_with_owner.owner = request.user # Asignar como propietario de la foto al user autenticado
        form = PhotoForm(request.POST, instance=photo_with_owner)
        if form.is_valid():
            new_photo = form.save() # Guarda el objeto y lo devuelve
            form = PhotoForm() # Al no pasar valores aparece el formulario vacio
            success_message = 'Guardado con éxito'
            success_message += '<a href="{0}">'.format(reverse('photo_detail',args=[new_photo.pk]))
            success_message += 'ver foto'
            success_message += '</a>'

    context = {
        'form': form ,
        'success_message': success_message
    }
    return render(request, 'photos/new_photo.html', context)
def upload(request):
    if not request.user.is_authenticated():
        # Replace youself redirect.
        return HttpResponseRedirect("/register/")
    else:
        if request.method == "POST":
            photo_form = PhotoForm(request.user, request.POST, request.FILES)
            if photo_form.is_valid():
                photo = PhotoItem()
                photo.image = photo_form.cleaned_data["image"]
                photo.descr = photo_form.cleaned_data["descr"]
                photo.save()

                if photo_form.cleaned_data["new_album"]:
                    album = PhotoAlbum()
                    album.name = photo_form.cleaned_data["new_album"]
                    album.cover = photo
                    album.author = request.user
                    album.save()
                else:
                    album = PhotoAlbum.objects.get(pk=request.POST["album"])

                photo.album = album
                photo.save()
                return HttpResponseRedirect("/photos/%s/%d/" % (request.user.username, album.id))
        else:
            photo_form = PhotoForm(request.user)

        return render_to_response(
            "photo_upload.html", {"photo_form": photo_form}, context_instance=RequestContext(request, processors=[])
        )
def create(request):
    """
    Show a form for create a new photo post.
    :param request: HttpRequest Object
    :return: HttpResponse Object
    """

    success_message = ''

    if request.method == 'GET': #GET REQUEST
        form = PhotoForm()
    else: #POST REQUEST
        photo_with_owner = Photo()
        photo_with_owner.owner = request.user #Automatic asign user autenticated as owner

        form = PhotoForm(request.POST,instance=photo_with_owner)
        if form.is_valid():
            new_photo = form.save() #Save the object photo and return it
            form =  PhotoForm() #Empty form after submitting
            success_message = 'Photo created succesfully'
            success_message += '<a href="{0}">'.format(reverse('photo_detail',args=[new_photo.pk]))
            success_message += 'Take a look'
            success_message += '</a>'
    context = dict(form=form,success_message=success_message)

    return render(request,'photos/new_photo.html',context)
Exemple #6
0
    def post(self, request):
        """
        Muestra un formulario
        :param request:
        :return:
        """
        sucess_message = []

        # Es esto seguro? -> Que pasa si meto owner con POST
        photo_with_owner = Photo()
        photo_with_owner.owner = request.user
        form = PhotoForm(request.POST, instance=photo_with_owner)

        if form.is_valid():
            photo = form.save()  # Guarda el objeto y me lo devuelve
            sucess_message = 'Guardado con éxito '
            sucess_message += '<a href=\"{0}\">'.format(reverse('photos_detail', args=[photo.pk]))
            sucess_message += 'Ver foto'
            sucess_message += '</a>'
        form = PhotoForm()

        context = {
            'form': form,
            'sucess_message': sucess_message
        }
        return render(request, 'photos/new_photo.html', context)
 def post(self, request):
     success_message = ''
     number_of_photos_uploaded = self.get_number_of_photos_from_user(
         request)
     if not check_if_uploads_remaining(number_of_photos_uploaded):
         form = PhotoForm()
         success_message = 'Ya has subido 25 fotos. Has alcansado el limite.'
     else:
         photo_with_owner = Photo()
         photo_with_owner.owner = request.user
         form = PhotoForm(request.POST, instance=photo_with_owner)
         if form.is_valid():
             new_photo = form.save()
             form = PhotoForm()
             success_message = 'Guardado con éxito'
             success_message += '<br>'
             success_message += '<br>'
             success_message += '<a href="{0}">'.format(
                 reverse('photos_detail', args=[new_photo.pk]))
             success_message += 'Ver foto'
             success_message += '</a>'
     context = {
         'form': form,
         'success_message': success_message,
         'nof': number_of_photos_uploaded,
         'nof2': 25 - number_of_photos_uploaded
     }
     return render(request, 'photos/new_photo.html', context)
    def post(self, request):
        """
        Crea una foto en base a la información POST
        :param request: HttpRequest
        :return: HttpResponse
        """
        success_message = ''
        photo_with_owner = Photo()
        photo_with_owner.owner = request.user   # asigno como propietario de la foto el usuario autenticado
        form = PhotoForm(request.POST, instance=photo_with_owner)
        if form.is_valid():
            # Guarda el objeto del formulario en la DB y lo devuelve
            new_photo = form.save()

            # Inicializamos formulario, con el reverse componemos la url dinámica que mostrará con la nueva
            # foto
            form = PhotoForm()
            success_message = 'Guardado con éxito!'
            success_message += '<a href="{0}">'.format(reverse('photo_detail', args=[new_photo.pk]))
            success_message += 'Ver foto'
            success_message += '</a>'
        context = {
            # Pasamos en el context los datos que se mostrarán en el template
            'form': form,
            'success_message': success_message
        }
        return render(request, 'photos/new_photo.html', context)
Exemple #9
0
 def post(self, request):
     """
     Crea una foto en base a la documentacioón POST
     :param request: HttpRequest
     :param pk: id de la foto
     :return: HttpResponse
     """
     success_message = ''
     photo_with_owner = Photo()
     photo_with_owner.owner = request.user                      # asigno como usuario de la foto, el usuario auteticado
     form = PhotoForm(request.POST, instance=photo_with_owner)  # Instanciamos el formulario con los datos del POST
     if form.is_valid():                                        # Preguntar si es válido
         new_photo = form.save()                                # Guarda el objeto Photo y me lo devuelve
         form = PhotoForm()
         success_message = 'Guardado con éxito!'
         success_message += '<a href="{0}">'.format(
             reverse('photo_detail', args=[new_photo.pk])
         )
         success_message += 'Ver foto'
         success_message += '</a>'
     context = {
         'form': form,
         'success_message': success_message
     }
     return render(request, 'photos/new_photo.html', context)
Exemple #10
0
    def post(self, req):
        """
        Muestra un form para crear una foto y la crea si la peticion es POST
        :param req: HttpRequest
        :return: HttpResponse
        """
        error_messages = []
        success_message = ""

        # Creamos owner y se lo pasamos al form con un objeto pre-establecido
        photo_with_owner = Photo()
        photo_with_owner.owner = req.user

        form = PhotoForm(req.POST, instance=photo_with_owner)
        if form.is_valid():
            new_photo = form.save()
            form = PhotoForm()
            success_message = "Foto guardada con éxito! "
            success_message += '<a href="{0}">'.format(reverse("photos_detail", args=[new_photo.pk]))
            success_message += "(ver foto)</a>"
        else:
            error_messages.append("Formulario incompleto.")

        context = {"form": form, "success_message": success_message}
        return render(req, "photos/new_photo.html", context)
Exemple #11
0
    def post(self, request):

        #Crea una instancia vacía de foto
        photo_with_owner = Photo()

        #Asigna los datos
        photo_with_owner.owner = request.user

        form = PhotoForm(request.POST, instance=photo_with_owner)
        if form.is_valid():
            new_photo = form.save(
            )  #Guarda el objeto que viene en el formulario y lo devuelve

            #Poner todos los campos vacíos
            form = PhotoForm()

            success_message = 'Guardado con exito!'

            #reverse sirve para generar la url
            success_message += '<a href="{0}">'.format(
                reverse('photo_detail', args=[new_photo.pk]))
            success_message += 'Ver Foto'
            success_message += '</a>'
        context = {'form': form, 'success_message': success_message}
        return self.render(request, context)
    def post(self, request):

        #Crea una instancia vacía de foto
        photo_with_owner = Photo()

        #Asigna los datos
        photo_with_owner.owner = request.user

        form = PhotoForm(request.POST, instance=photo_with_owner)
        if form.is_valid():
            new_photo = form.save() #Guarda el objeto que viene en el formulario y lo devuelve

            #Poner todos los campos vacíos
            form = PhotoForm()

            success_message = 'Guardado con exito!'

            #reverse sirve para generar la url
            success_message += '<a href="{0}">'.format(reverse('photo_detail', args=[new_photo.pk]))
            success_message += 'Ver Foto'
            success_message += '</a>'
        context = {
            'form': form,
            'success_message': success_message
        }
        return self.render(request, context)
Exemple #13
0
def upload_project_photos(request, o_id):
    if request.user.is_anonymous():
        p_lic_num = None
    else:
        try:
            p_lic_num = str(request.user.professional_profiles.first().
                            professional.lic_num)
        except:
            p_lic_num = None
    if str(p_lic_num) == str(o_id):
        template_name = 'meister/meister_project_photos_upload.html'  # Replace with your template.
        success_url = '/meister/' + o_id  # Replace with your URL or reverse().

        if request.method == "POST":
            form = PhotoForm(request.POST, request.FILES)
            content_type = ContentType.objects.get(model='meister')
            object_id = int(o_id)
            files = request.FILES.getlist('img')
            if form.is_valid():
                if len(files) > 0:
                    for f in files:
                        instance = Photo.objects.create(
                            img=f,
                            title=f.name,
                            content_type=content_type,
                            object_id=object_id)
                        instance.save()
                else:
                    pass
                return redirect(success_url)
        form = PhotoForm()
        info_dict = {'form': form}
        return render(request, template_name, info_dict)
    else:
        raise Http404(_('No Pages Found.'))
Exemple #14
0
def commit(request):
    if request.method == "POST":
        photo_form = PhotoForm(request.POST, request.FILES)
        if photo_form.is_valid():
            process_photo(request, request.FILES.get("photo"))
        return HttpResponseRedirect("/index/")
    else:
        photo_form = PhotoForm()
    return render_to_response('ct_photo.html', {"form": photo_form})
Exemple #15
0
def photo_add_view(request):
    form = PhotoForm()
    data = {}
    if request.is_ajax() and request.POST:
        form = PhotoForm(request.POST, request.FILES)
        if form.is_valid():
            form.save()
            return JsonResponse(data)

    context = {'form': form}
    return render(request, 'photos/main.html', context)
Exemple #16
0
def new_photo(request):
    if request.method == 'POST':
        form = PhotoForm(request.POST)
        if form.is_valid():
            new_photo = form.save()
            messages.success(request, 'Foto creada correctamente con ID {0}'.format(new_photo.pk))
            form = PhotoForm()
    else:
        form = PhotoForm()
    context = {'form': form}
    return render(request, 'photos/new.html', context)
Exemple #17
0
 def post(self, request):
     photo = Photo()
     photo.owner = request.user
     form = PhotoForm(request.POST, instance=photo)
     if form.is_valid():
         new_photo = form.save()
         messages.success(
             request,
             'Foto creada correctamente con ID {0}'.format(new_photo.pk))
         form = PhotoForm()
     context = {'form': form}
     return render(request, 'photos/new.html', context)
Exemple #18
0
def edit_photo(request, photo_id):
    photo = Photo.objects.get(id=photo_id)
    photo_form = PhotoForm(request.POST)
    valid=False
    if photo_form.is_valid():
        photo.title = photo_form.cleaned_data['title']
        photo.pet = photo_form.cleaned_data['pet']
        photo.public = photo_form.cleaned_data['public']
        photo.save()
        valid=True
    data = {'edit_photo_form': photo_form, 'photo_id': photo_id, 'valid': valid, 'photo': photo}
    return render_to_response('photos/edit_photo.html',
                              data,
                              RequestContext(request))
Exemple #19
0
    def post(self, request):
        message = ''
        photo_with_user = Photo(owner=request.user)
        #photo_with_user.owner = request.user

        form = PhotoForm(request.POST, instance=photo_with_user)
        if form.is_valid():
            new_photo = form.save()
            message = 'Guardado con éxito! <a href="{0}">Ver foto</a>'.format(reverse('photo_detail', args=[new_photo.pk]))
            form = PhotoForm()
        context = {
            'form': form,
            'message': message
        }
        return render(request, 'photos/new_photo.html', context)
Exemple #20
0
    def post(self, request):
        success_message = ''
        photo_with_owner = Photo()
        photo_with_owner.owner = request.user
        form = PhotoForm(request.POST, instance=photo_with_owner)
        if form.is_valid():
            new_photo = form.save()
            form = PhotoForm()
            success_message = 'Imagen guardada con éxito! Ver '
            success_message += '<a href="{0}">'.format(
                reverse('photo_detail', args=[new_photo.pk]))
            success_message += 'foto'
            success_message += '</a>'

        context = {'new_photo_form': form, 'success_message': success_message}
        return render(request, 'photos/new_photo.html', context)
Exemple #21
0
    def post(self,request):
        success_message = ''
        photo_with_owner = Photo()
        photo_with_owner.owner = request.user #Automatic asign user autenticated as owner

        form = PhotoForm(request.POST,instance=photo_with_owner)
        if form.is_valid():
            new_photo = form.save() #Save the object photo and return it
            form =  PhotoForm() #Empty form after submitting
            success_message = 'Photo created succesfully'
            success_message += '<a href="{0}">'.format(reverse('photo_detail',args=[new_photo.pk]))
            success_message += 'Take a look'
            success_message += '</a>'
        context = dict(form=form,success_message=success_message)

        return render(request,'photos/new_photo.html',context)
Exemple #22
0
def product_photos(request, slug):
    album = get_object_or_404(Album, slug=slug)

    if request.method == 'POST':
        form = PhotoForm(request.POST or None, request.FILES or None)
        if form.is_valid():
            c = form.save(commit=False)
            c.album = album
            c.save()
            redirect('products:product-photos', slug)
    else:
        form = PhotoForm()

    return render(request, 'products/product_photos.html', {
        'form': form,
        'album': album
    })
Exemple #23
0
    def post(self, request):
        """
        Presenta el formulario para crear una foto y, en caso de que la petición sea POST la valida
        y la crea en caso de que sea válida
        :param request: objeto HttpRequest con los datos de la petición
        :return: objeto HttpResponse con los datos de la respuesta
        """
        message = None
        photo_with_user = Photo(owner=request.user)
        photo_form = PhotoForm(request.POST, instance=photo_with_user)
        if photo_form.is_valid():
            new_photo = photo_form.save()
            photo_form = PhotoForm()
            message = 'Foto creada satisfactoriamente. <a href="{0}">Ver foto</a>'.format(
                reverse('photos_detail', args=[new_photo.pk]))

        context = {'form': photo_form, 'message': message}
        return render(request, 'photos/photo_creation.html', context)
Exemple #24
0
    def get(self, request):
        """
        Muestra un formulario para crear una foto
        :param request: HttoRequest
        :return: HttpResponse
        """
        form = PhotoForm()
        if form.is_valid():
            new_photo = form.save()  # Guarda el objeto foto y me lo devuelve
            form = PhotoForm()
            success_message = 'Guardado con éxito!'
            success_message += ' <a href="{0}">'.format(
                reverse('photo_detail', args=[new_photo.pk]))
            success_message += 'Ver foto'
            success_message += '</a>'
        context = {'form': form, 'success_message': ''}

        return render(request, 'photos/new_photo.html', context)
Exemple #25
0
    def post(self, request):
        """
        Presenta el formulario para crear una foto
        :param request: objeto HttpRequest con los datos de la petición
        :return: HttpResponse con la plantilla
        """
        message = None
        photo_with_user = Photo(owner=request.user)
        photo_form = PhotoForm(request.POST, instance=photo_with_user)
        if photo_form.is_valid():
            new_photo = photo_form.save()
            photo_form = PhotoForm()
            message = "Foto creada satisfactoriamente. <a href='{0}'>Ver foto</a>".format(
                # obtiene la url nombrada 'photos_detail'
                reverse('photos_detail', args={new_photo.pk}))

        context = {'form': photo_form, 'message': message}
        return render(request, 'photos/photo_creation.html', context)
Exemple #26
0
 def post(self, request):
     """
     Crea una foto en base a la información POST
     """
     success_message = ''
     photo_with_owner = Photo()
     photo_with_owner.owner = request.user  # asigno como propietario de la foto el usuario autenticado
     form = PhotoForm(request.POST, instance=photo_with_owner)
     if form.is_valid():
         new_photo = form.save()  # Guarda el objeto y me lo devuelve
         form = PhotoForm()
         success_message = 'Guardado con éxito!'
         success_message += '<a href="' + reverse(
             'photo_detail', args=[new_photo.pk]) + '">'
         success_message += 'Ver foto'
         success_message += '</a>'
     context = {'form': form, 'success_message': success_message}
     return render(request, 'photos/new_photo.html', context)
Exemple #27
0
def create(request):
    success_message = ""
    if request.method == "GET":
        form = PhotoForm()
    else:
        photo_with_owner = Photo()
        photo_with_owner.owner = request.user
        form = PhotoForm(request.POST, instance=photo_with_owner)
        if form.is_valid():
            new_photo = form.save()
            form = PhotoForm()
            url = reverse("photo_detail", args=[new_photo.pk])
            success_message = "Guardado con éxito"
            success_message += f"<a href='{url}'>"
            success_message += "Ver foto"
            success_message += "</a>"

    context = {"form": form, "success_message": success_message}
    return render(request, 'photos/new_photo.html', context)
Exemple #28
0
    def post(self, request):
        # Crea una foto en base a la informació POST

        success_message = ''
        photo_with_owner = Photo()
        photo_with_owner.owner = request.user  # asigna como propietario
        form = PhotoForm(request.POST, instance=photo_with_owner)
        if form.is_valid():
            new_photo = form.save()  # Guarda el objeto y devuelve
            form = PhotoForm()
            success_message = '¡Guardado con éxito!'
            success_message += '<a ref="{0}">'.format(reverse('photos_detail', args=[new_photo.pk]))
            success_message += 'Ver foto'
            success_message += '</a>'
        context = {
            'form': form,
            'succes_message': success_message
        }

        return render(request, 'photos/new_photo.html', context)
Exemple #29
0
    def post(self, request):
        """
		Muestra un formulario para crear una foto y la crea si la peticion es POST
		"""
        success_message = ''
        photo_with_owner = Photo()
        photo_with_owner.owner = request.user  # 	asigno como propietario de la foto , al usuario autenicado
        form = PhotoForm(request.POST, instance=photo_with_owner)
        if form.is_valid():
            new_photo = form.save()  #guarda el objeto y devuelmelo
            form = PhotoForm()
            success_message = 'Guardado exitoso!!'
            success_message += '<a href="{0}">'.format(
                reverse('photos_detail', args=[new_photo.pk]))
            success_message += 'Ver Foto'
            success_message += '</a>'

        context = {'form': form, 'success_message': success_message}

        return render(request, 'photos/new_photo.html', context)
Exemple #30
0
def new(request):
    if request.method == 'POST':
        form = PhotoForm(request.POST, request.FILES)
        if form.is_valid():
            photo = Photo(
                title = form.cleaned_data['title'],
                image = request.FILES['image'],
                user = request.user,
            )
            photo.save()

            return HttpResponseRedirect(reverse('photos:index'))
    else:
        form = PhotoForm()

    return render_to_response(
        'photos/new.html',
        {'form': form},
        context_instance=RequestContext(request)
    )
Exemple #31
0
    def post(self, request):
        """
        Muestra un formulario para crear una foto y la crea si la peticion es POST
        :param request:
        :return:
        """
        success_mesage = ''
        photo_with_owner = Photo()
        photo_with_owner.owner = request.user
        form = PhotoForm(request.POST, instance=photo_with_owner)
        if form.is_valid():
            new_photo = form.save()  #Guarda el objeto foto y se lo devuelve
            form = PhotoForm()
            success_mesage = 'Guardado con exito '
            success_mesage += '<a href="{0}">'.format(
                reverse('photo_detail', args=[new_photo.pk]))
            success_mesage += 'Ver foto'
            success_mesage += '</a>'

        context = {'form': form, 'success_message': success_mesage}
        return render(request, 'photos/new.html', context)
Exemple #32
0
    def post(self, request):
        """
        Muestra un formulario para crear una foto
        :param request: HttpRequest
        :return: HttpResponse
        """
        success_message = ''
        photo_with_owner = Photo()
        photo_with_owner.owner = request.user  # asigno como propietario de la foto al usuario autenticado
        form = PhotoForm(request.POST, instance=photo_with_owner)
        if form.is_valid():
            new_photo = form.save()  # Guarda el objeto foto y me lo devuelve
            form = PhotoForm()
            success_message = 'Guardado con éxito!'
            success_message += ' <a href="{0}">'.format(
                reverse('photo_detail', args=[new_photo.pk]))
            success_message += 'Ver foto'
            success_message += '</a>'
        context = {'form': form, 'success_message': success_message}

        return render(request, 'photos/new_photo.html', context)
Exemple #33
0
    def post(self, request):
        """
        crea una foto en base a la información POST
        :param request: HttpRequest
        :return:HttpResponse
        """
        success_message = ''

        photo_with_owner = Photo()
        photo_with_owner.owner = request.user  #Asigno como usuario de la foto, el usuario autenticado
        form = PhotoForm(request.POST, instance=photo_with_owner)
        if form.is_valid():
            new_photo = form.save()
            form = PhotoForm()
            success_message = 'Guardado con éxito  '
            success_message += '<a href="{}">'.format(
                reverse('photo_detail', args=[new_photo.pk]))
            success_message += 'Ver foto'
            success_message += '</a>'
        context = {'form': form, 'success_message': success_message}
        return render(request, 'photos/new_photo.html', context)
Exemple #34
0
 def post(self, request):
     """
     Crea la foto en base a la informacion del post
     :param request: HttpRequest
     :return: HttpResponse
     """
     success_message = ''
     photo_with_owner = Photo()
     photo_with_owner.owner = request.user # Asigno como propietario de la foto al usuario autenticado actual
     form = PhotoForm(request.POST, instance=photo_with_owner)
     if form.is_valid():
         new_photo = form.save() # Guarda el objeto y me lo devuelves
         form = PhotoForm()
         success_message = 'Foto guardada con exito!'
         success_message += '<a href="{0}">'.format(reverse('photos_detail', args=[new_photo.pk]))
         success_message += 'Ver foto'
         success_message += '</a>'
     context = {
         'form': form,
         'success_message': success_message
     }
     return render(request, 'photos/new_photo.html', context)
Exemple #35
0
    def post(self, request):
        """
		Creates new photo from form model
		:param request:
		:return:
		"""
        success_message = ''
        photo_with_owner = Photo()
        photo_with_owner.owner = request.user
        form = PhotoForm(request.POST, instance=photo_with_owner)

        if form.is_valid():
            photo = form.save(
            )  # genera el objeto del formulario, lo guarda en BD y lo devuelve
            success_message = 'Guardado con éxito! '
            success_message += '<a href="{0}"'.format(
                reverse('photo_detail', args=[photo.pk])) + '>'
            success_message += 'Ver Foto'
            success_message += '</a>'

        context = {'form': form, 'success_message': success_message}
        return render(request, 'photos/new_photo.html', context)
Exemple #36
0
    def post(self, request):
        success_message = ''

        # Asginamos el owner automáticamente
        photo_with_owner = Photo()
        photo_with_owner.owner = request.user

        form = PhotoForm(request.POST, instance=photo_with_owner)

        if form.is_valid():
            new_photo = form.save(
            )  # Guarda el objeto pho en la bbdd y lo deuvelve
            form = PhotoForm()  # Inicializar formulario

            success_message = 'Guardado con éxito'
            success_message += '<a href="{0}">'.format(
                reverse('photo_detail', args=[new_photo.pk]))
            success_message += 'Ver foto'
            success_message += '</a>'

        context = {'form': form, 'success_message': success_message}

        return render(request, 'photos/new_photo.html', context)
def upload_photo(request):
	if request.method == 'POST':
		user = request.user
		album_id = request.GET.get('album_id')
		form = PhotoForm(request.POST, request.FILES)
		if form.is_valid():
			cd = form.cleaned_data
			title = cd['title']
			description = cd['description']
			image = cd['image']
			owner = user
			gallery = get_object_or_404(Gallery, id=album_id)

			photo = Photo(title=title, description=description,
				image=image, owner=owner, gallery=gallery,
				)
			photo.save()
			return HttpResponseRedirect("/photos/")
	else:
		form = PhotoForm()
	return render_to_response("photos/photo_upload.html", {
        "form": form,
        }, context_instance=RequestContext(request)
        )
Exemple #38
0
def create(request):
    #이부분은 이렇게 구현해 줘야하지만
    #login_required 데커레이터를 이용하면 이게 됨 그냥
    #settings.LOGIN_URL 이부분이 중요
    # if not request.user.is_authenticated():
    #     return redirect(settings.LOGIN_URL)

    if request.method == "GET":
        form = PhotoForm()
        # PhotoForm(instance=객체)
        #이런식으로 쳐 넣으면 그냥 들어가서 그거 그대로 뽑아서 보여주기 가능
        #수정할때 필요함
    elif request.method == "POST":
        #무조건 파일하고 분리해줘야함
        form = PhotoForm(request.POST, request.FILES)
        #이방법과
        #form.is_bound =True
        #form.data = request.POST
        #form.files = request.FILES

        if form.is_valid():
            #is_valid 로 한번 걸러진 데이터는 clened_data['key']로 접근해줘야함!!
            obj = form.save(commit=False)
            #로그인을 하지 않으면 여기서 에러가난다
            #user 값이 없으니까
            obj.user = request.user
            #세션에서 불러오는듯
            obj = form.save()
            #리얼 이거 스킬이네 리다이렉트에 모델객체가 넘어갈 경우
            #그 객체의 get_absolute_url()메서드를 호출한다!
            #그니까 이 객체의 원래 클래스에 정의해주는거임!
            #모델.py에있는거지
            #이거 만들어 줘야함
            return redirect(obj)

    return render(request, 'edit.html', context={'form': form})
Exemple #39
0
    def post(request):
        """
        Shows a form for a new photo
        :param request: HttpRequest
        :return: HttpResponse
        """
        success_message=''
        photo_with_owner = Photo()
        photo_with_owner.owner = request.user #user authenticated
        form=PhotoForm(request.POST, instance=photo_with_owner)
        if form.is_valid():
            new_photo = form.save()
            form = PhotoForm() #a new clean form
            success_message = 'Photo saved correctlly'
            success_message += '<a href = "{0}">'.format(reverse('photo_detail', args=[new_photo.pk]))
            success_message += 'Show photo'
            success_message += '</a>'

        form = PhotoForm()
        context = {
            'form' : form,
            'success_message' : success_message
        }
        return render(request, 'photos/new_photo.html', context)