How can I add a CSS Class to a Flask-Table Column - css

I want to add CSS Classes to specific Columns, the Table is made via Flask-Table. But I only found how to add Classes to the whole table is there a way to add classes to a Column too?
class Table(Table):
classes = ["table", "table-hover", "clickable-row", "sortable"]
username = Col("Username")
vorname = Col("Vorname")
nachname = Col("Nachname")
gebdat = DatetimeCol("Gebdat", datetime_format="dd.MM.yyyy")
admin = BoolCol("Rolle", yes_display='Admin', no_display='Benutzer')
aktiv = BoolCol("Status", yes_display='aktiviert',
no_display='deaktiviert')
edit = LinkCol("Bearbeiten", 'benutzerverwaltung.benutzerBearbeiten',
url_kwargs=dict(id='id'))

You can pass a dict in the column_html_attrs keyword argument when declaring a specific column inside the table class:
class MyTable(Table):
col = Col('Label', column_html_attrs = {'class': 'my-class'})
For more details check this example from the Flask-Table github.

Related

Django CMS - Copy relations in custom plugin not working

I have a problem with copy_relations after publishing a page.
I have a plugin with additional model. This model has ForeignKey to my plugin.
class InfContactForm(CMSPlugin):
name = models.CharField(max_length=50)
def copy_relations(self, oldinstance):
self.inf_contact_form.all().delete()
for inf_contact_form in oldinstance.inf_contact_form.all():
inf_contact_form.pk = None
inf_contact_form.plugin = self
inf_contact_form.save()
class InfContactFormAgreement(models.Model):
inf_contact_form = models.ForeignKey(InfContactForm, related_name="inf_contact_form")
agreement = HTMLField(blank=True, null=True)
The "InfContactFormAgreement" model is then used as stacked inline in "InfContactForm" plugin form.
Like it is written in docs, there is also copy_relations() method but when the page is published, nothing happens. When I get back again to edit mode InfContactFormAgreement is doubled every time I do it.
Here is also my cms_plugins.py file:
class PluginInfContactForm(CMSPluginBase):
render_template = '_contact_form.html'
name = name1
model = InfContactForm
require_parent = False
inlines = [AgreementStackedInline, ]
def render(self, context, instance, placeholder):
context['instance'] = instance
context = super(PluginInfContactForm, self).render(context, instance, placeholder)
agreements = instance.inf_contact_form.all()
context.update({
'agreements': agreements,
})
return context
plugin_pool.register_plugin(PluginInfContactForm)
Thank you for any advice.
instead of:
inf_contact_form.plugin = self
you should use:
inf_contact_form.inf_contact_form = self
and the resulting code should look like this:
def copy_relations(self, oldinstance):
self.inf_contact_form.all().delete()
for inf_contact_form in oldinstance.inf_contact_form.all():
inf_contact_form.pk = None
inf_contact_form.inf_contact_form = self
inf_contact_form.save()
regards
I had a similar situation, the only difference being that my many-to-many relationship was not in a plugin, but an extension (PageExtension).
In my case, #Dariusz solution did not work, and I had to update the implicit "inbetween" model that exists between the Extension model and the Associated model.
My solution (the key being the "through"):
class Extension(PageExtension):
tags_regions = models.ManyToManyField(Region, related_name="articles", blank=True)
def copy_relations(self, oldinstance):
for region_tag in oldinstance.tags_regions.through.objects.filter(extension=oldinstance):
region_tag.extension = self
region_tag.save()

Mongoengine serialize dictionary (with nested dicts)?

I've created a dictionary from an Uploaded file in Django.
This dictionary has a nested list of dictionaries:
file = {"name": "filename", "sections": [{"section_name": "string", "lines": [{line_number: 0, "line"; "data"}]}], "etc": "etc"}
The model represents the dictionaries depth too.
class Line(EmbeddedDocument):
line_number = IntField()
line = StringField()
definition = ReferenceField(Definition)
class Section(EmbeddedDocument):
section_name = StringField()
lines = EmbeddedDocumentListField(Line))
class File(Document):
name = StringField()
sections = EmbeddedDocumentListField(Section))
created_on = DateTimeField()
created_by = StringField()
modified_on = DateTimeField()
modified_by = StringField()
In the POST I have the following to chop the file up into the above Dict (the file is a simple text file):
file= {}
with open(os.path.join(path, filename + ".txt"), 'r') as temp_file:
filelines = temp_file.readlines()
sections = []
section = {}
lines = []
for i, l in enumerate(filelines):
if i == 0:
section["section_name"] = "Top"
elif '*' in l:
if l.index('*') == 0 and '*' not in lines[len(lines) - 2"line"]:
section["lines"] = lines
lines = []
sections.append(section)
section = dict()
section["section_name"] = filelines[i + 1][1:-2]
line = {"line_number": i + 1, "line": l}
lines.append(line)
section['lines'] = lines
sections.append(section)
file["name"] = filename
file["sections"] = sections
I will tidy this up eventually.
Once the dict has been made how do I serialise it using the serializer?
Is it possible to insert this into a serializer?
If not how can I get it all into the database with validation?
I've tried json.dumps() and JsonRequst() then putting them in data= for the serializer but get Unable to get repr for <class '....'>
I'm pretty new to Django and MongoDB so if you need more info I can provide :)
Thanks!
Update
Change the model's List Fields to EmbeddedDocumentListField as suggest in the answer.
Answered
Thanks to Boris' suggestion below it pointed me to an error I wasn't getting initially. I had a typo and passing the dict directly into FileSerializer(data=file) works like a charm! :)
James!
The easiest way to validate that your incoming JSONs adhere to the Mongoengine Documents schema that you've specified is to use DRF-Mongoengine's DocumentSerializer.
Basically, what you need to do is create a serializer
serializers.py
import rest_framework_mongoengine
class FileSerializer(rest_framework_mongoengine.DocumentSerializer):
class Meta:
fields = '__all__'
model = File
Then you need a view or viewset that makes use of this Serializer to respond to GET/POST/PUT/DELETE requests.
views.py
from rest_framework_mongoengine import viewsets
class FileViewSet(viewsets.ModelViewSet):
lookup_field = 'id'
serializer_class = FileSerializer
def get_queryset(self):
return File.objects.all()
and register this viewset with a router
urls.py
from rest_framework import routers
# this is DRF router for REST API viewsets
router = routers.DefaultRouter()
# register REST API endpoints with DRF router
router.register(r'file', FileViewSet, r"file")
I'd also recommend using EmbeddedDocumentListField instead of ListField(EmbeddedDocumentField(Section)) - it has additional methods.

Advanced Custom Fields data from ancestor page

I am trying to make ACF data available on child pages two levels under the parent. I have a solution for making it available to a child page:
if ( $post->post_parent ) {
$headingFont = get_field('community_heading_font', $post->post_parent);
$bodyFont = get_field('community_body_font', $post->post_parent);
$primaryColor = get_field('community_primary', $post->post_parent);
$secondaryColor = get_field('community_secondary', $post->post_parent);
$fifteenSecondaryColor = get_field('community_fifteen_secondary', $post->post_parent);
$tertiaryColor = get_field('community_tertiary', $post->post_parent);
}
However, this information isn't available once we're a level deeper. That is, the ACF field 'community_heading_font' isn't available to the grandchild of the page originally providing data for that field.
I've tried post->post_parent->post_parent, and I've also tried to use post->post_parent on a variable:
$parentPage = $post->post_parent;
$grandparentPage = $parentPage->post_parent
To get the $grandparentPage ID for use in your ACF functions, use the wp_get_post_parent_id() function.
$grandparentPage = wp_get_post_parent_id($post->post_parent);
$headingFont = get_field('community_heading_font', $grandparentPage);
https://codex.wordpress.org/Function_Reference/wp_get_post_parent_id

I need to select a particular row in a table with selenium webriver

I need to select a particular row in a table with selenium web driver, I have close to 5000 rows, Navigating through each row would be difficult. Any better approach if we have?
You need to click on a checkbox to select the row right?
I'll assume thats what you meant:
The only way I know how is to check each row, select the filter (i.e. a customer number) and once you find it, click on the selection checkbox.
Mostly of the tables are similar so here is an example:
This is your table:
= = = = = = =
=================================================================================================
= = = = = = =
=================================================================================================
= = = = = = =
=================================================================================================
Lets say that in the first row, is where the checkbox is, and that in the second row is the location of the filter.
meaning the data you will use in order to know that this is the row you need....
you will need to inspect the table element in order to find its ID, once you have that info you can use a similar method as the below:
Where you will use your webdriver, data filter, tableID and the number of the column where your data filter is located.
The method will return the row you need to click, then you can simply use the row[columnNumberLocation].Click() in order to select it.
public IWebElement returnRow(IWebDriver webDriver, string filter ,string tableName, int i)
{
IWebElement tableElement = webDriver.FindElement(By.Id(tableName));
IWebElement tbodyElement = tableElement.FindElement(By.TagName("TBODY"));
List<IWebElement> rows = new List<IWebElement>(tbodyElement.FindElements(By.TagName("tr")));
foreach (var row in rows)
{
List<IWebElement> cells = new List<IWebElement>(row.FindElements(By.TagName("td")));
if (cells.Count > 0)
{
string s = cells[i].Text;
if (s.Equals(filter))
{
return row;
}
}
}
return null;
}
It depends on what is your requirement of selecting that particular row.
I assume you need to select that according to the row index.
So it's all about the your x-path to locate the element.
ex: I need to get row number 2000
WebElement element = driver.findElement(By.xpath("//tr[2000]"));

How to Advance filter for category and author in Smartsearch in kentico

I have created basic search and uses the SearchHelper to get smart search results based on the search paramaters.
Now creating the Advance search based on Category , Author etc but did not find the way to filter the result based on these condition.
I am looking for a way to display the results using the dataset that
// Prepare parameters
SearchParameters parameters = new SearchParameters()
{
SearchFor = searchText,
SearchSort = SearchHelper.GetSort(srt),
Path = path,
ClassNames = DocumentTypes,
CurrentCulture = culture,
DefaultCulture = defaultCulture,
CombineWithDefaultCulture = CombineWithDefaultCulture,
CheckPermissions = CheckPermissions,
SearchInAttachments = SearchInAttachments,
User = (UserInfo)CMSContext.CurrentUser,
SearchIndexes = Indexes,
StartingPosition = startPosition,
DisplayResults = displayResults,
NumberOfProcessedResults = numberOfProceeded,
NumberOfResults = 0,
AttachmentWhere = AttachmentsWhere,
AttachmentOrderBy = AttachmentsOrderBy,
BlockFieldOnlySearch = BlockFieldOnlySearch,
};
// Search
DataSet results = SearchHelper.Search(parameters);
The easiest way is to use the method:
SearchHelper.CombineSearchCondition()
The first parameter is the searchText, with the search terms you probably already have.
The second parameter is searchConditions, which can be formatted as per https://docs.kentico.com/k10/configuring-kentico/setting-up-search-on-your-website/smart-search-syntax
Alternatively you could just append your search conditions to your search text manually, separating each term with a space.
Remember that to filter based on any field they need to be selected as searchable in the SiteManager->Development->DocumentTypes->DocumentType->Search Tab.

Resources