NameError: name 'RandomCharField' is not defined - django-extensions

from django_extensions.db.fields import RandomCharField
class Product(models.Model):
stock = RandomCharField(length=4, include_alpha=False)
NameError: name 'RandomCharField' is not defined
How to fix it?

Related

ValidationError when using pydantic Field

I run these codes by defining two classes, Blackboard and Table, based on BaseModel. The I defined another class which takes two attributes: bloackboard, defined to be a Blackboard; tables, defined to be a list of Table class objects.
from typing import List
from pydantic import BaseModel, Field
class Blackboard(BaseModel):
size = 4000
color: str = Field(..., alias='yanse',
description='the color of the blackboard, you can choose green or black.')
class Table(BaseModel):
position: str
class ClassRoom(BaseModel):
blackboard: Blackboard
tables: List[Table]
m = ClassRoom(
blackboard={'color': 'green'},
tables=[{'position': 'first row, left 1'}, {'position': 'first row, left 2'}]
)
I got an error :
File "pydantic\main.py", line 342, in pydantic.main.BaseModel.__init__
pydantic.error_wrappers.ValidationError: 1 validation error for ClassRoom
blackboard -> yanse
field required (type=value_error.missing)
I want to know how could I correctly use Field class.
Thanks
I expect to have no error.
You are using an alias for the color field in your schema and filling your data with python dictionaries.
in this case, you should replace:
blackboard={'color': 'green'}
with:
blackboard={'yanse': 'green'}
The color field is used when you have a python schema object, not in dictionaries.
In case you wanted to populate your Blackboard model using color, you can activate allow_population_by_field_name option in the Blackboard config options as follow:
class Blackboard(BaseModel):
size = 4000
color: str = Field(..., alias='yanse',
description='the color of the blackboard,
you can choose green or black.')
class Config:
allow_population_by_field_name = True

Trying to access R class methods and fields within Python using rpy2

I am using rpy2 to import a library from CRAN repository called "MatrixEQTL" to run in within Python using importr, here is my attempt:
import rpy2.robjects as robjects
from rpy2.robjects.packages import importr
robjects.r('install.packages("MatrixEQTL")')
mtrql = importr('MatrixEQTL')
I am trying to access both class fields as well as class methods but I failed here is what the class looks like when printing into the python shell:
# to view class SlicedData of MatrixEQTL R package
print(mtrql.SlicedData)
Generator for class "SlicedData":
Class fields:
Name: dataEnv nSlices1 rowNameSlices
Class: environment numeric list
Name: columnNames fileDelimiter fileSkipColumns
Class: character character numeric
Name: fileSkipRows fileSliceSize fileOmitCharacters
Class: numeric numeric character
Class Methods:
"Clear", "show#envRefClass", "nSlices", "getRefClass", "export",
"initialize", "CombineInOneSlice", "callSuper", "initFields", "nCols",
"getClass", "RowStandardizeCentered", "import", "SaveFile", "RowReorder",
"setSlice", "getSlice", "RowReorderSimple", "CreateFromMatrix", "nRows",
"ResliceCombined", "LoadFile", "ColumnSubsample", "SetNanRowMean",
"setSliceRaw", "getSliceRaw", "copy", "RowMatrixMultiply", "usingMethods",
"GetAllRowNames", "RowRemoveZeroEps", "field", ".objectParent",
"IsCombined", "untrace", "trace", "Clone", "GetNRowsInSlice",
".objectPackage", "show", "FindRow"
Reference Superclasses:
"envRefClass"
I want to access for instance class field say fileDelimiter and also class Methods say LoadFile but I couldn't, here is also my attempt to access class method LoadFile and the error message that generated:
# If I try to run this without "()"
data = mtrql.SlicedData
load_my_file = data.LoadFile(file)
data = data.LoadFile(file)
AttributeError: 'DocumentedSTFunction' object has no attribute 'LoadFile'
# And that's my attempt for when adding "()" to the class name
data = mtrql.SlicedData
load_my_file = data.LoadFile(file)
data = data.LoadFile(file)
AttributeError: 'RS4' object has no attribute 'LoadFile'
I tried to look for a solution to this issue but I wasn't successful, please help me understand and solve this issue.
Thank you so much in advance.
mtrql.SlicedData is a "Generator", that is a constructor. In R that means a function (that will return an instance of the class), which is why mtrql.SlicedData is an R function with rpy2.
Consider the following example from the R documentation (https://rdrr.io/r/methods/Introduction.html):
import rpy2.robjects as ro
Pos = ro.r("""
setClass("Pos", slots = c(latitude = "numeric", longitude = "numeric",
altitude = "numeric"))
""")
With rpy2, the object Pos is an R function:
>>> type(Pos)
rpy2.robjects.functions.SignatureTranslatedFunction
However that function object has an S3 class in R (there are several OOP systems in R, 2 of them coexisting in standard R unfortunately).
>>> tuple(Pos.rclass)
('classGeneratorFunction',)
A specific print function is implemented for this S3 class, and it will use the attributes package and className for the object (the R function-that-is-in-fact-a-Generator) to display all the info about the clas you are seeing.
Since this is a constructor, to create an instance you can do:
pos = Pos()
or
pos = Pos(latitude=0, longitude=0, altitude=-10)
The instance will have instance attributes (and methods)
>>> tuple(pos.list_attrs())
('latitude', 'longitude', 'altitude', 'class')
>>> tuple(pos.do_slot('altitude'))
(-10,)
With your specific example, you probably want something like:
slidata = mtrql.SlicedData()
slidata.do_slot('LoadFile')(file)
The documentation can provide more information about R S4 classes in rpy2, and how to make wrapper classes in Python that map attributes and methods.
https://rpy2.github.io/doc/v3.3.x/html/robjects_oop.html#s4-objects

AttributeError: 'NoneType' object has no attribute 'text' in web-scraping

I'm trying to recreate the web scraping on this website
https://medium.freecodecamp.org/how-to-scrape-websites-with-python-and-beautifulsoup-5946935d93fe
I'm working in jupyter as a first project and I've come up with this error
AttributeError: 'NoneType' object has no attribute 'text'
I've tried changing the link but it makes no difference. I don't really know enough to do anything about the problem. Here is all the code so far...
#import the libraries
import urllib.request
from bs4 import BeautifulSoup
# specify the url
quote_page = "https://www.bloomberg.com/quote/SP1:IND"
page = urllib.request.urlopen(quote_page)
# parse the html using BeautifulSoup and store in variable `soup`
soup = BeautifulSoup(page, "html.parser")
# Take out the <div> of name and get its value
name_box = soup.find("h1", attrs={"class": "name"})
name = name_box.text.strip()
# strip() is used to remove starting and trailing
print (name)
# get the index price
price_box = soup.find("div", attrs={"class":"price"})
price = price_box.text.strip()
print (price)
Any help would be appreciated a lot
I use selenium to webscrape, but I am sure I can help you out (maybe).
This section is were you code gives you the error I assume:
price_box = soup.find("div", attrs={"class":"price"})
price = price_box.text.strip()
print (price)
What I would do is:
price_box = soup.find("div", attrs={"class":"price"})
price = price_box().text
print (price.text)

“guiWidgetsToolkittcltk” is not a defined class

I want to create GUI using gWidget in R but I am getting all these kind of weird errors:
guitoolkit = new("guiWidgetsToolkittcltk")
Error in getClass(Class, where = topenv(parent.frame())) :
“guiWidgetsToolkittcltk” is not a defined class
or:
> setIs("guiWidget","guiWidgetORgWidgetTcltkORtcltk")
Error in .walkClassGraph(classDef, "subclasses", where) :
the 'subClass' list for class “guiWidgetORgWidgetTcltkORtcltk”, includes an undefined class “guiWidget”
Any idea what I am missing?

How can I use zope.schema to group portal types into categories?

I need to create a Plone configlet that delivers this kind of structure:
types = {
'News articles': ['NewsMediaType', 'News Item'],
'Images': ['Image'],
'Pages': ['Page']
}
I made a prototype to show what I was thinking to have in the form:
So I need to group some portal_types together and let the user assign a name for this group. How can I do that? Any ideas?
edited:
I made a great progress with the problem, but when save the form, validation give me an error
# -*- coding: utf-8 -*-
from plone.theme.interfaces import IDefaultPloneLayer
from z3c.form import interfaces
from zope import schema
from zope.interface import Interface
from plone.registry.field import PersistentField
class IThemeSpecific(IDefaultPloneLayer):
""" """
class PersistentObject(PersistentField, schema.Object):
pass
class IAjaxsearchGroup(Interface):
"""Global akismet settings. This describes records stored in the
configuration registry and obtainable via plone.registry.
"""
group_name = schema.TextLine(title=u"Group Name",
description=u"Name for the group",
required=False,
default=u'',)
group_types = schema.List(title=u"Portal Types",
description=u"Portal Types to search in this group",
value_type =schema.Choice(
title=u"Portal Types",
vocabulary=u"plone.app.vocabularies.ReallyUserFriendlyTypes",
required=False,
),
required=False,)
class IAjaxsearchSettings(Interface):
"""Global akismet settings. This describes records stored in the
configuration registry and obtainable via plone.registry.
"""
group_info = schema.Tuple(title=u"Group Info",
description=u"Informations of the group",
value_type=PersistentObject(IAjaxsearchGroup, required=False),
required=False,)
-
from plone.app.registry.browser import controlpanel
from collective.ajaxsearch.interfaces.interfaces import IAjaxsearchSettings
from collective.ajaxsearch.interfaces.interfaces import IAjaxsearchGroup
from z3c.form.object import registerFactoryAdapter
class AjaxsearchSettingsEditForm(controlpanel.RegistryEditForm):
schema = IAjaxsearchSettings
label = u"Ajaxsearch settings"
description = u""""""
def updateFields(self):
super(AjaxsearchSettingsEditForm, self).updateFields()
def updateWidgets(self):
super(AjaxsearchSettingsEditForm, self).updateWidgets()
class AjaxsearchSettingsControlPanel(controlpanel.ControlPanelFormWrapper):
form = AjaxsearchSettingsEditForm
That's a CRUD (create-read-update-delete) pattern.
The plone.z3cform package has specific support for just such forms. Define a schema for a types group:
class IAJAXTypesGroup(interface):
name = ...
types = ...
then use a CRUD form:
from plone.z3cform.crud import crud
class AJAXGroupsCRUDForm(crud.CrudForm):
update_schema = IAJAXTypesGroup
def get_items(self):
# return a sequence of (id, IAJAXTypesGroup-implementer) tuples
return self.context.getGroups()
def add(self, data):
# return a new IAJAXTypesGroup implementer; a IObjectCreatedEvent is generated
# alternatively, raise zope.schema.ValidationError
id = self.context.createGroup(**data)
return self.context.getGroup(id)
def remove(self, (id, item)):
# Remove this specific entry from your list
self.context.deleteGroup(id)
Groups need to have an id, items are shown in the order that get_items() returns them.
I created the class for factory
class AjaxsearchGroup(object):
"""
group of config
"""
zope.interface.implements(IAjaxsearchGroup)
registerFactoryAdapter(IAjaxsearchGroup, AjaxsearchGroup)
To use the settings
# get groups config
registry = queryUtility(IRegistry)
settings = registry.forInterface(IAjaxsearchSettings, check=False)
for config in settings.group_info:
types[config.group_name] = config.group_types
Thank you a lot!

Resources