What's the best way of passing a param using a ModelViewSet? Forexample achieving something like this :
http://127.0.0.1:8000/api/v1/financing-settings/template/?param=block
Below is the approach I was using but found out I have set the param in the body section, but it's not what I want :
class TemplateView(ModelViewSet):
"""ViewSet for Saving Block/ Step template."""
def list(self, request, *args, **kwargs):
"""Get list of Block/Steps with is_process_template is equal to True."""
param = request.data['param']
if param == "block":
_block = Block.objects.filter(is_process_template=True).values()
return JsonResponse({"data": list(_block)}, safe=False, status=200)
elif param == "step":
_step = Step.objects.filter(is_process_template=True).values()
return JsonResponse({"data": list(_step)}, safe=False, status=200)
return Response(status=status.HTTP_204_NO_CONTENT)
param = request.GET.get('param')
or for a post request
param = request.POST.get('param')
param = request.query_params.get('param')
Related
Im trying to add a payment method.
I also add Getway and Get Success Message.
Now I want to show success message with cid and name in my template page.
When I want to get context data, I got This Error.
** Local variable 'cid' referenced before assignment. **
My code:
class CheckoutSuccessView(View):
model = Transaction
template_name = 'success.html'
def get(self, request, *args, **kwargs):
# return render(request, self.template_name,{'transaction':transaction})
return HttpResponse('nothing to see')
def post(self, request, *args, **kwargs):
data = self.request.POST
try:
Transaction.objects.create(
name = data['value_a'],
cid = data['value_b'],
tran_id=data['tran_id'],
val_id=data['val_id'],
amount=data['amount'],
card_type=data['card_type'],
card_no=data['card_no'],
...
...
)
messages.success(request,'Payment Successfull')
name = data['value_a'],
cid = data['value_b'],
except:
messages.success(request,'Something Went Wrong')
context = {
'cid': cid,
'name' : name
}
return render(request, 'success.html', context)
You may miss block or put extra indentation.
Define it before try block.
You may try this:
class CheckoutSuccessView(View):
model = Transaction
template_name = 'success.html'
def get(self, request, *args, **kwargs):
# return render(request, self.template_name,{'transaction':transaction})
return HttpResponse('nothing to see')
def post(self, request, *args, **kwargs):
data = self.request.POST
name = data['value_a'],
cid = data['value_b'],
try:
Transaction.objects.create(
name = data['value_a'],
cid = data['value_b'],
tran_id=data['tran_id'],
val_id=data['val_id'],
amount=data['amount'],
card_type=data['card_type'],
card_no=data['card_no'],
...
...
)
messages.success(request,'Payment Successfull')
except:
messages.success(request,'Something Went Wrong')
context = {
'cid': cid,
'name' : name
}
return render(request, 'success.html', context)
I think you are using sslcommerz-lib for SSLCOMMERZ PAYMENT GATEWAY.
In my Django Project I have the following Problem:
I would like to have a dynamic Django form. In the first step the user is asked something by the first form. When I get the postmethod the variables should be used for genereating a new form
my views.py
def calc(request):
if request.method =="POST":
get_form = CalculationForm(request.POST)
if get_form.is_valid():
op = get_form.cleaned_data['op']
ab = get_form.cleaned_data['ab']
alternative = AlternativForm(optype = op, wsgroup = ab)
return render(request, 'calculated_lensar.html', {"alternativ" : alternativ})
else:
form = CalculationForm()
return render(request, 'calc.html', {'form': form})
The secondform (postmethod) looks like
class AlternativForm(forms.Form):
praep_button = ((3, 'hallo'), (4, 'tschüss'))
def __init__(self, optype, wsgroup, *args, **kwargs):
super(AlternativForm, self).__init__(*args, **kwargs) #dont know for what this is standing
self.optype = optype
self.wsgroup = wsgroup
self.values = self.read_db()
self.praep_button = self.buttons()
self.felder = self.blub()
self.neu2 = self.myfield_choices()
def read_db(self):
import sqlite3
....
return result #tuple with 15x5 elements
def buttons(self):
praep_button = []
for i in self.values:
praep_button.append((i[4], i[1]))
return praep_button #Just formating result from read_db in tuple(15x2)
def blub(self):
return forms.ChoiceField(widget=forms.RadioSelect, choices=self.praep_button)
myfield = forms.ChoiceField(widget=forms.RadioSelect, choices=praep_button) #print --><django.forms.fields.ChoiceField object at 0x751f9b90>
def myfield_choices(self):
field = self['myfield']
"""i think here is the problem.
Above 'myfield' is a django.forms.fields.ChoiceField object, but here it is rendered to html (like it should be). I have the code from https://stackoverflow.com/questions/6766994/in-a-django-form-how-do-i-render-a-radio-button-so-that-the-choices-are-separat.
But instead i should use field = self.felder (radioselect woth tuple of the db)"""
widget = field.field.widget
attrs = {}
auto_id = field.auto_id
if auto_id and 'id' not in widget.attrs:
attrs['id'] = auto_id
name = field.html_name
return widget.render(name, field.value(), attrs=attrs)
#return widget.get_renderer(name, field.value(), attrs=attrs)
So all in all I hope the problem is clear.
If i am using AlternativForm() i get the constant form. Instead i would like to get a dynamic form. If I access in views.py:
alternative = AlternativForm(optype = op, wsgroup = ab)
alternative = alternativ.felder
than I get . Can I render that to html?
If I set in forms.py:
field = self.felder
than I get the error that it is a field and not a widget
Thank you for reading!
You just need to assign the choices in the form's __init__() method. Almost what you're doing, but instead of defining self.felder to be a field, you need to use the already initialised form's fields:
myfield = forms.ChoiceField(widget=forms.RadioSelect, choices=praep_button)
def __init__(self, optype, wsgroup, *args, **kwargs):
super().__init__(*args, **kwargs)
self.fields['myfield'].choices = self.get_choices(optype, wsgroup) # create your choices in this method
def get_choices(optype, wsgroup):
# call your other methods here
return praep_button
class IndexAjaxView(View):
def get(self, request):
param = request.GET.get('param')
if param == 'get_total_topup':
return self.get_total_topup()
return JSONResponse({}, status=404)
def get_total_topup(self, request):
return JSONResponse({
'value': 'Rp.{:,.0f},-'.format(
TopUp.objects.filter(owned_by=request.user).aggregate(Sum('amount'))['amount__sum']
)
})
somebody can help me ? I want to get data via ajax, but the response is 500 with message get_total_topup() missing 1 required positional argument: 'request'
Your call in return self.get_total_topup() has no arguments but your definition def get_total_topup(self, request) requires one. Try return self.get_total_topup(request).
class IndexAjaxView(View):
def get(self, request):
param = request.GET.get('param')
if param == 'get_total_topup':
return self.get_total_topup(request) # <--- just change this
return JSONResponse({}, status=404)
def get_total_topup(self, request):
return JSONResponse({
'value': 'Rp.{:,.0f},-'.format(
TopUp.objects.filter(owned_by=request.user).aggregate(Sum('amount'))['amount__sum']
)
})
You are missing one positional argument in the method call.
return self.get_total_topup()
Fix it to
return self.get_total_topup(request)
According to this post, I'm trying to modify my whole script in order to get Class Based Views (CBV) in my Django application.
I would like to get any help, because it's the first time I'm using CBV.
My previous script function looks like this :
#login_required
def IdentityIndividuForm(request) :
success = False
query_Nom_ID = query_Prenom_ID = query_VilleNaissance_ID = None
if 'recherche' in request.GET:
query_Nom_ID = request.GET.get('q1NomID')
query_Prenom_ID = request.GET.get('q1PrenomID')
query_VilleNaissance_ID = request.GET.get('q1VilleNaissanceID')
sort_params = {}
lib.Individu_Recherche.set_if_not_none(sort_params, 'Nom__icontains', query_Nom_ID)
lib.Individu_Recherche.set_if_not_none(sort_params, 'Prenom__icontains', query_Prenom_ID)
lib.Individu_Recherche.set_if_not_none(sort_params, 'VilleNaissance__icontains', query_VilleNaissance_ID)
query_ID_list = Individu.objects.filter(**sort_params)
else :
query_ID_list = Individu.objects.none()
if request.method == 'POST':
form = IndividuFormulaire(request.POST or None, request.FILES or None)
if form.is_valid() :
post = form.save()
return HttpResponseRedirect(reverse('IndividuResume', kwargs={'id': post.id}))
else :
form = IndividuFormulaire()
form.fields['Utilisateur'].initial = request.user.last_name + " " + request.user.first_name
context = {
"form" : form,
"Individu" : Individu,
"query_Nom_ID" : query_Nom_ID,
"query_Prenom_ID" : query_Prenom_ID,
"query_VilleNaissance_ID" : query_VilleNaissance_ID,
"query_ID_list" : query_ID_list,
}
return render(request, 'Identity_Individu_Form.html', context)
I had a GET part and a POST part in my function but both part are independent. The first one lets to make a research over my database. The second one lets to create an object to my database.
My question is : How I can overwrite the GET part with function based on CBV ?
My new function form_valid(self, form) works well, but I don't overcome to migrate the GET part to my CBV part.
Thank you!
You can try it, first get super context data, after it do processing as you wish and after it update the contest data with yours
by default CreateView is subclass of the ProcessFormView that provide get method, as:
def get(self, request, *args, **kwargs):
form_class = self.get_form_class()
form = self.get_form(form_class)
return self.render_to_response(self.get_context_data(form=form))
so you can try to override the get method with return as:
return self.render_to_response(self.get_context_data(request, form=form))
and the get_context_data
def get_context_data(self, **kwargs) :
context_data = super(IdentityIndividuFormView, self).get_context_data(**kwargs)
if 'recherche' in self.request.GET:
query_Nom_ID = self.request.GET.get('q1NomID')
query_Prenom_ID = self.request.GET.get('q1PrenomID')
query_VilleNaissance_ID = self.request.GET.get('q1VilleNaissanceID')
sort_params = {}
lib.Individu_Recherche.set_if_not_none(sort_params, 'Nom__icontains', query_Nom_ID)
lib.Individu_Recherche.set_if_not_none(sort_params, 'Prenom__icontains', query_Prenom_ID)
lib.Individu_Recherche.set_if_not_none(sort_params, 'VilleNaissance__icontains', query_VilleNaissance_ID)
query_ID_list = Individu.objects.filter(**sort_params)
context_data['queryset'] = query_ID_list
else :
query_ID_list = Individu.objects.none()
context_data['queryset'] = query_ID_list
return context_data
I see another issue here, that you missed out #login_required part of the check here, to do so use the mixin like this :
from django.contrib.auth.mixins import LoginRequiredMixin
class IdentityIndividuFormView(LoginRequiredMixin, CreateView) :
And I suppose in case of GET request you can update the context using this:
def get(self, request, *args, **kwargs):
Am trying to override save() method so that only the creator and administrator are able to update the model field values as :
if not self.pk:
super(Shastra, self).save(*args, **kwargs)
else:
if (self.person == args[0].user) or (self.person.is_superuser):
super(Shastra, self).save(*args, **kwargs)
While update am passing request to the save method as
def edit(request, shastra_id):
shastra_id = int(shastra_id)
shastra = Shastra.objects.get(pk = shastra_id )
if request.method == 'POST':
form_shastra_edit = ShastraEditForm(request.POST, instance = shastra)
if form_shastra_edit.is_valid():
form_shastra_edit.save(request)
return HttpResponseRedirect('/edited/successfully')
else:
form_shastra_edit = ShastraEditForm(instance = shastra)
But am getting " tuple index out of range " error . What is going wrong in this ?
You can not use request in a Model.save() method. You have to do request-based validation in your views method (in your edit method for instance). The Model layer is unaware of 'request' objects..
Make your edit method something like:
def edit(request, shastra_id):
shastra_id = int(shastra_id)
shastra = Shastra.objects.get(pk = shastra_id )
if request.method == 'POST':
form_shastra_edit = ShastraEditForm(request.POST, instance = shastra)
if form_shastra_edit.is_valid() and shastra.user == request.user:
form_shastra_edit.save(request)
return HttpResponseRedirect('/edited/successfully')
else:
form_shastra_edit = ShastraEditForm(instance = shastra)