I have one form in forms.py
class EmailForm(forms.Form):
recipient = forms.CharField(max_length=14, min_length=12,
widget=forms.TextInput(attrs=require))
message = forms.CharField(max_length=140, min_length=1,
widget=forms.Textarea(attrs={'cols': 30, 'rows': 5}))
and my site url is
admin.autodiscover()
urlpatterns = patterns('', (r'^admin/(.*)',
include(admin.site.urls)),)
now I want it to be shown on admin interface
I tried so far
First attempt
from myapps.forms import EmailForm
class EmailAdmin(admin.ModelAdmin):
form = EmailForm
did not work Exception Value:
'DeclarativeFieldsMetaclass' object is not iterable
Second attempt
and now I followed http://docs.djangoproject.com/en/dev/ref/contrib/admin/#django.contri...
but could not get help
class EmailAdmin(admin.ModelAdmin):
def my_view(self,request):
return admin_my_view(request,self)
def get_urls(self):
urls = super(SmsAdmin, self).get_urls()
my_urls = patterns('',(r'^my_view/
$',self.admin_site.admin_view(self.my_view)))
return my_urls + urls
def admin_my_view(request, model_admin):
opts = model_admin.model._meta
admin_site = model_admin.admin_site
has_perm = request.user.has_perm(opts.app_label \
+ '.' + opts.get_change_permission())
context = {'admin_site': admin_site.name,
'title': "My Custom View",
'opts': opts,
'root_path': '/%s' % admin_site.root_path,
'app_label': opts.app_label,
'has_change_permission': has_perm}
template = 'admin/demo_app/admin_my_view.html'
return render_to_response(template,
context,context_instance=RequestContext(request))
admin.site.register(EmailForm,EmailAdmin)
and when I run server and type on browser localhost:8000/admin
and hit enter button
Exception Value:
'DeclarativeFieldsMetaclass' object is not iterable
and second time just after first time when I again enter then it show
me the admin page but I can't see my EmailAdmin in admin interface..
Just help me or suggest me any link.
Thanks
(This is my attempt at reformatting your model code):
class EmailForm(forms.Form):
recipient = forms.CharField(max_length=14, min_length=12,
widget=forms.TextInput(attrs=require))
message = forms.CharField(max_length=140, min_length=1,
widget=forms.Textarea(attrs={'cols': 30, 'rows': 5}))
I would put my money on the bit that says "attrs=require" -- if that's not a typo.
What you want instead is something like this:
recipient = forms.CharField(max_length=14, min_length=12,
widget=forms.TextInput(), required=True)
Related
I am working on the project the application is working fine
but small issue with list box,
I created a class where we can call get suggestion from the entry data a sample code is given below
from tkinter import *
root = Tk()
root.geometry('300x300')
search = StringVar()
search1 = StringVar()
search_list = ["Apple", "Ball", "cat", "dog"]
Label(root, text="Search :").pack(pady=15)
search1_ent = Entry(root, textvariable=search)
search1_ent.pack(pady=15)
search2_ent = Entry(root, textvariable=search1)
search2_ent.pack(pady=15)
list_box = Listbox(root, height=10, width=20)
EntryList.EntryBoxListLink(search_list, list_box, search1_ent, search, 90, 87, 20)
root.mainloop()
I created a py file on the name Entry list in that created a class Entry box list link,
It may not be perfect code but worked fine.
the class code is
import contextlib
from tkinter import *
class EntryBoxListLink:
"""this class is created to link entry box and the listbox"""
def __init__(self, list_data='', list_box='', entry_box=None, set_variable='', x_axis=38, y_axis=52, width=20,
next_entry=None):
self.list_data = list_data
self.list_box = list_box
self.entry_box = entry_box
self.set_variable = set_variable
self.x_axis = x_axis
self.y_axis = y_axis
self.width = width
def destroyListBox(event):
"""this is the command when the list box to place forget"""
with contextlib.suppress(BaseException):
self.list_box.place_forget()
def searchIList(event):
"""this gives the list box where the data no are aligned"""
self.list_box.config(width=self.width)
self.list_box.place(x=self.x_axis, y=self.y_axis)
self.list_box.bind('<Leave>', destroyListBox)
self.list_box.bind('<Double-1>', itemsSelected)
self.list_box.bind('<Return>', itemsSelected)
if self.list_data is not None:
match = [i for i in self.list_data if
(self.set_variable.get().lower() or self.set_variable.get().capitalize()) in i]
self.list_box.delete(0, END)
for c in match:
try:
self.list_box.insert(END, c.title())
except BaseException:
self.list_box.insert(END, c)
if not match:
destroyListBox(None)
if self.set_variable.get() == "":
destroyListBox(None)
def itemsSelected(event):
"""when the no is selected from list box it aligned to
the phone number and gives the data"""
for i in self.list_box.curselection():
self.set_variable.set(self.list_box.get(i))
self.entry_box.focus_set()
destroyListBox(None)
if next_entry is not None:
next_entry.focus()
def set_entry_focus(event):
if list_box.curselection()[0] == 0:
return self.entry_box.focus_set()
def focusAndSelect():
self.list_box.focus_set()
self.list_box.select_set(0)
self.entry_box.bind("<KeyRelease>", searchIList)
self.entry_box.bind("<Down>", lambda event: focusAndSelect())
self.list_box.bind("<Up>", set_entry_focus)
the issue is when I select the second entry box the list box should be gone,
to be more frank when the search1 and listbox are not in focus the list box should be place forget!
I am trying to pass additional information to the parse function but it is giving a type error.
TypeError: parse() got an unexpected keyword argument 'body'
i am unable to resolve this issue.
"""
return [scrapy.Request(url=website.search_url.format(prod), callback=self.parse,
cb_kwargs = {"body":website.body_xpath,"product_list":website.products_list_xpath,
"names":website.products_name_xpath,"selling_price":website.selling_price_xpath,
"market_price":website.market_price_xpath}) for website in websites for prod in modified_products]
def parse(self, response):
body = response.cb_kwargs.get("body")
product_list = response.cb_kwargs.get("product_list")
name = response.cb_kwargs.get("names")
selling_price = response.cb_kwargs.get("selling_price")
market_price = response.cb_kwargs.get("market_price")
"""
I forgot to write those names in parse function definition, after adding them i am getting the correct result. Thanks for having a look at it.
"""
return [scrapy.Request(url=website.search_url.format(prod), callback=self.parse,
cb_kwargs = dict(body = website.body_xpath, product_list = website.products_list_xpath,
name = website.products_name_xpath, selling_price = website.selling_price_xpath,
market_price = website.market_price_xpath)) for website in websites for prod in modified_products]
def parse(self, response, body, product_list, name, selling_price, market_price):
body = response.cb_kwargs["body"]
product_list = response.cb_kwargs["product_list"]
name_ = response.cb_kwargs["name"]
selling_price_ = response.cb_kwargs["selling_price"]
market_price_ = response.cb_kwargs["market_price"]
"""
Is there any way to print more than one report by one click in Odoo 10? For example i have one report template and some employees. Each employee should has own report with same template. And i want to print all report by one button.
I created template and python file. But could not print for each employee. Can you help me please?
you must have to extend qweb report like this
class orders_print(report_sxw.rml_parse):
def __init__(self, cr, uid, name, context):
super(orders_print,self).__init__(cr,uid, name, context=context)
class SaleOrderReport(models.AbstractModel):
_name = 'report.sale.report_saleorder'
_inherit = 'report.abstract_report'
_template = 'sale.report_saleorder'
_wrapped_report_class = orders_print
#api.multi
def render_html(self, docids,data=None,context=None):
report_obj = self.env['report']
report = report_obj._get_report_from_name('sale.report_saleorder')
if data['data']:
d = ast.literal_eval(data['data']['options'])
docs = self.env[report.model].browse(d['ids'])
docargs = {
'doc_ids': self._ids,
'doc_model': 'sale.order',
'docs': docs,
}
return report_obj.render('sale.report_saleorder', docargs)
else:
return super(SaleOrderReport,self).render_html(docids,data=data)
Following is the code. Basically, I am scraping movie info. from IMDB.com. But somehow the Request doesn't scrap the url, which is in the object "addr". The "print" I put into the parse_item2 simply does not show up.
This drives me crazy. I spent hours on it. Could anyone with some experience help? Thank you so much.
# code for the spider
from scrapy.contrib.spiders import CrawlSpider, Rule
from scrapy.contrib.linkextractors.sgml import SgmlLinkExtractor
from scrapy.selector import Selector
from scrapy.http import Request, Response
from beta.items import BetaItem
import urllib2
class AlphaSpider(CrawlSpider):
name = 'alpha'
allowed_domains = ['amazon.com','imdb.com']
start_urls = ['http://www.imdb.com/search/title?at=0&sort=boxoffice_gross_us&title_type=feature&year=2005,2005']
rules = (Rule(SgmlLinkExtractor(restrict_xpaths=('//td/a',), allow=('/title/')), callback='parse_item1'),
)
def parse_item1(self, response):
sel = Selector(response)
item = BetaItem()
idb = sel.xpath('//link[#rel="canonical"]/#href').extract()
idb = idb[0].split('/')[-2]
item['idb'] = idb
title = sel.xpath('//h1[#class="header"]/span[#class="itemprop"]/text()').extract()
item['title'] = title
addr = 'http://www.imdb.com/title/' + idb + '/business'
request = Request(addr, callback=self.parse_item2)
request.meta['item'] = item
return request
def parse_item2(self, response):
print 'I am here'
item = response.meta['item']
sel = Selector(response)
# BLA BLA BLA
return item
The reason for the problem is indeed as Blender said in his comment above. It takes quite some time to crawl stuff for some particular request.
I've been scouring the internet for a couple days and couldn't find anything, so I'm hoping you guys can point me in the right direction. I'm trying to customize the django admin so that a button appears inline after a URL field. The button appears, and the javascript works, except despite marking it null=True and blank=True the admin validation keeps saying the field is required; I want the url field to be optional.
Is there any way to make this field optional? I'm assuming it's some combination of blank=True and null=True, but I've tried it in a handful of places with no luck.
Here are what I think to be the relevant code bits (also, I know inline CSS from the widget is a bad idea. It's only until I get everything working!). If you need to see anything else, please let me know.
models.py
class Team(models.Model):
name = models.CharField(max_length=64)
name_color = models.CharField(max_length=7, default='#000000')
name_shadow_color = models.CharField(max_length=7, default='#ffffff')
created = models.DateField(editable=True, default=datetime.now)
retired = models.DateField(null=True, blank=True)
url = models.URLField(null=True, blank=True, default=None)
admin.py
class TeamAdmin(admin.ModelAdmin):
list_filter = ('created', 'retired',)
list_select_related = True
list_display = ('name', 'created',)
search_fields = ('name', )
ordering = ('name',)
form = TeamAdminForm
admin_forms.py
class TeamAdminForm(forms.ModelForm):
url = URLActionField()
class Media:
js = ('js/jquery-1.8.0.min.js', 'js/admin/teamform.js', )
class Meta:
model = Team
admin_widgets.py
class URLActionField(forms.TextInput):
def render(self, name, value, attrs=None):
if attrs is None:
attrs = {}
# TODO: not responsive!!
if 'style' not in attrs.keys():
attrs['style'] = 'width: 275px;'
else:
attrs['style'] = '%s width: 275px;' % attrs['style']
attrs['required'] = False
attrs['blank'] = True
attrs['null'] = True
output = []
output.append(super(URLActionField, self).render(name, value, attrs))
output.append(' <input type="button" value="%s" style="width: 200px; margin-left: 20px; height: 24px; line-height: 15px;" class="grp-button" id="url-scraper">' % unicode(_(u'Scrape URL for data')))
return mark_safe(u''.join(output))
Thanks in advance.
You need to make a custom widget and use it with the build-in URL field. You are dealing with a formfield and not a modelfield. So use 'required=False'. Avoid using null on string-based fields unless you have an excellent reason. If a string-based field has null=True, that means it has two possible values for “no data”: NULL, and the empty string.
In Model.py:
class Team(models.Model):
...
url = models.URLField(blank=True)
In Admin.py append to the build-in AdminURLFieldWidget output (no js required):
from django.contrib.admin.widgets import AdminURLFieldWidget
class CustomAdminURLFieldWidget(AdminURLFieldWidget):
def render(self, name, value, attrs=None):
output = []
output.append(super(CustomAdminURLFieldWidget,
self).render(name, value, attrs))
if value:
output.append('<p>%s</p>' %(value, value))
return mark_safe(u''.join(output))
In Admin.py create a form:
from models import Team
class TeamAdminForm(forms.ModelForm):
url = forms.URLField(required=False, widget=CustomAdminURLFieldWidget)
class Meta:
model = Team
In Admin.py create a ModelAdmin:
class TeamAdmin(admin.ModelAdmin):
form = TeamAdminForm