简体   繁体   中英

Django request.method = 'GET' not working

I'm trying to load db table data on my app, in order to do an UPDATE on it, so far, I found out this is done by a request.method = 'GET' don't know if this always the case, but surely it is one of the methods to accomplish this.

However, my app is full of POST requests, to create new documents on the db table, I just need to retrieve one of these by specifying it's name. Using 'GET' method. But it's not working, seems like it doesn't evaluates the expression, I don't really know why.

This is my models.py :

class Proyecto(models.Model):
    id_proyecto = models.IntegerField(primary_key=True) #integer NOT NULL, CLAVE PRIMARIA
    nombre_proyecto = models.TextField(null=True) #text,
    fecha_creacion = models.DateField(null=True) #date,
    existente = models.BooleanField()

    def __unicode__(self):
        return u'%s | %s ' % (self.id_proyecto, self.nombre_proyecto)

    class Meta:
        unique_together = [("id_proyecto","nombre_proyecto")]
        db_table = 'proyecto'

I'll use existente BooleanField, as a checkmark on my template, if this existente is active, then perform a query by it's nombre_proyecto field (project name) and bring the specified document.

My forms.py :

class ProyectoForm(forms.Form):
    nombre_proyecto = forms.CharField(widget=forms.TextInput())
    existente = forms.BooleanField(required=False)

    def clean(self):
        return self.cleaned_data

My views.py where the method lies:

def proyecto_view(request):
    alerta=""
    if request.method == "POST":
        form = ProyectoForm(request.POST)
        if form.is_valid():
            name =form.cleaned_data['nombre_proyecto'] #hay que verificar si el proyecto ya existe
        if existente is not None and existente != '':
            projects = Proyecto.objects.filter(nombre_proyecto=name)
            ctx = {"projects" : projects}
            return render_to_response('scppp/proyecto.html', ctx, context_instance=RequestContext(request))
        if Proyecto.objects.filter(nombre_proyecto=name).exists():
            alerta="ya existe el proyecto"
            formProy = 1
            ctx ={'alerta':alerta, 'formProy':formProy}
            return render_to_response('scppp/inicial.html', ctx, context_instance=RequestContext(request))
        else:
            if not name:    
                id_proyecto=1
            else:
                id_proyecto=Proyecto.objects.all().aggregate(Max('id_proyecto'))['id_proyecto__max']+1
                nombre_proyecto = name
    else:
        alerta = "data erronea"
        formProy = 1
        ctx = {'alerta':alerta, 'formProy':formProy}
        return render_to_response('scppp/inicial.html', ctx, context_instance=RequestContext(request))

    sombra = "style=\"color: #a2a2a2;\""
    num = ""
    slash = ""
    quotes = ""
    arenas = ""
    fluidos = ""
    onclick = ""
    sombra2 = sombra
    graf = ""
    formProy = 0
    ctx = {'id_proyecto':id_proyecto,'nombre_proyecto':nombre_proyecto, 'sombra':sombra, 'sombra2':sombra2, 'graf':graf, 'num':num, 'slash':slash, 'quotes':quotes, 'arenas':arenas, 'fluidos':fluidos, 'onclick':onclick, 'alerta':alerta, 'formProy':formProy}
    return render_to_response('scppp/proyecto.html', ctx, context_instance=RequestContext(request))
else:
    form = ProyectoForm()
    formProy = 1
    ctx = {'form': form, 'formProy': formProy}
    return render_to_response('scppp/inicial.html', ctx, context_instance=RequestContext(request))

Here if existente is not None and existente != '': conditional should evaluates if existente checkmark on inicial.html is active, if it is, render proyecto.html template.

The inicial.html interesting code with checkmark:

<tr><td>
    <span class="Sub-Titulo-Aplicacion">Tipo de Proyecto: </span>
    <input class="check-style" type="checkbox" name="curva" value="checkbox" >Petroleo</input>
    </td></tr>
    <tr><td>
    <input class="check-style" type="checkbox" name="curva" value="checkbox" >Gas</input>
    </td></tr>
    <tr><td>
    <span class="Sub-Titulo-Aplicacion">Proyecto: </span>
    <input class="check-style" type="checkbox" name="tipo" value="checkbox" >Nuevo</input>
    </td></tr>
    <tr><td>
    <input class="check-style" type="checkbox" name="existente" value="existente" >Existente</input>
 </td></tr>

If this checkbox is active, render proyecto.html :

{% for project in projects %}
            <a  class="Contenedor-Texto-Menu"><span class="Text-menu" > Datos</span></a>
             <a href="/pozos{{num}}/{{id_proyecto}}/{{nombre_proyecto}}" class="Contenedor-Texto-sub-Menu"><span class="Text-menu" > Yacimiento y Pozo</span></a>
             <a {% autoescape off %}{{arenas}}{{slash}}{{id_proyecto}}{{slash}}{{nombre_proyecto}}{{quotes}}{% endautoescape %} class="Contenedor-Texto-sub-Menu"><span class="Text-menu" {% autoescape off %}{{sombra}}{% endautoescape %}> Arena </span></a><tr>
             <a {% autoescape off %}{{fluidos}}{{slash}}{{id_proyecto}}{{slash}}{{nombre_proyecto}}{{quotes}}{% endautoescape %} class="Contenedor-Texto-sub-Menu"><span class="Text-menu" {% autoescape off %}{{sombra}}{% endautoescape %}> Fluido </span></a><tr>
             <div style="overflow:hidden; width:0px; height:0px;">
            <form id="submitArch" action="/archivo/{{id_proyecto}}/{{nombre_proyecto}}/" method="POST" enctype="multipart/form-data">
            {% csrf_token %}
            <input id="cargarArch" type="file" class="Contenedor-Texto-sub-Menu" name="archivo" style="display:none;" onchange="submitArch()">
            </form>
            </div>
            <a class="Contenedor-Texto-sub-Menu" {% autoescape off %}{{onclick}}{% endautoescape %}><span class="Text-menu" {% autoescape off %}{{sombra}}{% endautoescape %}> Cargar un archivo </span></a><tr>
             <!--<a href="/graficos/{{id_proyecto}}/{{nombre_proyecto}}" class="Contenedor-Texto-Menu">-->
            <a {% autoescape off %}{{graf}}{% endautoescape %} class="Contenedor-Texto-Menu" {% autoescape off %}{{sombra2}}{% endautoescape %}><span class="Text-menu" > Procesamiento </span></a><tr>
            <a  class="Contenedor-Texto-Menu" {% autoescape off %}{{sombra2}}{% endautoescape %}><span class="Text-menu" > Reporte </span></a><tr>
{% endfor %}

This is all the logic of the existente BooleanField, sorry if this sounds noobish, but this is an already started project and it becomes confusing at times.

If you have any idea about why this isn't evaluating that conditional plz let me know, I just can't figure it out .

Many thanks in advance!

PS = I'm using Django==1.6.1 , Python 3.3.1 and PostgreSQL v9.0.

No need of use of filter.exists . Need only

if Proyecto.objects.filter(nombre_proyecto=name):

If query does not match any documents, it will return [] .So id doen't enter into if condition.Since emptylist emptystring refers False in python.

if all you want to do is determine if at least one result exists. It's more efficient to use exists().

if Proyecto.objects.filter(nombre_proyecto=name).exists():

If you want to update .Simply use get .

proyecto = Proyecto.objects.get(nombre_proyecto=name)
proyecto.nombre_proyecto = "newname"
proyecto.save()

If you want to update multiple documents in the queryset.

Proyecto.objects.filter(nombre_proyecto=name).update(nombre_proyecto="newname")

Note if Proyecto.objects.filter(nombre_proyecto=name) gives more than one document, Dont use get .Use update .Otherwise it will occur multple objects returned error.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM