Checkboxes in a table and values post - python

I'm new on django and I wish to POST checkboxes values from a view to another view.
This is the snippet:
When I check the two only checkboxes that are in my table rows I have only one value (from Django debug window):
Variable Value
csrfmiddlewaretoken u'6i8aRyhvTq29EOy6sfffzPtKy9jXUsVi'
Login u'jhgjghj'
but the post objects should be:
Variable Value
csrfmiddlewaretoken u'6i8aRyhvTq29EOy6sfffzPtKy9jXUsVi'
Login u'jhgjghj'
Login u'sdfsfd' (the second object not posted)
In addition I have a second problem.
This is the view to which I pass these POST data:
def deleteObjects(request):
template = 'delObj.html'
objects = []
for obj in request.POST.items():
if obj('Login'):
todelete = Login.objects.get(obj('Login'))
objects.append(todelete)
context = {'objects' : objects}
return render(request, template, context)
I get an error "Tuple object is not callable" (for the row if obj('name') == 'Login':), but i can't understand why.
Aren't POST data elements KEY and VALUE of a dict-like object?
Thanks in advance

Yes, POST is a dict-like object, but you seem to have a misunderstanding about how those work. items() returns a tuple of (key, value) for each item in the dict - so, for example, obj would be ('Login', 'jhghghj'). So it makes no sense to say obj('Login'): obj is not callable, and neither is it accessed via dict notation (which would be obj['login']). Instead you would want this:
for key, value in request.POST.items():
if key == 'Login':
todelete = Login.objects.get(value)
However, and here's where we get to your first problem, I can't understand why you want to iterate through at all. Like you said, request.POST is a dict-like object, and you want a single key, Login. So normally you would simply get the value of Login via request.POST['Login'] - except that you have two values for Login, and the reason POST is only dict-like and not actually a dict is that it defines a getlist method for exactly this use case. So, this is what you want:
for value in request.POST.getlist('Login'):
todelete = Login.objects.get(value)

Related

django pass field-name as variable in get_or_create

I am trying to see if I can pass field name as a variable in get_or_create (since I have a function where the key in the kwargs can vary)
Like so:
def convert_value(cell_value, field_to_lookup):
rem_obj, created = Rem.objects.get_or_create(field_to_lookup=cell_value)
print ('created? ',created)
return rem_obj
The above wont work since it would look for 'field_to_lookup' as the key.
This post suggests using getattr but not sure if that'll be applicable in this case since I will again need to assign the output to a variable
This post helped. Now passing the field-value pair as dict which allows passing variables for field names. Here's the code:
def convert_value(cell_value, field_to_lookup):
rem_obj, created = Rem.objects.get_or_create(**{field_to_lookup:cell_value})
print ('created? ',created)
return rem_obj
Alternatively, I could directly just pass the dict to the function.

Django Update Model Field with Variable User Input... .update(key=value)

I'm attempting to create a function to allow updates to fields based on the front-end input.
The handler would receive a profile_updates dictionary with two keys. Each will contain a list of key/value pairs.
list_of_updates['custom_permissions'] = [{"is_staff":"True"},{"other_permission":"False"}]
def update_profile(message):
list_of_updates = message['profile_updates']
user_update_id = message['user_id']
for update in list_of_updates['custom_permissions']:
for key, value in update.iteritems():
User.objects.filter(id=user_update_id).update(key=value)
I would like to make 'key' a variable fed from the .iteritems().
Appreciate anyone's input on how, or if, this is possible.
You don't need to loop through the dict. You can pass it as a kwarg expansion.
def update_profile(message):
list_of_updates = message['profile_updates']
user_update_id = message['user_id']
for update in list_of_updates['custom_permissions']:
User.objects.filter(id=user_update_id).update(**update)

change request.GET QueryDict values

I want to change request.GET querydict object in django. I tried this but changes made by me are not reflected. I tried this
tempdict = self.request.GET.copy() # Empty initially
tempdict['state'] = ['XYZ',]
tempdict['ajaxtype'] = ['facet',]
print self.request.GET
I get
<QueryDict: {}> as my output
Is it possible to change the request.GET querydict object in django?
You can't change the request.GET or request.POST as they are instances of QueryDict which are immutable according to the docs:
QueryDict instances are immutable, unless you create a copy() of them. That means you can’t change attributes of request.POST and request.GET directly.
Your code should work if you add one little step: you are now making a copy of the request.GET, but you have not assigned it back to the request. So it is just a standalone object which is not related to the request in any way.
This would the the necessary improvement:
tempdict = self.request.GET.copy()
tempdict['state'] = ['XYZ',]
tempdict['ajaxtype'] = ['facet',]
self.request.GET = tempdict # this is the added line
print(self.request.GET)
I have tested it in writing custom middleware, but I assume it works the same way in all places.

Why QueryDict returns a list when checking for an object?

i'm tring a thing with ** operator
i've this function
def splitData(data, operation, n=0, m=0):
..
log.debug("data: %s",data)
...
and i call it from an API (django-rest-framework) view that takes data from a POST
so what i do is this
log.debug("data from get %s",request.DATA.get('data','[]'))
res = splitData(**request.DATA)
result is correct
data from get [{'id':1,'a1':1},{'id':2,'a1':2}]
while the output form the debug inside the splitData function is this
data: [u"[{'id':1,'a1':1},{'id':2,'a1':2}]"]
why the data that is taken from the **request.DATA is a list?
(There's no such thing as request.DATA - presumably you mean request.REQUEST. Please post actual code in future.)
This has nothing to do with kwargs.
It is because request data is a QueryDict object, which is customised to allow multiple values for each key.

Django HttpRequest problem

I'm trying to gat the value of a form field in django, now
xxx = request.POST[u'a1']
gives me a value, but
xxx = request.POST.get(u'a1')
gives me nothing
what am I doing wrong?
Update:
Using the first method, request.method = POST,
using the second method changes it to GET,
all I am doing is replacing one line of code.
Ingmar, yes this does return true.
Shawn, first method produces DEBUG:root:[(u'a1', u'A1_6')],
second method produces DEBUG:root:[]
The get method takes two parameters: key and a return value for where there's no match for the key (defaults to None).
Maybe the first example worked only in cases where the form had a value in the field 'a1'.
Either set a return value for the get method (e.g. xxx = request.POST.get(u'a1', 'something')) or check in advance whether you have that field in the form (if u'a1' in request.POST ...)
A bit confusing question, but the way I understand you, you have a request that at one point contains a QueryDict with data in request.POST, but at a later point in the code cointains an empty QueryDict: {} in request.POST, and you are looking for the reason why and where the data disappears.
The Django docs say the QueryDict in HttpRequest is immutable, and cannot be changed. So you probably shouldn't be looking for code changing the value of the request.POST QueryDict, but some code that replaces the whole request.POST QueryDict with another one.
My guess is that you are assigning the value 'GET' to request.method at some point in the code, since you say that in function number two, request.method is changed to GET
When tinkering with a response of the type PUT some time ago I discovered that django actually applies logic to the HttpResponse object if response.method is changed, resulting in a changed request.POST QueryDict.

Categories