flask-admin and allow_inheritance for an embedded document in mongoengine - mongoengine

For flask-admin the following only gives me CRUD access to Task and the TaskItem embedded document, but no access to ItemParameter or ItemTitle. Is this not supported in flask-admin or am I doing something wrong? Thx
class TaskItem(db.EmbeddedDocument):
type = db.StringField(max_length = 32)
column = db.IntField()
row = db.IntField()
width = db.IntField()
height = db.IntField()
meta = {'allow_inheritance': True}
class ItemParameter(TaskItem):
label = db.StringField(max_length = 32)
formula = db.StringField(max_length = 256)
parameter = db.ReferenceField(Parameter)
class ItemTitle(TaskItem):
label = db.StringField(max_length = 32)
document = db.ReferenceField(Document)
class Task(db.Document):
items = db.ListField(db.EmbeddedDocumentField(TaskItem))
def __unicode__(self):
return unicode(self.name)
# Flask-Admin
class SecuredModelView(ModelView):
def is_accessible(self):
return current_user.has_role('admin')
admin.add_view(SecuredModelView(Task))

As stated by the flask-admin creator this feature is not yet supported.
https://github.com/flask-admin/flask-admin/issues/907

Related

Django model passes wrong value

I am making a webapp with Django Framework. I am making a form for creating new "incidents" (this form is using a model called NewIncidents). I am trying to take the values under "title" from my IncidentsType table, and use them as options for a Select menu in the form. But, something weird happens: in the form, the options appear, but when you submit the form and check how it was submitted (in the admin panel), it shows the .object(n) instead of the name of the option.
For example: Result of one submit : in the form showed the correct selection name, which was "Internet", but after submitting, in the admin panel, it showed IncidentsType object (3).
My models:
from django.db import models
class NewUsers(models.Model):
name = models.CharField(max_length=38)
user_name = models.CharField(max_length=35)
class NewIncidents(models.Model):
tipo = models.CharField(max_length = 50)
titulo = models.CharField(max_length = 200)
resolucion = models.CharField(max_length = 300)
class IncidentsType(models.Model):
title = models.CharField(max_length = 200)
subtitle = models.CharField(max_length = 200)
description = models.CharField(max_length = 400)
My form:
from django import forms
from django.db import models
from .models import NewIncidents, IncidentsType
class IncidentForm(ModelForm):
incidents = IncidentsType.objects.all()
eleji = []
for incident in incidents:
ttype = incident.title
num = str(incident)
conjunto = (num, ttype)
eleji.append(conjunto)
tipo = forms.ChoiceField(choices=eleji)
class Meta:
model = NewIncidents
fields = ('tipo', 'titulo', 'resolucion')
labels = {
'tipo': 'Tipo de Incidente:',
'titulo': 'Resumen del Incidente:',
'resolucion': 'Resolucion del Incidente:',
}
widgets = {
'tipo': forms.Select(attrs={'class' : 'form-control'}),
'titulo': forms.TextInput(attrs={'class' : 'form-control'}),
'resolucion': forms.TextInput(attrs={'class' : 'form-control'}),
}
on your models try defining the str function to help django better represent the objects of the model in the admin page
example for the IncidentsType:
class IncidentsType(models.Model):
title = models.CharField(max_length = 200)
subtitle = models.CharField(max_length = 200)
description = models.CharField(max_length = 400)
def __str__(self):
return self.title
basicly this function should return a string that represents the object like a name or a title
you can read more about it in the docs here

How in Pyhton's OOP a class's method access to another class's method?

I am new to Python OOP and I am trying to learn the basics of Python OOP and I came across a video on YouTube that teaches the basics of it. The code is an example code from the video. I understood all of it but I am not able to understand how the class "Course's" "get_average_grade()" method is accessing the class "Student's" "get_grade()" method? Any help is highly appreciated.
class Student:
def __init__(self, name, age, grade):
self.name = name
self.age = age
self.grade = grade # 0-100
def get_grade(self): #<---- This method was used inside the Course class
return self.grade
class Course:
def __init__(self, name, max_students):
self.name = name
self.max_students = max_students
self.students = []
def add_student(self, student):
if len(self.students) < self.max_students:
self.students.append(student)
return True
return False
def get_average_grade(self):
value = 0
for student in self.students:
value = value + student.get_grade() #<---- This Method is from the Student class
return value / len(self.students)
s1 = Student("Tim", 19, 95)
s2 = Student("Bill", 19, 75)
s3 = Student("Jill", 19, 65)
course = Course("Science", 2)
course.add_student(s1)
course.add_student(s2)

Default values were not showing in the html page (Flask Forms)?

I am getting data from the database get_row = PolicyCheck.query.filter_by(id=1).first()
class EditPasswordPolicyForm(FlaskForm):
greater = IntegerField('greater')
lesser = IntegerField('lesser')
special = BooleanField('special')
upper = BooleanField('upper')
lower = BooleanField('lower')
digit = BooleanField('digit')
update = SubmitField('update')
def __init__(self, *args, **kwargs):
super(EditPasswordPolicyForm, self).__init__(*args, **kwargs)
get_row = PolicyCheck.query.filter_by(id=1).first()
self.greater.default = get_row.greaterthan
self.lesser.default = get_row.lessthan
self.special.default = get_row.specialChar
self.upper.default = get_row.isupper
self.lower.default = get_row.islower
self.digit.default = get_row.isdigit
The values are getting updated for whatever the value I fill in the form and submit, but all the form fields are blank by default. I want to show the latest updated data from the database in the form fields as default values. When I fill the form and submit It should get refreshed by the latest updated value as default values and should not be blank.
def __init__(self, *args, **kwargs):
super(EditPasswordPolicyForm, self).__init__(*args, **kwargs)
get_row = PolicyCheck.query.filter_by(id=1).first()
self.greater.data = get_row.greaterthan
self.lesser.data = get_row.lessthan
self.special.data = get_row.specialChar
self.upper.data = get_row.isupper
self.lower.data = get_row.islower
self.digit.data = get_row.isdigit
Maybe it will work.

Object has no attribute but attribute is defined

I have defined an attribute in a custom class, but I keep receiving an AttributeError when I try to access it.
class SMainWindow(QMainWindow):
def __init__(self):
# Constructor
super(SMainWindow, self).__init__()
self.myapp = PyQtApp()
self.layout = QVBoxLayout()
self.label_text = ''
self.settings = scrudb.retrieve_settings('current')
self.competition = self.retrieve_competition()
self.set_competition(self.competition.id)
self.label = QLabel(self.label_text)
self.button_scrutineer = QPushButton('Scrutineer Competition')
self.button_comps = QPushButton('Change Competition')
self.button_comp = QPushButton('Edit Competition Details')
self.button_dancers = QPushButton('Add/Edit Competitors')
self.button_judges = QPushButton('Add/Edit Judges')
self.button_dancerGroups = QPushButton(
'Define Competitor Groups & Dances')
self.button_import = QPushButton('Import CSV')
self.button_delete = QPushButton('Delete Competition')
self.button_exit = QPushButton('Exit')
self.button_comps.clicked.connect(self.select_competition)
self.button_delete.clicked.connect(self.delete_competition)
self.button_exit.clicked.connect(self.exit_app)
if (self.competition == None):
self.disable_buttons()
self.layout.addWidget(self.label)
self.layout.addWidget(self.button_scrutineer)
self.layout.addWidget(self.button_comps)
self.layout.addWidget(self.button_comp)
self.layout.addWidget(self.button_dancers)
self.layout.addWidget(self.button_judges)
self.layout.addWidget(self.button_dancerGroups)
self.layout.addWidget(self.button_import)
self.layout.addWidget(self.button_delete)
self.layout.addWidget(self.button_exit)
self.myapp.setLayout(self.layout)
def set_competition(self, comp_id):
self.competition = scrudb.retrieve_competition(comp_id)
if (self.competition != None):
self.label_text = ('<center>Competition:<br><strong>%s</strong><br>%8s<br>%s</center>' % (self.competition.name, self.get_formatted_date(self.competition.eventDate), self.competition.location))
self.label.setText(self.label_text)
self.settings.lastComp = self.competition.id
scrudb.set_settings(self.settings)
return self.competition
else:
self.label_text = ('<center>No Competition Selected</center>')
return None
File "/Users/majikpig/mu_code/src/main/python/scruinterface1.py", line 182, in set_competition
self.label.setText(self.label_text)
AttributeError: 'SMainWindow' object has no attribute 'label'
You need to change order of fields ... in set competition function you try to access field, which you haven't defined yet.
self.set_competition(self.competition.id)
self.label = QLabel(self.label_text)

How to create a python instance that has another class object linked to it?

If I have a simple class like below:
class Usr:
def __init__(self, time_r):
self.time_range = time_r
where I want the attributetime_r to be an object of class TimeRange like below:
class TimeRange:
def __init__(self, min_time, max_time):
self.ti = min_time
self.tf = max_time
I would like to create an empty instance of Usr s = Usr and then assign the attributes later. Example: s.time_range.ti = 5 , s.time_range.tf = 10
In other words time_r in Usr should be an attribute that will automatically create an instance of TimeRange for that Usr instance
How can one link the two classes in the manner above?
you could set initializers to default values (e.g. None):
class TimeRange:
def __init__(self, min_time=None, max_time=None):
self.ti = min_time
self.tf = max_time
class Usr:
def __init__(self, time_r=None):
self.time_range = time_r if time_r is not None else TimeRange()
then:
s = Usr()
s.time_range.ti = 5
s.time_range.tf = 10
you may want to set more reasonable default values for TimeRange...

Resources