everybody
I'm trying to make an edit form for an object other than the context. It's a dictionary stored in the session. I'm following Martin Aspeli Schema Drive Forms. It should be easy, but for some reason, the edit form doesn't load any data. Maybe I'm losing some simple detail, but I can't find it. I made ignoreContext=True and tried returning a dictionary and after that an instance that implements the schema, but it didn't work.
from plone.directives import form, dexterity
from zope.interface import invariant, Invalid, implements
class IUser(form.Schema):
'''Represents an user'''
uid = schema.TextLine(
title = _(u'Login'),
)
gn = schema.TextLine(
title = _(u'Name'),
)
sn = schema.TextLine(
title = _(u'Surname'),
)
uniqueIdentifier = schema.TextLine(
title = _(u'Identifier'),
description = _(u'Ej. V11222333'),
)
accClass = schema.TextLine(
title = _(u'User class'),
)
dateExpiration = schema.TextLine(
title = _(u'Date of expiration'),
)
class User:
implements(IUser)
def __init__(self, **kargs):
self.uid = kargs['uid']
self.gn = kargs['givenName']
self.sn = kargs['sn']
self.uniqueIdentifier = kargs['uniqueIdentifier']
self.accClass = kargs['accClass']
self.dateExpiration = kargs.get('dateExpiration', '2015/06')
class Edit(form.SchemaEditForm):
'''Modify User'''
grok.context(IUserManager) # It's ok. This is a view of an IUserManager object
grok.require('zope2.View') # <- just for testing
grok.name('modify')
schema = IUser
ignoreContext = True
label = 'Modify an User'
def getContent(self):
# I've tried returning a dictionary too, but it's useless
user = User(**SessionUsers(self.context).current())
return user
Related
I have the below model for a my dynamodb table using pynamodb :
from pynamodb.models import Model
from pynamodb.attributes import (
UnicodeAttribute, UTCDateTimeAttribute, UnicodeSetAttribute, BooleanAttribute
)
class Reminders(Model):
"""Model class for the Reminders table."""
# Information on global secondary index for the table
# user_id (hash key) + reminder_id+reminder_title(sort key)
class Meta:
table_name = 'Reminders'
region = 'eu-central-1'
reminder_id = UnicodeAttribute(hash_key=True)
user_id = UnicodeAttribute(range_key=True)
reminder_title = UnicodeAttribute()
reminder_tags = UnicodeSetAttribute()
reminder_description = UnicodeAttribute()
reminder_frequency = UnicodeAttribute(default='Only once')
reminder_tasks = UnicodeSetAttribute(default=set())
reminder_expiration_date_time = UTCDateTimeAttribute(null=True)
reminder_title_reminder_id = UnicodeAttribute()
next_reminder_date_time = UTCDateTimeAttribute()
should_expire = BooleanAttribute()
When i want to create a new reminder i do it through the below code :
class DynamoBackend:
#staticmethod
def create_a_new_reminder(new_reminder: NewReminder) -> Dict[str, Any]:
"""Create a new reminder using pynamodb."""
new_reminder = models.Reminders(**new_reminder.dict())
return new_reminder.save()
In this case the NewReminder is an instance of pydantic base model like so :
class NewReminder(pydantic.BaseModel):
reminder_id: str
user_id: str
reminder_title: str
reminder_description: str
reminder_tags: Sequence[str]
reminder_frequency: str
should_expire: bool
reminder_expiration_date_time: Optional[datetime.datetime]
next_reminder_date_time: datetime.datetime
reminder_title_reminder_id: str
when i call the save method on the model object i receive the below response:
{
"ConsumedCapacity": {
"CapacityUnits": 2.0,
"TableName": "Reminders"
}
}
Now my question is the save method is directly being called by a lambda function which is in turn called by an API Gateway POST endpoint so ideally the response should be a 201 created and instead of returning the consumed capacity and table name , would be great if it returns the item inserted in the database. Below is my route code :
def create_a_new_reminder():
"""Creates a new reminder in the database."""
request_context = app.current_request.context
request_body = json.loads(app.current_request.raw_body.decode())
request_body["reminder_frequency"] = data_structures.ReminderFrequency[request_body["reminder_frequency"]]
reminder_details = data_structures.ReminderDetailsFromRequest.parse_obj(request_body)
user_details = data_structures.UserDetails(
user_name=request_context["authorizer"]["claims"]["cognito:username"],
user_email=request_context["authorizer"]["claims"]["email"]
)
reminder_id = str(uuid.uuid1())
new_reminder = data_structures.NewReminder(
reminder_id=reminder_id,
user_id=user_details.user_name,
reminder_title=reminder_details.reminder_title,
reminder_description=reminder_details.reminder_description,
reminder_tags=reminder_details.reminder_tags,
reminder_frequency=reminder_details.reminder_frequency.value[0],
should_expire=reminder_details.should_expire,
reminder_expiration_date_time=reminder_details.reminder_expiration_date_time,
next_reminder_date_time=reminder_details.next_reminder_date_time,
reminder_title_reminder_id=f"{reminder_details.reminder_title}-{reminder_id}"
)
return DynamoBackend.create_a_new_reminder(new_reminder=new_reminder)
I am very new to REST API creation and best practices so would be great if someone would guide me here . Thanks in advance !
I m trying to perform a little calculation and Logic on date.time with Flask application.
1.) the application will calculate the difference between issue date and expiry date called "remaining days" , The application will check if remaining days is less than 365 days and trigger a function
I attempted the first logic to manipulate the data and submit to database
`#bp.route('/cerpacs/add', methods=['GET', 'POST'])
#login_required
def add_cerpac():
"""
Add a an Cerpac/ expartriates to the database
"""
check_admin()
add_cerpac = True
form =CerpacForm()
if form.validate_on_submit():
cerpac = Cerpac(cerpac_serial_no=form.cerpac_serial_no.data,
cerpac_issue_date= form.cerpac_issue_date.data,
cerpac_exp_date=form.cerpac_exp_date.data,
employee =form.employee.data, )
form.cerpac_issue_date.data = cerpac.cerpac_issue_date
form.cerpac_exp_date.data = cerpac.cerpac_exp_date
if request.method == 'POST':
todays_date = datetime.now()
t = cerpac.cerpac_issue_date
t1 = cerpac.cerpac_exp_date
remaining_days = t1 - t
print(remaining_days) - good prints my result!
remaining_days = cerpac.remaining_days ----not adding to database
try:
add cerpac to the database
db.session.add(cerpac)
db.session.commit()
flash('You have successfully added a Cerpac.' )`
`
my model:
class Cerpac(db.Model):
__tablename__ = 'cerpacs'
id = db.Column(db.Integer, primary_key=True)
cerpac_issue_date = db.Column(db.DateTime)
cerpac_exp_date=db.Column(db.DateTime)
remaining_days = db.Column(db.DateTime)
cerpac_serial_no = db.Column(db.String(60))
cerpac_upload = db.Column(db.String(20), default='cerpac.jpg')
renew_status = db.Column(db.Boolean, default=False)
process_status = db.Column(db.Boolean, default=False)
renewcerpac_id = db.Column(db.Integer, db.ForeignKey('renewcerpacs.id'))
employee_id = db.Column(db.Integer, db.ForeignKey('employees.id'))
def __repr__(self):
return '<Cerpac {}>'.format(self.name) model:
I want to add this to database and eventually write a function like this:
I had a mistake also in the code because I had error issue_date not defined. How do I define issue_date as a date.time variable?
def remaining_days(issue_date, expired_date):
issue_date = datetime(issue_date)
days_to_go = expired - issue
if days_to_go == 365:
renew_status== True
print("time to renew")
print("We are Ok")
I would simplify this to something like:
from datetime import datetime
class Cerpac(db.Model):
...
cerpac_exp_date=db.Column(db.DateTime)
...
#property
def remaining_days(self):
return (self.cerpac_exp_date - self.cerpac_issue_date).days
#property
def days_to_expiry(self):
return (self.cerpac_exp_date - datetime.now()).days
Then, days_to_expiry and remaining_days become properties calculated when you query, and update automatically when they renew their cards.
here is my code:
models.py
from django.db import models
class Country(models.Model):
country_name = models.CharField(max_length = 20, default = '', )
country_other_details = models.CharField(max_length = 100, default = '', null = True)
class Meta:
verbose_name_plural = "Countries"
def __str__(self):
return self.country_name
class State(models.Model):
in_country = models.ForeignKey(Country, related_name='in_country',on_delete=models.DO_NOTHING)
state_name = models.CharField(max_length = 20, default = '')
state_other_details = models.CharField(max_length=100, default = '', null = True)
def __str__(self):
return self.state_name
class City(models.Model):
in_state = models.ForeignKey(State, related_name='in_state',on_delete=models.DO_NOTHING)
city_name = models.CharField(max_length = 20, default = '')
city_other_details = models.CharField(max_length = 100, null = True)
class Meta:
verbose_name_plural = "Cities"
def __str__(self):
return self.city_name
forms.py
from django.forms.models import inlineformset_factory
from django.forms.models import BaseInlineFormSet
from .models import Country, State, City
from django.forms.models import BaseInlineFormSet, inlineformset_factory
from django.utils.translation import ugettext_lazy as _
# from publishing.utils.forms import is_empty_form, is_form_persisted
CityFormset = inlineformset_factory(State, City, extra=2, fields=("city_name",))
class BaseStateFormset(BaseInlineFormSet):
def add_fields(self, form, index):
super(BaseStateFormset, self).add_fields(form, index)
# save the formset in the 'nested' property
form.nested = CityFormset(
instance=form.instance,
data=form.data if form.is_bound else None,
files=form.files if form.is_bound else None,
prefix='address-%s-%s' % (
form.prefix,
CityFormset.get_default_prefix()),
# extra=1
)
def is_valid(self):
result = super(BaseStateFormset, self).is_valid()
if self.is_bound:
for form in self.forms:
if hasattr(form, 'nested'):
result = result and form.nested.is_valid()
return result
def save(self, commit=True):
result = super(BaseStateFormset, self).save(commit=commit)
for form in self.forms:
if hasattr(form, 'nested'):
if not self._should_delete_form(form):
form.nested.save(commit=commit)
return result
StateFormset = inlineformset_factory(Country, State, formset=BaseStateFormset, extra=2, fields=("state_name",))
views.py
from .models import Country, State, City
def manage_state(request, parent_id):
parent = get_object_or_404(Country, id=parent_id)
if request.method == 'POST':
formset = forms.StateFormset(request.POST, instance=parent)
if formset.is_valid():
formset.save()
# return redirect('parent_view', parent_id=parent.id)
return redirect(reverse('india:manage_state', kwargs={"parent_id": parent.id}))
else:
formset = forms.StateFormset(instance=parent)
return render(request, 'home.html', {
'parent':parent,
'children_formset':formset})
What i want is a single form that will create an object to Parent(Country) model and multiple object to Child(State) as according to country's object and multiple objects to Grand Child(City) according to corresponded State
for example:
<form method="POST">
Parentform:(Country)
<input name="country_name">
Childform:(State)
<input name="state_name">
GrandChildform:(City)
<input name = "City_name">
<button> Add GrandChild</button>
<button> Add Child </button>
<button>Add Parent</button>
</form>
also the add button should be able to add the more Countries, States and Cities dynamically to the form.
Any help, suggestions or references would be Grateful.
Thanks in Advance.
I got the solution. Thanks to PYTHON and Django.
As I got, We can edit our own admin using a built-in package django-nested-admin.
We don't require to built our Custom forms,views or anything.
I am Sharing Image of my Django-admin:
Image
To do it I am sharing the Descriptions:
First we install a package using pip:
pip install django-nested-admin.
Now we Add the library in settings.py:
INSTALLED_APPS[
...
'nested_admin',
...
]
Add the urls of the library in the urls.py:
url(r'^nested_admin/', include('nested_admin.urls')),
Register models in admin.py:
from django.contrib import admin
from .models import State, Country, City
from nested_admin import NestedModelAdmin, NestedStackedInline, NestedTabularInline
class CityTabularInline(NestedTabularInline):
model = City
extra = 1
class StateTabularInline(NestedTabularInline):
model = State
extra = 1
inlines = [CityTabularInline, ]
class CountryAdmin(NestedModelAdmin):
inlines = [StateTabularInline, ]
admin.site.register(Country, CountryAdmin)
Usage:
NestedModelAdmin: to extend the django ModelAdmin class and to be able to use differents
types of classes in the inlines attribute.
NestedStackedInline: to allow the addition of TabularInline classes in the inlines
attribute.
NestedTabularInline: to extend the TabularInline.
for more details please Visit.
I am trying to save a text file from the first page of a flatNotebook, write them to an EXTERNALLY defined sqLite database and write the values to a grid on the second page of the flatNotebook. The values are saved to the text file and written to the database successfully but I cannot get the values to populate the grid at the same time. They values show up in the grid after I close the program and restart it. I am having a hard time understanding how to call the function onAddCue(). I have tried so many things that I'm just confusing myself at this point. Please help me understand what I am doing wrong. Here is my entire code:
cue =[4,'NodeA',11,22,33,44,55,66,77,88,99]
class InitialInputs(scrolled.ScrolledPanel):
global cue
def __init__(self, parent, db):
scrolled.ScrolledPanel.__init__(self, parent, -1)
self.db = db
self.cur = self.db.con.cursor()
self.saveBtn = wx.Button(self, -1, "Save Current Values")
self.Bind(wx.EVT_BUTTON, self.onSave, self.saveBtn)
self.dirname = ""
def onSave(self, event):
global cue
dlg = wx.FileDialog(self, "Choose a file", self.dirname, "", "*.txt", wx.FD_SAVE | wx.FD_OVERWRITE_PROMPT)
if dlg.ShowModal() == wx.ID_OK:
itcontains = cue
self.filename=dlg.GetFilename()
self.dirname=dlg.GetDirectory()
filehandle=open(os.path.join(self.dirname, self.filename),'w')
filehandle.write(str(itcontains))
filehandle.close()
dlg.Destroy()
row = cue[0] - 1
InsertCell ="UPDATE CUES SET 'Send'=?,'RED'=?,'GREEN'=?,'BLUE'=?,'RGB_Alpha'=?,'HUE'=?,'SAT'=?,'BRightness'=?,'HSB_Alpha'=?,'Fade'=? WHERE DTIndex=%i" %row
self.cur.execute(InsertCell, cue[1:])
self.db.con.commit()
GridPanel().grid.onAddCue() #This is the part that's not working
class Grid(gridlib.Grid):
global cue
def __init__(self, parent, db):
gridlib.Grid.__init__(self, parent, -1)
self.CreateGrid(20,10)
for row in range(20):
rowNum = row + 1
self.SetRowLabelValue(row, "cue %s" %rowNum)
self.db = db
self.cur = self.db.con.cursor()
meta = self.cur.execute("SELECT * from CUES")
labels = []
for i in meta.description:
labels.append(i[0])
labels = labels[1:]
for i in range(len(labels)):
self.SetColLabelValue(i, labels[i])
all = self.cur.execute("SELECT * from CUES ORDER by DTindex")
for row in all:
row_num = row[0]
cells = row[1:]
for i in range(len(cells)):
if cells[i] != None and cells[i] != "null":
self.SetCellValue(row_num, i, str(cells[i]))
self.Bind(gridlib.EVT_GRID_CELL_CHANGED, self.CellContentsChanged)
def CellContentsChanged(self, event):
x = event.GetCol()
y = event.GetRow()
val = self.GetCellValue(y,x)
if val == "":
val = "null"
ColLabel = self.GetColLabelValue(x)
InsertCell = "UPDATE CUES SET %s = ? WHERE DTindex = %d"%(ColLabel,y)
self.cur.execute(InsertCell, [(val),])
self.db.con.commit()
self.SetCellValue(y, x, val)
class GridPanel(wx.Panel):
def __init__(self, parent, db):
wx.Panel.__init__(self, parent, -1)
self.db = db
self.cur = self.db.con.cursor()
grid = Grid(self, db)
sizer = wx.BoxSizer(wx.HORIZONTAL)
sizer.Add(grid)
self.SetSizer(sizer)
self.Fit()
def onAddCue():
global cue
row = cue[0] - 1
col=0
while col < 10:
for i in cue[1:]:
grid.SetCellValue(row, col, str(i))
col = col+1
class GetDatabase():
def __init__(self, f):
# check db file exists
try:
file = open(f)
file.close()
except IOError:
# database doesn't exist - create file & populate it
self.exists = 0
else:
# database already exists - need integrity check here
self.exists = 1
self.con = sqlite.connect(f)
class Frame(wx.Frame):
def __init__(self):
wx.Frame.__init__(self, None, -1,"Stage Lighting", size=(800,600))
panel = wx.Panel(self)
notebook = wx.Notebook(panel)
page1 = InitialInputs(notebook, db)
page2 = GridPanel(notebook, db)
notebook.AddPage(page1, "Initial Inputs")
notebook.AddPage(page2, "Grid")
sizer = wx.BoxSizer()
sizer.Add(notebook, 1, wx.ALL|wx.EXPAND, 5)
panel.SetSizer(sizer)
self.Layout()
if __name__ == "__main__":
db = GetDatabase("data.db")
app = wx.App()
logging.basicConfig(level=logging.DEBUG)
Frame().Show()
app.MainLoop()
Apparently, the question is about python syntax errors!
onAddCue is a method belonging to the class GridPanel. The class is instantiated in the variable page2.
So, you need to call the method something like this:
page2.OnAddCue()
hi i am very new to python so please help even if you feel i am asking a silly doubt. the thing is i am creating five lineedits from which values have to be extracted on click of button. but the problem is on click of button i am getting interfaceerror:Error binding parameter 0 - probably unsupported type. Below is my code:
class NewWindow(QtGui.QDialog):
def __init__(self, parent=None):
super(NewWindow, self).__init__(parent)
self.group1= QtGui.QGroupBox("Add Data")
self.patientName = QtGui.QLabel("Name")
self.patientEdit = QtGui.QLineEdit()
self.patientid = QtGui.QLabel("Id")
self.patientidEdit = QtGui.QLineEdit()
self.patientidEdit.setValidator(QtGui.QIntValidator(self.patientidEdit))
self.age = QtGui.QLabel("Age")
self.ageEdit = QtGui.QLineEdit()
self.ageEdit.setValidator(QtGui.QIntValidator(self.ageEdit))
self.genderlabel = QtGui.QLabel("Gender")
self.patientgend = QtGui.QLineEdit()
self.eyeType = QtGui.QLabel("Eye Type")
self.eyeTypeEdit = QtGui.QLineEdit()
self.AddData = QtGui.QPushButton("Add Data")
self.AddData.clicked.connect(self.AddData_clicked)
self.databaseLayout = QtGui.QGridLayout()
self.databaseLayout.addWidget(self.patientName,0,0)
self.databaseLayout.addWidget(self.patientEdit,0,1)
self.databaseLayout.addWidget(self.patientid,2,0)
self.databaseLayout.addWidget(self.patientidEdit,2,1)
self.databaseLayout.addWidget(self.age,4,0)
self.databaseLayout.addWidget(self.ageEdit,4,1)
self.databaseLayout.addWidget(self.genderlabel,6,0)
self.databaseLayout.addWidget(self.patientgend,6,1)
self.databaseLayout.addWidget(self.eyeType,8,0)
self.databaseLayout.addWidget(self.eyeTypeEdit,8,1)
self.databaseLayout.addWidget(self.AddData,10,10)
self.group1.setLayout(self.databaseLayout)
mainLayout = QtGui.QVBoxLayout()
mainLayout.addWidget(self.group1)
mainLayout.addStretch(1)
self.setLayout(mainLayout)
def AddData_clicked(self):
self.db_con = sqlite3.Connection
self.db_name = "./patientData.db"
self.createDb = sqlite3.connect(self.db_name)
self.queryCurs = self.createDb.cursor()
self.name = self.patientEdit.text()
self.id = self.patientidEdit.text()
self.age = self.ageEdit.text()
self.gender = self.patientgend.text()
self.eye_type = self.eyeTypeEdit.text()
self.queryCurs.execute('''CREATE TABLE IF NOT EXISTS PATIENT
(NAME TEXT NOT NULL, ID INTEGER PRIMARY KEY, AGE INTEGER NOT NULL, GENDER TEXT NOT NULL, EYE_TYPE TEXT NOT NULL)''')
self.queryCurs.execute('''INSERT INTO PATIENT(NAME, ID, AGE, GENDER, EYE_TYPE)
VALUES(?,?,?,?,?)''',(self.name,self.id,self.age,self.gender,self.eye_type))
print ('inserted row')
please help me, where am i going wrong........
i am getting error at line VALUES(?,?,?,?,?).......