How to use a filter in queryset, so users are limited to view their own answers? - filter

I made an application form. A user can use this form many times. Everytime a user uses the form, the input is added to the queryset in views.py. Now, I want users to see only their input in the html file. The filter i'm using in my views does not seem to work. Could anybody help me?
def requestlist(request):
object_list = MODEL.objects.all().order_by('timestamp')
if request.user.is_authenticated():
object_list = MODEL.objects.filter(user=self.request.user)
else:
raise PermissionDenied
context = {
"object_list": queryset,
}
return render(request, "requestlist.html", context)
All ideas are appreciated!

You have to return the object_list in the context as there is no 'queryset' variable
def requestlist(request):
object_list = MODEL.objects.all().order_by('timestamp')
if request.user.is_authenticated():
object_list = MODEL.objects.filter(user=self.request.user)
else:
raise PermissionDenied
context = {
"object_list": object_list,
}
return render(request, "requestlist.html", context)

Related

Is there a way to call pagination methods get_next_link and get_previous_link in DRF viewset?

I want to add additional values ​​to the pagination response in my viewset and keep the fields what already there. I was able to add count, but i can`t add next and previous urls to response, is where a way to call pagination_class methods in viewset.
def list(self, request, *args, **kwargs):
queryset = self.filter_queryset(self.get_queryset())
page = self.paginate_queryset(queryset)
if page is not None:
serializer = self.get_serializer(queryset, many=True)
return self.get_paginated_response(serializer.data)
else:
status_count = Vps.objects.all().aggregate(
started=Count("status", filter=Q(status="started")),
blocked=Count("status", filter=Q(status="blocked")),
stopped=Count("status", filter=Q(status="stopped"))
)
serializer = self.get_serializer(queryset, many=True)
status_count["results"] = serializer.data
return Response(status_count)
def get_paginated_response(self, data):
status_count = Vps.objects.all().aggregate(
started=Count("status", filter=Q(status="started")),
blocked=Count("status", filter=Q(status="blocked")),
stopped=Count("status", filter=Q(status="stopped"))
)
pagination = self.pagination_class()
page = self.paginate_queryset(data)
return Response(OrderedDict([
('count', pagination.get_count(data)),
('next', self.pagination_class.get_next_link),
('previous', self.pagination_class.get_previous_link),
('started', status_count["started"]),
('blocked', status_count["blocked"]),
('stopped', status_count["stopped"]),
('results', page)
]))
I was able to solve this by creating custom pagination class
class VpsLimitOffsetPagination(LimitOffsetPagination):
def get_paginated_response(self, data):
status_count = Vps.objects.all().aggregate(
started=Count("status", filter=Q(status="started")),
blocked=Count("status", filter=Q(status="blocked")),
stopped=Count("status", filter=Q(status="stopped"))
)
return Response(OrderedDict([
('count', self.count),
('started', status_count["started"]),
('blocked', status_count["blocked"]),
('stopped', status_count["stopped"]),
('next', self.get_next_link()),
('previous', self.get_previous_link()),
('results', data)
]))

A simple query but Graphene-Django is returning null values

I am trying to make a simple query with graphene-django but i can not get the DB, it gives me null.
I think the code is ok, what is going wrong, I am working for hours on it.
Do you have any idea, what it is?
Thanks in advance
import graphene
from graphene_django.types import DjangoObjectType, ObjectType
from myProject.models import Times
class TimesType(DjangoObjectType):
class Meta:
model=Times
fields="__all__"
class Query(ObjectType):
today_times = graphene.Field(TimesType, id=graphene.ID())
all_times = graphene.List(TimesType)
def resolve_todaytimes(self, info, id=None):
return Times.objects.get(pk=id)
def resolve_alltimes(root, info, **kwargs):
return Times.objects.all()
schema = graphene.Schema(query=Query, mutation=Mutation)
query {todayTimes(id:"1029"){id}}
{
"data": {
"todayTimes": null
}
}
The resolver method should be named in resolve_<FieldName> format
class Query(ObjectType):
today_times = graphene.Field(TimesType, id=graphene.ID())
all_times = graphene.List(TimesType)
def resolve_today_times(self, info, id=None): # not `resolve_todaytimes`
return Times.objects.get(pk=id)
def resolve_all_times(root, info, **kwargs): # not `resolve_alltimes`
return Times.objects.all()
Alternatively, you can use the resolver parameter to set the callable resolver as,
def resolve_todaytimes(self, info, id=None):
return Times.objects.get(pk=id)
def resolve_alltimes(root, info, **kwargs):
return Times.objects.all()
class Query(ObjectType):
today_times = graphene.Field(
TimesType,
id=graphene.ID(),
resolver=resolve_todaytimes
)
all_times = graphene.List(
TimesType,
resolver=resolve_alltimes
)

django: inlineformset very slow

I have the following models:
class Recipe(models.Model):
....
class Ingredient(models.Model):
....
class RecipePosition(models.Model):
recipe = models.ForeignKey(Recipe,related_name='recipe_positions', on_delete=models.CASCADE)
ingredient = models.ForeignKey(Ingredient,related_name='ingredient_recipeposition',on_delete=models.PROTECT) ....
in my views.py i am trying to create an inlineformset so that i can edit all the Reciposition related to particular Recipe:
def recipe_ingredients_formset_update(request,slug=None):
instance = get_object_or_404(Recipe.objects.prefetch_related('recipe_positions__ingredient'), slug=slug)
RecipeIngredientsFormSet = inlineformset_factory(Recipe,RecipePosition,form=RecipePoistionForm, can_delete=True, extra=5)
if request.method == "POST":
formset = RecipeIngredientsFormSet(request.POST, request.FILES, instance=instance)
helper = RecipePositionCreateFormSetHelper()
if formset.is_valid():
formset.save()
# Do something. Should generally end with a redirect. For example:
messages.success(request, "Successfully Updated", extra_tags='alert')
return HttpResponseRedirect('')
else:
formset = RecipeIngredientsFormSet(instance=instance)
helper = RecipePositionCreateFormSetHelper()
context = {
"instance":instance,
"formset":formset,
"helper":helper,
"url":instance.get_absolute_url_recipe_update_inline_bulk_ingredients()
}
return render(request, 'recipe_recipositions_bulk_edit.html', context)
I searched on net, but not able to understand. I am using Django Debug toolbar.
If i have 56 RecipePosition items for a particular Recipe. it took me 36 seconds to load

Error when returning a HttpResponse from a Django Helper Function

I have the below code in a basic Django view, which creates a new product and I am using AJAX to filter a list of industries. I would like to move the ajax processing code into a separate method but I am getting that the view didn't return an HttpResponse object. It returned None instead.
Can anyone recommend the way to separate it out safely? I have other views that use the exact logic.
def new_instrument(request):
if request.is_ajax() and request.method == 'GET':
if request.GET.get('typeis') =='industry':
print('Now loading industries')
sectorid = int(request.GET.get('sector_is'))
sector = models.SecSectorMaster.objects.filter(pk=sectorid).order_by('sectorname')
industries = models.SecIndustryMaster.objects.filter(sectorid=sector).order_by('industryname')
industry_dict = {}
for this_i in industries:
industry_dict[this_i.industryid] = this_i.industryname
return HttpResponse(
json.dumps(industry_dict),
content_type="application/json"
)**
if request.method == 'POST':
mainform= forms.EditInstrumentForm(sector,industrygroup,industries,request.POST,prefix="main")
if mainform.is_valid():
security = mainform.save()
selectid = security.pk
return redirect('instrumentsapp.views.security_list')
else:
return render(request, 'instrumentsapp/edit_instrument.html', {'mainform': mainform})
else:
mainform = forms.EditInstrumentForm(prefix="main")
return render(request, 'instrumentsapp/edit_instrument.html', {'mainform': mainform})
You can separate your view and use JsonResponse directly, and you should return a response if your test fail, this might be your issue since they told you that it returned None instead. I believe you should write something like this
from django.http import JsonResponse
def get_industry(request):
if request.is_ajax() and request.method == 'GET':
if request.GET.get('typeis') =='industry':
print('Now loading industries')
sectorid = int(request.GET.get('sector_is'))
sector = models.SecSectorMaster.objects.filter(pk=sectorid).order_by('sectorname')
industries = models.SecIndustryMaster.objects.filter(sectorid=sector).order_by('industryname')
industry_dict = {}
for this_i in industries:
industry_dict[this_i.industryid] = this_i.industryname
return JsonResponse(industry_dict)
return JsonResponse({'industry': None})

post method in generic class based view is not called upon form submission in Django?

I have a written a mixin that overrides the POST and get_from_kwargs of CreateView. I am doing AJAX submission of my form. I see that get_from_kwargs is called by printing on the console. But none of the other methods such as post,form_valid or form_invalid is being called. I have placed print statements in these methods but none of them is being called.
Here is my mixin:
class PendFormMixin(object):
form_hash_name = 'form_hash'
pend_button_name = 'pend'
def get_form_kwargs(self):
"""
Returns a dictionary of arguments to pass into the form instantiation.
If resuming a pended form, this will retrieve data from the database.
"""
pk_form = self.kwargs.get('pk', None)
form_hash = None
if pk_form:
form_data = PendedForm.objects.get(pk=pk_form)
form_hash = form_data.hash
print "form_hash", form_hash
if form_hash:
import_path = self.get_import_path(self.get_form_class())
print import_path
print self.get_pended_data(import_path, form_hash)
return {'data': self.get_pended_data(import_path, form_hash)}
else:
print "called in kwargs"
# print super(PendFormMixin, self).get_form_kwargs()
return super(PendFormMixin, self).get_form_kwargs()
def post(self, request, *args, **kwargs):
"""
Handles POST requests with form data. If the form was pended, it doesn't follow
the normal flow, but saves the values for later instead.
"""
self.object = None
if self.pend_button_name in self.request.POST:
print "here"
form_class = self.get_form_class()
print form_class
form = self.get_form(form_class)
# print "form is ", form
self.form_pended(form)
return super(PendFormMixin, self).post(request, *args, **kwargs)
else:
print "here in post"
return super(PendFormMixin, self).post(request, *args, **kwargs)
# Custom methods follow
def get_import_path(self, form_class):
return '{0}.{1}'.format(form_class.__module__, form_class.__name__)
def get_form_hash(self, form):
content = ','.join('{0}:{1}'.format(n, form.data[n]) for n in form.fields.keys())
return md5(content).hexdigest()
def form_pended(self, form):
import_path = self.get_import_path(self.get_form_class())
form_hash = self.get_form_hash(form)
pended_form = PendedForm.objects.get_or_create(form_class=import_path,
hash=form_hash)
for name in form.fields.keys():
pended_form[0].data.get_or_create(name=name, value=form.data[name])
return form_hash
def get_pended_data(self, import_path, form_hash):
print "import_path is", import_path
print "form_hash is", form_hash
# data = PendedValue.objects.filter(import_path=import_path, form_hash=form_hash)
data = PendedValue.objects.filter(form__form_class=import_path, form__hash=form_hash)
print "data ", data
return dict((d.name, d.value) for d in data)
Here is my view:
class ArticleCreateView(PendFormMixin, CreateView):
form_class = ArticleForm
model = Article
template_name = "article_create.html"
# success_url = reverse_lazy('blog_create')
success_url = '/admin'
def form_valid(self, form):
"""
If the request is ajax, save the form and return a json response.
Otherwise return super as expected.
"""
if self.request.is_ajax():
self.object = form.save()
time.sleep(5)
print "here"
return HttpResponse(json.dumps("success"),
mimetype="application/json")
if self.pend_button_name in self.request.POST:
print "in the form_valid"
return
print "in the form_valid"
return super(ArticleCreateView, self).form_valid(form)
def form_invalid(self, form):
"""
We haz errors in the form. If ajax, return them as json.
Otherwise, proceed as normal.
"""
print "self is ", self.request.POST
if self.request.is_ajax():
return HttpResponseBadRequest(json.dumps(form.errors),
mimetype="application/json")
if self.pend_button_name in self.request.POST:
print "in the form_invalid"
return redirect('/admin')
return super(ArticleCreateView, self).form_invalid(form)
unable to figureout what is going wrong. It used to work previously, before I used the mixin. but by introducing the above mixin, the code does not work any more.

Resources