Django generic Views with templates - django-templates

I've added a new template to my project (thing_listings.html) and I've added the views;
from django.views import generic
from .models import Things
class IndexView(generic.ListView):
template_name = 'home/index.html'
def get_queryset(self):
return Things.objects.all()
**class ThingView(generic.ListView):
template_name = 'home/thing_listings.html'
def get_queryset(self):
return Things.objects.all()**
class DetailView(generic.DetailView):
model = Labs
template_name = 'home/detail.html'
and the URl's;
from django.conf.urls import url
from . import views
app_name = 'home'
urlpatterns = [
# /home/
url(r'^$', views.IndexView.as_view(), name = 'index'),
**# /thingview/
url(r'^$', views.ThingView.as_view(), name='thingview'),**
# /home/"details"/
url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'),
]
At the moment the site runs fine, except when I click on the thing_listings link I just get directed to index instead of what thing view is supposed to direct me to. Please help, I'm not sure where I've gone wrong.
Ive used the href: {% url 'home:thingview' %}

I've found the solution if anyone else is having the same issue.
All you should need to do is add the path to your regular expression eg:
url(r'^servicesview/$', views.ServicesView.as_view(), name='services'),
I've repeated the process multiple times to make sure it works.

Related

data i entered in the admin page not reflecting in my webpage,

The data i entered in the admin page not showing up on the web page.
i don't know what is going wrong with my code, please help
webpage
admin.py
from django.contrib import admin
from blog.models import Post
# Register your models here.
class PostAdmin(admin.ModelAdmin):
list_display = ('title','slug','status','created_on')
list_filter = ('status',)
search_fields = ['title','content']
prepopulated_fields = {'slug':('title',)}
admin.site.register(Post, PostAdmin)
urls.py
from . import views
from django.urls import path
urlpatterns = [
path('blogspot/',views.PostList.as_view(), name="b"),
path('<slug:slug>/',views.PostDetail.as_view(), name="post_detail"),
]
views.py
from django.views import generic
from .models import Post
# Create your views here.
class PostList(generic.ListView):
queryset = Post.objects.filter(status=1).order_by('-created_on')
template_name = 'blog/index.html'
class PostDetail(generic.DetailView):
model = Post
template_name = 'blog/post_detail.html'

Scrapy Playwright: execute CrawlSpider using scrapy playwright

Is it possible to execute CrawlSpider using Playwright integration for Scrapy? I am trying the following script to execute a CrawlSpider but it does not scrape anything. It also does not show any error!
import scrapy
from scrapy.linkextractors import LinkExtractor
from scrapy.spiders import CrawlSpider, Rule
class GumtreeCrawlSpider(CrawlSpider):
name = 'gumtree_crawl'
allowed_domains = ['www.gumtree.com']
def start_requests(self):
yield scrapy.Request(
url='https://www.gumtree.com/property-for-sale/london/page',
meta={"playwright": True}
)
return super().start_requests()
rules = (
Rule(LinkExtractor(restrict_xpaths="//div[#class='grid-col-12']/ul[1]/li/article/a"), callback='parse_item', follow=False),
)
async def parse_item(self, response):
yield {
'Title': response.xpath("//div[#class='css-w50tn5 e1pt9h6u11']/h1/text()").get(),
'Price': response.xpath("//h3[#itemprop='price']/text()").get(),
'Add Posted': response.xpath("//dl[#class='css-16xsajr elf7h8q4'][1]/dd/text()").get(),
'Links': response.url
}
Requests extracted from the rule do not have the playwright=True meta key, that's a problem if they need to be rendered by the browser to have useful content. You could solve that by using Rule.process_request, something like:
def set_playwright_true(request, response):
request.meta["playwright"] = True
return request
class MyCrawlSpider(CrawlSpider):
...
rules = (
Rule(LinkExtractor(...), callback='parse_item', follow=False, process_request=set_playwright_true),
)
Update after comment
Make sure your URL is correct, I get no results for that particular one (remove /page?).
Bring back your start_requests method, seems like the first page also needs to be downloaded using the browser
Unless marked explicitly (e.g. #classmethod, #staticmethod) Python instance methods receive the calling object as implicit first argument. The convention is to call this self (e.g. def set_playwright_true(self, request, response)). However, if you do this, you will need to change the way you create the rule, either:
Rule(..., process_request=self.set_playwright_true)
Rule(..., process_request="set_playwright_true")
From the docs: "process_request is a callable (or a string, in which case a method from the spider object with that name will be used)"
My original example defines the processing function outside of the spider, so it's not an instance method.
As suggested by elacuesta, I'd only add change your "parse_item" def from an async to a standard def.
def parse_item(self, response):
It defies what all I've read too, but that got me through.

Question on How # and # String Trigger Works in Odoo Chatter?

Hope you guys doin well,
I'm curious about how can a certain string like # and # can trigger a popup of a user and channels in Odoo Chatter & Discuss. This chatter has mail.thread Models related to it but i can't seem to understand how is it possible to create my own custom trigger in chatter?
Is it belong to certain views and not in models?
Any help will be appreciated!
Those are suggestion delimiters for the models used to update the suggestion list.
const suggestionDelimiters = ['#', ':', '#', '/'];
For example # is used to fetch partners (mail.partner model) matching a given search term. The _updateSuggestionList function will search the suggestions, sort them then will show (update) the popup list
To add a new custom trigger, you need add the delimiter to the suggestionDelimiters list and alter the _computeSuggestionModelName function to return the related model, the model must be defined like the mail.partner model.
If you want to patch an existing model, check the following example (taken from the hr module):
/** #odoo-module **/
import {
registerInstancePatchModel,
registerFieldPatchModel,
} from '#mail/model/model_core';
import { attr, one2one } from '#mail/model/model_field';
// Patch model
registerInstancePatchModel('mail.partner', 'hr/static/src/models/partner/partner.js', {
async checkIsEmployee() {
await this.async(() => this.messaging.models['hr.employee'].performRpcSearchRead({
context: { active_test: false },
domain: [['user_partner_id', '=', this.id]],
fields: ['user_id', 'user_partner_id'],
}));
this.update({ hasCheckedEmployee: true });
},
});
// Patch fields
registerFieldPatchModel('mail.partner', 'hr/static/src/models/partner/partner.js', {
hasCheckedEmployee: attr({
default: false,
}),
});
There is another way, and that is using the / or "command" popup. You can add your own item in the popup list and trigger any actions when a user selects your item from the popup.
Inherit from mail.channel
class MailChannel(models.Model):
_inherit = 'mail.channel'
Add a new method that starts with _define_command_XXXXX. This registers the item in the popup.
def _define_command_sample(self):
return {'help': _('Here is some sample help')}
Add a new method that starts with _execute_command_XXXXX. This method is executed when the user uses your command.
def _execute_command_sample(self, **kwargs):
# Send a "temporary" message to the user
self._send_transient_message(self.env.user.partner_id, f"Hello! You just successfully used the /sample command. You typed {kwargs['body']}.")
Reference: Github where Odoo defines the /lead command
PS: The above is for Odoo V12.0 - V14.0. Odoo V15.0 works a bit different, but you can check this and this for how to do it.

Am new to cucumber. I am running two feature files. While running it shows an error. If am running the first tag only it runs fine

#CucumberOptions(features = { "src\\test\\java\\com\\Features\\" }, glue = { "stepDefinitions" }, plugin = {
"pretty", "json:target/cucumber.json" }, tags = { "#Login","#baseCheck"}, monochrome = true)
Please help me solve this issue.
Error : None of the features at [src\test\java\com\Features\] matched the filters: [#Login, #baseCheck]
For this scenario Runner checks for feature which contains two tags "Login" and "baseCheck", however in your case one feature file contains tag as "Login" and other feature file contains tag as "baseCheck". Hence it treats as no feature exist with two tags and shows error as 'No feature' exist.
One quick fix is you have to add tags in testrunner as tags= {"#login,#basecheck"}
you specified each tag name in double quote, try this tag={ "#Login,#baseCheck"}
Yes, We need to define Cucumber setting as below.
import org.junit.runner.RunWith;
import cucumber.api.CucumberOptions;
import cucumber.api.junit.Cucumber;
#RunWith(Cucumber.class)
#CucumberOptions(
features = {"src/test/resources"},
glue={"classpath:gradle/cucumber"},
format= {"pretty","html:test-outout"},
tags = {"#SmokeTests,#RegressionTest"}
)
public class TestRunner {
}
You can also used tags like this = { "#Login","#baseCheck"},
just write #baseCheck below Feature: and above Scenario: otherwise it will take tag as feature and throw exception "None of the features at [src\test\java\com\Features] matched the filters: [#Login, #baseCheck]"
For example:-
Feature: My Feature File
#baseCheck
Scenario: My scenerio
Given first
Then second
Then Third

I am having trouble with web2py routes.example.py

Hi I would like to ask a question about routes.example.py
My app is called "HelloWorld"
If I use following URL
http://127.0.0.1:8000/helloWorld/default/index
The user is guided to the main page.
I am trying to figure out handling errors.
For example If I have a following URL
http://127.0.0.1:8000/helloWorld/default/index11
I have to handle the error.
Based on my research, I know that I need to work on "routes.example.py"
The following is my work in routes.example.py
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
from fileutils import abspath
from languages import read_possible_languages
possible_languages = read_possible_languages(abspath('applications', app))
routers = {
app: dict(
default_language = possible_languages['default'][0],
languages = [lang for lang in possible_languages
if lang != 'default']
)
}
*** above part is given by the web2py***
\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\
default_application = "HelloWorld"
default_controller = "default"
default_function = "index"
routes_onerror = [
('HelloWorld/400', '/HelloWorld/default/login'),
('HelloWorld/*', '/HelloWorld/static/fail.html'),
('*/404', '/HelloWorld/static/cantfind.html'),
('*/*', '/HelloWorld/error/index')
]
I define the default application, default controller and default fuction
Bases on these, I define the error cases in routes_onerror...
Can you tell me that what I am missing?