Using json to copy data (Django)

Asked

Viewed 524 times

2

I thought better, and I think I’ll use json.

def entry_detail_json(request, pk):
    data = Entry.objects.filter(pk=pk)
    s = serializers.serialize("json", data)
    return HttpResponse(s)

But being on the page

http://localhost:8000/entry/2/

how do I refer to the page

http://localhost:8000/entry/json/2/

And assigns the values in the following function to copy the data?

I got the result as follows:

<input name="new_proposal" type="submit" class="btn btn-primary" value="{{ entry.id }}" 

py views.

def create_proposal(request, employee_pk=1, **kwargs):
    f = None
    if request.method == 'GET':
        f = request.GET['new_proposal']
    if f:
        employee = Employee.objects.get(pk=employee_pk)  # TODO
        nlp = NumLastProposal.objects.get(pk=1)  # sempre pk=1
        # entry = Entry.objects.get(pk=kwargs.get('pk', None))
        entry = Entry.objects.get(pk=f)
        obj = Proposal(
            num_prop=nlp.num_last_prop + 1,
            type_prop='R',
            category=entry.category,
            description=entry.description,
            work=entry.work,
            person=entry.person,
            employee=employee,
            seller=entry.seller,
        )
        obj.save()
        # Define que foi dado entrada
        entry.is_entry = True
        entry.save()
        # Incrementa o número do último orçamento
        nlp.num_last_prop += 1
        nlp.save()
        print('Orçamento criado com sucesso')
    return redirect('proposal_list')

It’s working, but I know it’s not the best way to treat it.

And in the end I ended up not using JSON. How I would use JSON instead of doing as I did?

[{"pk": 2, "fields": {"work": 2, "description": "Ih1vwUcIYwc0ce", "created": "2015-07-31T19:41:04.408Z", "priority": "u", "category": 1, "person": 45, "seller": 2, "is_entry": true, "modified": "2015-07-31T21:11:59.165Z"}, "model": "core.entry"}]
  • It’s not clear enough what you’re wanting.

  • @Orion Note that the information I’m passing in obj = Proposal(...), the values come from each entry field = Entry.objects.get(pk=entry_detail_json(2)) # or something similar What I wanted to do, and that maybe it’s simpler, is to take all values from the json that I generated at the url address, but I don’t know how to do that. I was trying this because actually I couldn’t get the current Entry id inside the page.

  • I still can not understand, try to reduce the code only to what matters and edit the question more clearly, because personally I am not able to understand the doubt.

  • @Orion edited the question, I hope you have clarified better.

  • @Regisdasilva reopened the question. Can you remove that last Edit and put it as an answer? This makes it more useful for those who have the same problem in the future.

1 answer

0

As I understand it, you need to send the entry.id value (in this case 2) to the "entry-Detail-json" view which, in your case, you are sending by GET parameter, correct?

You can name the url and send "entry.id" as the url parameter.

For example, imagine you have the url that will process json:

 url(r'^entry-detail-json/(?P<pk>\d*)', 
     'link.para.entry_detail_json',  
      name='entry-detail-json')

Note the

... "name='entry-detail-json'"... 

In order to access this url in the template where you have entry.id, just type:

<a href="{% url 'entry-detail-json' pk=entry.id %}">Json entry</a>

I think in your case, you really need that line:

{% url 'nome_do_url' nome_do_parametro=valor_do_parametro %}

In this case the value of "entry.id" will be injected into the view as the name "pk":

def entry_detail_json(request, pk):
    data = Entry.objects.filter(pk=pk)
    s = serializers.serialize("json", data)
    return HttpResponse(s)

You can also call the url of another view:

return redirect('entry-detail-json', pk=entry.id)

You can even pass more than one parameter, making this url a kind of json output

url:

url(r'^json-output/(?P<obj_type>\w*)/(?P<pk>\d*)',
    'link.para.json_output', 
     name='json-ouput')

view:

import json

def json_output(request, obj_type=None, pk=None):

    if obj_type is None or pk is None:
        return HttpResponseBadRequest

    if obj_type == "entry" :
        data = Entry.objects.filter(pk=pk)
        return HttpResponse(json.dumps(data)), mimetype='application/json')
    elif obj_type == "other_object"
        data = OtherObject.objects.filter(pk=pk)
        return HttpResponse(json.dumps(data)), mimetype='application/json')
    else:
        return HttpResponseBadRequest

template:

<a href="{% url 'json-output' obj_type="entry" pk=entry.id %}">Json entry</a>
<a href="{% url 'json-output' obj_type="other_object" pk=other.id %}">Json Object</a>

I hope that’s what you’re looking for.

Regards

Browser other questions tagged

You are not signed in. Login or sign up in order to post.