TypeError at /stories/story_id story_detail() missing 1 required positional argument: 'story_id' - arguments

I want the user to click through all customer's stories to read up on an individual story. But getting this error:
**TypeError at /stories/story_id
story_detail() missing 1 required positional argument: 'story_id'**
My Views.py:
def all_stories(request):
""" A view to show all stories, including search function """
stories = Stories.objects.all()
context = {
'stories': stories,
}
return render(request, 'stories/stories.html', context)
def story_detail(request, story_id):
""" A view to show individual story detail """
story_detail = get_object_or_404(Story, pk=story_id)
context = {
'story': story_detail,
}
return render(request, 'stories/story_detail.html', context)
My urls.py:
from django.urls import path
from . import views
urlpatterns = [
path('', views.all_stories, name='stories'),
path('story_id', views.story_detail, name='story_detail'),
]
I'm not sure what I have done or can do to fix this, can somebody help?

Related

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
)

graphene could not convert string to float in SerializerMutation

Is the SerializerMutation suppose to convert ID! from base64 to a pk? Is there some frontend/backend helper util to assist in conversion? I haven't been able to find anything specific.
Example create thing mutation:
class CreateThingMutation(SerializerMutation):
#classmethod
def get_serializer_kwargs(cls, root, info, **input):
import pdb;pdb.set_trace()
return None
#classmethod
def mutate_and_get_payload(cls, root, info, text, id):
import pdb;pdb.set_trace()
return None
class Meta:
serializer_class = ThingListViewSerializer
Example query:
mutation TestCreate($input: CreateThingMutationInput!) {
createThing(input: $input) {
item {
id
}
}
}
Example ID!:
item.id === atob('VW5pdE5vZGU6MjA=') === "UnitNode:20"
Edit, I was failing to convert the ID all the way so i had "20", just converted the type:
Number(atob(item.id).split(':')[1])
Question still remains about if there are any utility tools to automagically convert data being submitted to a mutation.

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

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)

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

Which XPath to use while scraping Google Play store?

I am scraping the Google Play store for the app reviews. I am able to get only 40 reviews only. The problem is in the xhr path upon reaching scrapy throws error:
Http status code not handled or not allowed
Code:
import scrapy
from scrapy.exceptions import CloseSpider
from scrapy.spider import BaseSpider
from scrapy.http import Request
class Product(scrapy.Item):
brand = scrapy.Field()
title = scrapy.Field()
class aqaqspider(BaseSpider):
name = "gaana"
allowed_domains = ["play.google.com"]
start_urls = [
"https://play.google.com/store/apps/details?id=com.gaana&hl=en",
]
page = 1
def parse(self, response):
products = response.xpath('//div[#class="single-review"]')
if not products:
raise CloseSpider("No more products!")
for product in products:
item = Product()
#item['brand'] = product.xpath(".//span[contains(#class, 'qa-brandName')]/text()").extract()[0].strip()
item['title'] = product.xpath('.//.//div/div/span[#class="author-name"]/a/text()').extract()[0].strip()
yield item
self.page += 1
yield Request(url="https://play.google.com/store/getreviews?authuser=1" ,
headers={"Referer": "https://play.google.com/store/apps/details?id=com.gaana&hl=en", "X-Requested-With": "XMLHttpRequest"},
callback=self.parse,
dont_filter=True)
Please don't say that it is against their Terms of Use. I know that but I need to learn things and move on. I am not exploiting anything.

Resources