简体   繁体   English

Django request.method ='GET'无法正常工作

[英]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. 我试图在我的应用程序上加载数据库表数据,以便对其进行更新,到目前为止,我发现这是由request.method = 'GET'完成的request.method = 'GET'不知道是否总是这样,但可以肯定的是,这是实现此目的的方法之一。

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. 但是,我的应用程序充满了POST请求,要在db表上创建新文档,我只需要通过指定其名称来检索其中之一。 Using 'GET' method. 使用'GET'方法。 But it's not working, seems like it doesn't evaluates the expression, I don't really know why. 但是它不起作用,似乎无法评估表达式,我真的不知道为什么。

This is my models.py : 这是我的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. 我将使用existente BooleanField作为模板上的复选标记,如果该existente是活动的,则通过它的nombre_proyecto字段(项目名称)执行查询并携带指定的文档。

My forms.py : 我的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: 我的views.py方法所在:

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. 在这里, if existente is not None and existente != '':条件应该评估inicial.html上的existente标记是否处于活动状态,如果是,则渲染proyecto.html模板。

The inicial.html interesting code with checkmark: 带有复选标记的inicial.html有趣代码:

<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 : 如果此复选框处于活动状态,则渲染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. 这就是existente BooleanField的全部逻辑,对不起,如果听起来有点笨拙,但这是一个已经开始的项目,有时会造成混乱。

If you have any idea about why this isn't evaluating that conditional plz let me know, I just can't figure it out . 如果您对为什么不评估有条件的plz有任何想法,请告诉我,我就是无法解决。

Many thanks in advance! 提前谢谢了!

PS = I'm using Django==1.6.1 , Python 3.3.1 and PostgreSQL v9.0. PS =我正在使用Django==1.6.1 ,Python 3.3.1和PostgreSQL v9.0。

No need of use of filter.exists . 无需使用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. 如果查询不匹配任何文档,它将返回[] 。因此id不会进入if条件。 emptylist emptystring在python中表示False

if all you want to do is determine if at least one result exists. 您要做的就是确定是否至少存在一个结果。 It's more efficient to use exists(). 使用exist()更有效。

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

If you want to update .Simply use get . 如果要update 。只需使用get

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

If you want to update multiple documents in the queryset. 如果要更新查询集中的multiple文档。

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. 请注意,如果Proyecto.objects.filter(nombre_proyecto=name)提供了多个文档,请不要使用get .Use update否则将发生多个multple objects returned错误。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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