Default values were not showing in the html page (Flask Forms)? - python-3.x

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.

Related

how solve django create model class dynamically

When dynamically creating and generating Model class, modify some
properties, fill in the information required by the sub-table, the
first time can return the normal result, the second result error,
after the analysis of the second result field to retain the first
table name:
class Object:
def __init__(self, **kwargs):
self.__dict__.update(kwargs)
def _model_new(cls, *args, **kwargs):
return cls(*args, **kwargs)enter code here
class ShardModel(object):
_shard_db_models = {}
temp_class = []
def __new__(cls, *args, **kwargs):
shard_key = kwargs.pop('shard_key', 0) % cls.Config.table_num
model_name = cls.__name__
model_name += '_%s' % shard_key
model_class = cls._shard_db_models.get(model_name)
if model_class is not None:
return model_class
# Deep copy attrs
attrs = dict()
attrs.update(cls.__dict__)
if 'objects' in attrs:
attrs['objects'] = attrs['objects'].__class__()
# Set table name with shard_key
meta = Object(**cls.Meta.__dict__)
meta.db_table = meta.db_table % shard_key
meta.abstract = False
attrs['Meta'] = meta
attrs['new'] = classmethod(_model_new)
attrs['__module__'] = cls.__name__
cursor = connection.cursor()
tables = [table_info.name for table_info in connection.introspection.get_table_list(cursor)]
# Create model class dynamically
model_class = type(model_name, tuple([models.Model] + list(cls.__bases__[1:])), attrs)
print(model_class)
if meta.db_table not in tables:
for cmd in ('makemigrations', 'migrate'):
exec_command(cmd, meta.app_label)
cls._shard_db_models[model_name] = model_class
return model_class
this is my model
class Nice(ShardModel):
user_id = models.IntegerField()
user_name = models.CharField(max_length=256)
password = models.CharField(max_length=256)
class Config:
table_num = 3
class Meta:
app_label = 'Test'
db_table = 'test_%s'
abstract = True
this my view
def NiceView(request):
user_id = int(request.GET.get('user_id'))
user = Nice(shard_key=user_id).objects.get(user_id=user_id)
return HttpResponse(json.dumps(model_to_dict(user)))
Here are the two times test results
url:http://127.0.0.1:8000/test?user_id=7
results:{"id": 2, "user_id": 7, "user_name": "ni", "password": "hao"};url:http://127.0.0.1:8000/test?user_id=5;error:(1054, "Unknown column 'test_1.user_id' in 'field list'")

Django ModelManager not saving the model instance correctly

I am working on an ecommerce project but my OrderManager() class does not saving the instance(i think)
When i am clicking on BOOK button i am getting this error which is defined in my view
order_amount = order_obj.total * 100
AttributeError: 'NoneType' object has no attribute 'total'
But when i refresh the page error goes way and order_obj.total * 100 is calculated, But my question is why i need to refresh the page again and again when i create a new order.
Here is my models.py
class OrderQuerySet(models.query.QuerySet):
def not_created(self):
return self.exclude(status='created')
class OrderManager(models.Manager):
def get_queryset(self):
return OrderQuerySet(self.model, using=self.db)
def create_or_get_order(self, product):
created = None
obj = None
qs = self.get_queryset().filter(product=product, active=True, status='created')
if qs.count() == 1:
obj = qs.first()
else:
self.model.objects.create(product=product)
created = True
return obj, created
class Order(models.Model):
order_id = models.CharField(max_length=120, blank=True)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
total = models.PositiveIntegerField()
active = models.BooleanField(default=True)
objects = OrderManager()
class Meta:
ordering = ['-ordered_on', '-updated']
def __str__(self):
return self.order_id
def check_done(self): # check everything is correct before final checkout
order_id = self.order_id
total = self.total
if order_id and total > 0:
return True
return False
def mark_paid(self):
if self.check_done():
self.status = 'paid'
self.save()
return self.status
def pre_save_create_order_id(sender, instance, *args, **kwargs):
if not instance.order_id:
instance.order_id = unique_order_id_generator(instance)
pre_save.connect(pre_save_create_order_id, sender=Order)
def pre_save_order_total(sender, instance, *args, **kwargs):
"""calculate the product total while clicking on Book Button
(Still booking is not done you just clicked on Book button)"""
instance.total = instance.product.price
pre_save.connect(pre_save_order_total, sender=Order)
Views.py
def checkout_home_view(request, *args, **kwargs):
order_obj = None
order_amount = None
order_currency = None
order_id = None
slug = kwargs['slug']
product = Product.objects.get(slug=slug)
if product is not None:
# ****************** Here is problem ******************************
order_obj, order_create = Order.objects.create_or_get_order(product)
''' HERE I AM GETTING order_obj as None BUT WHEN I REFRESH ERROR GOES WAY '''
print('order_obj', order_obj) # printing None initally
order_amount = order_obj.total * 100
order_currency = 'INR'
order_id = order_obj.order_id
if request.method == 'POST':
'check that booking is done'
is_prepared = order_obj.check_done() # check_done() defined in Order model
if is_prepared:
client = razorpay.Client(auth=("xxx", "xxx"))
payment = client.order.create(dict(amount=order_amount, currency=order_currency))
if payment:
order_obj.mark_paid() # mark_paid() defined in Order model
order_obj.save()
class OrderManager(models.Manager):
...
def create_or_get_order(self, product):
created = None
obj = None
qs = self.get_queryset().filter(product=product, active=True, status='created')
if qs.count() == 1:
obj = qs.first()
else:
# -------------- catch the returned obj and return --------------
obj = self.model.objects.create(product=product)
created = True
return obj, created

In Django FileField, how to set file.name that contains also random url?

EDIT
I am trying to modify the name of an uploaded file to include also some url in it. In my case it's the custom "file_url" variable. However the current result is: "filename", but the expected result should be: http://www.google.com/"filename"
Here is my View.py:
class CreateImage(CreateAPIView):
permission_classes = (IsAuthenticated,)
model = models.Image
serializer_class = serializers.ImageSerializer
def get_serializer(self, container, *args, **kwargs):
serializer_class = self.get_serializer_class()
kwargs["context"] = self.get_serializer_context()
old_filename = self.request.FILES['image'].name
if self.request.FILES:
if container == 'products':
data = self.request.data.copy()
product_name = data["product_name"]
file_url = f"{settings.MEDIA_DOMAIN}{container}/"
new_filename = get_product_new_filename(old_filename, product_name)
data['image'].name = file_url + new_filename
kwargs["data"] = data
return serializer_class(*args, **kwargs)
And simple model for reference:
class Image(models.Model):
image = models.FileField()
def __str__(self):
return self.image.name
Do you have any idea, how to include given url in the filename? [edit] it looks like the issue is with "/" sign. Is it possible to inlcude it in the name?
The workaround, would be to create additional field, say image_url as CharField, and save it there, but maybe there is a way to not duplicate table inputs.
Thanks in advance!

Doesn't create a database table from my model baseclass

I'm trying to build a logging application that stores date, exercise type, duration and comments in a database. It renders the form as i expect it but it does not create the database table from my base class. I just got stuck and hope anyone can help me what's going wrong.
CHOICES = [
(None, 'Choose Exercise'),
('Aerobics', 'Aerobics'),
('Box & Kick', 'Box & Kick'),
('Circle Training', 'Circle Training'),
('Core', 'Core'),
('Afrodance', 'Afro Dance'),
('HIT', 'HIT'),
('StepUp', 'StepUp'),
('Zumba', 'Zumba')]
class AerobicExercise(models.Model):
date = models.DateField(default='YYYYMMDD')
duration = models.DurationField()
comment = models.TextField(blank=True)
exercise = models.CharField(choices=CHOICES, max_length=20)
def __str__(self):
return self.exercise
class SplitDurationWidget(forms.MultiWidget):
def __init__(self, attrs=None):
widgets = (forms.NumberInput(attrs=attrs),
forms.NumberInput(attrs=attrs),
forms.NumberInput(attrs=attrs))
super(SplitDurationWidget, self).__init__(widgets, attrs)
def decompress(self, value):
if value:
hours = value.seconds // 3600
minutes = (value.seconds % 3600) // 60
seconds = value.seconds % 60
return [int(value.days), int(hours), int(minutes), int(seconds)]
return [0, 0, 0, 0]
class Duration(MultiValueField):
widget = SplitDurationWidget
def __init__(self, *args, **kwargs):
fields = (
forms.IntegerField(),
forms.IntegerField(),
forms.IntegerField(),
)
super(Duration, self).__init__(
fields=fields,
require_all_fields=True, *args, **kwargs
)
def compress(self, data_list):
if len(data_list) == 3:
return timedelta(
hours=int(data_list[0]),
minutes=int(data_list[1]),
seconds=int(data_list[2])
)
else:
return timedelta(0)
class AerobicForm(ModelForm):
def __init__(self, *args, **kwargs):
super(AerobicForm, self).__init__(*args, **kwargs)
self.fields['duration'] = Duration()
date = forms.DateField(initial=datetime.date.today())
class Meta:
model = AerobicExercise
fields = '__all__'
localized_fields = ('date',)
widgets = {
'comment': Textarea(attrs={'placeholder': 'The highlight of this workout was...'}),
}

custom delegate doesn't follow when reordering QTableView

I'm using a custom delegate to display a column of comboBoxes in my QTableView.
In addition to the default selection issue (enter link description here) I have a problem when I reorder the data of my QTableView (per column, or by applying filters). The comboxes stay where they were when the grid was not displayed.
Is there a way I can force a repaint of the delegate ? I to copy the code of the paint method (without the index) but this only caused my program to crash.
Let me know if I'm not clear enough.
Here is the code of my custom delegate :
class ComboBoxDelegate(QtGui.QItemDelegate):
def __init__(self, parent, itemslist):
QtGui.QItemDelegate.__init__(self, parent)
self.itemslist = itemslist
self.parent = parent
def paint(self, painter, option, index):
# Get Item Data
value = index.data(QtCore.Qt.DisplayRole).toInt()[0]
# value = self.itemslist[index.data(QtCore.Qt.DisplayRole).toInt()[0]]
# fill style options with item data
style = QtGui.QApplication.style()
opt = QtGui.QStyleOptionComboBox()
opt.currentText = str(self.itemslist[value])
opt.rect = option.rect
# draw item data as ComboBox
style.drawComplexControl(QtGui.QStyle.CC_ComboBox, opt, painter)
self.parent.openPersistentEditor(index)
def createEditor(self, parent, option, index):
##get the "check" value of the row
# for row in range(self.parent.model.rowCount(self.parent)):
# print row
self.editor = QtGui.QComboBox(parent)
self.editor.addItems(self.itemslist)
self.editor.setCurrentIndex(0)
self.editor.installEventFilter(self)
self.connect(self.editor, QtCore.SIGNAL("currentIndexChanged(int)"), self.editorChanged)
return self.editor
# def setEditorData(self, editor, index):
# value = index.data(QtCore.Qt.DisplayRole).toInt()[0]
# editor.setCurrentIndex(value)
def setEditorData(self, editor, index):
text = self.itemslist[index.data(QtCore.Qt.DisplayRole).toInt()[0]]
pos = self.editor.findText(text)
if pos == -1:
pos = 0
self.editor.setCurrentIndex(pos)
def setModelData(self,editor,model,index):
value = self.editor.currentIndex()
model.setData(index, QtCore.QVariant(value))
def updateEditorGeometry(self, editor, option, index):
self.editor.setGeometry(option.rect)
def editorChanged(self, index):
check = self.editor.itemText(index)
id_seq = self.parent.selectedIndexes[0][0]
update.updateCheckSeq(self.parent.db, id_seq, check)
def updateDelegate(self, indexRow, indewCol):
# index = self.parent.model.createIndex(indexRow, indewCol)
seq_id = self.parent.model.arraydata[indexRow][0]
print seq_id
check = select.getCheck(self.parent.db, seq_id)
check = check[0][0]
print check
if check != '':
pos = self.checkDict[check]
else:
pos = 0
self.editor.setCurrentIndex(pos)
And I call it from my QTableView class :
self.setEditTriggers(QtGui.QAbstractItemView.CurrentChanged)
self.viewport().installEventFilter(self)
self.delegate = ComboBoxDelegate(self, self.checkValues)
self.setItemDelegateForColumn(13,self.delegate)
I call the updateDelegate function when I sort the column (from the model class) :
def sort(self, Ncol, order):
self.emit(QtCore.SIGNAL("layoutAboutToBeChanged()"))
self.arraydata = sorted(self.arraydata, key=operator.itemgetter(Ncol))
i = 0
for row in self.arraydata:
self.parent.delegate.updateDelegate(i, 13)
i += 1
if order == QtCore.Qt.DescendingOrder:
self.arraydata.reverse()
self.emit(QtCore.SIGNAL("layoutChanged()"))
I needed to call QItemDelegate.paint() method in my custom paint() method. Hope it can help someone.

Resources