Delete part of a URL with Django

0

Performing an application in Django (without using the forms that the framework brings), when accessing to edit a record the url that the browser shows me remains as follows:

Up here all good, but once I edit the record I have the same url. How can I make the url run out of the Id I edited?

URL.py

url(r'^empresa$', empresa, name='empresa'),
url(r'^empresaEditar/(?P<id_empresa>\d+)/$', empresaEditar, name='empresaEditar'),

Views.py

def empresa(request):
    return render(request, 'estructuracion/empresa.html')

def empresaEditar(request, id_empresa):
    if request.method == 'POST':
        .
        .
        .
        msg='Registro modificado exitosamente'
        return HttpResponseRedirect('estructuracion/empresa',{'departamentos':departamentos, 'ciudades':ciudades,'msg':msg,})
    else:
        msg = validator.getMessage()
        return HttpResponseRedirect('estructuracion/empresa',{'departamentos':departamentos, 'business':business, 'ciudades':ciudades,'msg':msg,})

return render(request,'estructuracion/empresa.html',{'departamentos':departamentos, 'business':business, 'ciudades':ciudades,})

Another question is:

As you can see I am returning with HttpResponseRedirect but through this the messages that I sent you do not take me to html.

    
asked by jhon1946 26.12.2016 в 17:37
source

2 answers

0

To be able to send messages by HttpResponseRedirect use django messages, these messages are handled with the following tags: debug, info, success, warning and error. All documentation is here link .

my implementation was like this:

views.py

def usuario(request):
    if request.method == 'POST':
        #aca va el codigo de mi views
        messages.success(request, 'Usuario creado exitosamente') #aca creo el mensaje con la etiqueta messages.success, podemos ver q mi mensaje va dentro de los parentesis despues de request dentro de comillas
        return HttpResponseRedirect('/estructuracion/usuario')
    else:
        messages.warning(request, 'Se produjo un error') #Si no se cumple la condicion genero otro mensaje de alerta o error con la etiqueta messages.warning
        return HttpResponseRedirect('/estructuracion/usuario')
return render(request,'estructuracion/usuario.html')

As we can see automatically the messages are loaded and I only have to show them in the template:

{% for message in messages %}
    {% if 'success' in message.tags %}
        <div class="alert alert-success">
            <a class="close" href="#" data-dismiss="alert">×</a>
            {{ message }}
        </div>
     {% endif %}
 {% endfor %}
 {% for message in messages %}
     {% if 'error' in message.tags %}
         <div class="alert alert-error">
             <a class="close" href="#" data-dismiss="alert">×</a>
             {{ message }}
         </div>
     {% endif %}
 {% endfor %}
 {% for message in messages %}
     {% if 'warning' in message.tags %}
         <div class="alert alert-danger">
             <a class="close" href="#" data-dismiss="alert">×</a>
             {{ message }}
         </div>
     {% endif %}
 {% endfor %}

Des this form according to the label (warning, error or success) the template is presented. (I am using Bootstrap).

    
answered by 12.01.2017 / 17:17
source
0

Well, your question does not really understand much, but it can help you solve it, it's using the Django conventions for a better development.

It consists that when you go to do a redirection, you do it with a function that comes for it, it would be like this:

from django.shortcuts import redirect

if request.method == 'POST':
    ...
    return redirect('empresaEditar')

It is a cleaner way, with the name of the url, in case of having a namespace the url could be return redirect('namespace:empresaEditar')

It turns out that to pass the data, as well as what you are doing is not so easy, so I will propose 2 different options, which are:

1.Send the data per session:

...
# Lo envias en una vista
request.session['departamentos'] = departamentos
request.session['ciudades'] = ciudades
return redirect('empresaEditar')
...

# luego lo recuperas en tu otra vista de esta forma
def otra_vista(request):
    departamento = request.session.get('departamento', None)
    ciudades = request.session.get('ciudades', None)
    # haces lo que quieras con los datos

NOTE: What you send in the session is preferable that they are not own objects, that is, try to send python own objects as they are: str, int, dict, float, list, tuple, set, etc , otherwise if you have objects like querysets, the ideal would be to serialize them first to JSON, YAML or XML, it's your decision.

2. Send the data in the url (if you send querysets it is not useful)

For this you must modify your urls and now accept parameters with the regular expressions, then you rescue them in a normal way you would for a common edition:

...
# urls.py
url(r'^empresaEditar/(?P<id_empresa>\d+)/(?P<id_departamento>\d+)$', empresaEditar, name='empresaEditar'),

# luego, redireccionas usando reverse
from django.core.urlresolvers import reverse
return redirect(reverse('empresaEditar', args=(empresa.id, departamento.id)))
# o
# return redirect(reverse('empresaEditar', kwargs={'id_empresa': empresa.id, 'id_departamento': departamento.id}))

# en tu otra vista (donde haces la redirección)
def otra_vista(request, id_empresa, id_departamento):
    from django.shortcuts import get_object_or_404
    empresa = get_object_or_404(Empresa, id=id_empresa)
    departamento = get_object_or_404(Departamento, id=id_departamento)

I hope I helped you     ...

    
answered by 30.12.2016 в 19:55