Python dictionary as parameter with multiple values ββin dictionary
I'm new to python, started with python 3 and django1.8. Can we pass a dictionary as a parameter with multiple values ββin it, but fewer arguments in the function definition.
def save_myobj(request):
'''
'''
reqobj = dict(zip(request.POST.keys(), request.POST.values()))
my_dict = prepare_profile_dict(**reqobj)
obj = Model.objects.get(pk=1)
obj.__dict__.update(my_dict)
obj.save()
return HttpResponse("true")
Here is my request object:
reqobj = {
u'csrfmiddlewaretoken': u'xzlrzJkpKb0aAIvdJ7Z7aX05uhHjnwjX',
u'email': u'',
u'first_name': u'abc',
u'last_name': u'def',
u'revenue': u''
}
and here prepare_profile_dict
def prepare_profile_dict(first_name, last_name, email):
''' '''
return {
"revenue" : get_revenue(),
"first_name":first_name,
"last_name":last_name,
"email":email
};
But getting an error,
TypeError at /profile/save/
prepare_profile_dict() got an unexpected keyword argument 'revenue'
I don't think there is anything to do with the model.
class Model(models.Model):
'''
'''
first_name = models.TextField("first_name", blank=True, null=True, db_index=True)
last_name = models.TextField("last_name", blank=True, null=True, db_index=True)
email = models.TextField("email", blank=True, null=True, db_index=True)
revenue = models.IntegerField()
source to share
Yours prepare_profile_dict
does not take an argument revenue
(as stated in the error message); only first_name
, last_name
and email
. However, your dict extension contains the keyword when you call the function revenue
. Or remove it from reqobj
:
del reqobj['revenue']
or add an argument **kwargs
at the end prepare_profile_dict
to catch any additional keyword arguments (which will be ignored inside the function).
def prepare_profile_dict(first_name, last_name, email, **kwargs):
...
(Obviously, the same happens for csrfmiddlewaretoken
.)
Alternatively, you can use the querysets
update
method:
def save_myobj(request):
reqobj = dict(zip(request.POST.keys(), request.POST.values()))
my_dict = prepare_profile_dict(**reqobj)
# ensure my_dict only contains relevant keys
Model.objects.get(pk=1).update(**my_dict)
# No .save method needed
return HttpResponse("true")
source to share
Smart solution using ModelForm
:
# forms.py
from django import forms
from .models import Profile
from .somewhere import get_revenue
class ProfileForm(forms.ModelForm):
class Meta:
model = Profile
fields = "__all__"
def clean_revenue(self):
return get_revenue()
# views.py
from .forms import ProfileForm
from .models import Profile
def save_myobj(request):
if request.method !== "POST":
return HttpResponseNotAllowed(["POST"])
profile = Profile.objects.get(pk=1)
form = ProfileForm(request.POST, instance=profile)
if form.is_valid():
form.save()
return HttpResponse("true")
# returning form.errors might be better
# but anyway:
return HttpResponse("false")
source to share