how to render datatable inside ajax-modal in openstack horizon dashboard? - django

i'm beginner in Python Django. according to openstack's customizing horizon dashboard tutorial i've successfully added new panel, tab with datatable. i also added table actions in table class which open ajax-modal. but instead of render form inside that i need to render datatable which should feel up by ajax-response. each row contains form input element (e.g text,radio). but i couldn't figure out how to render datatable inside ajax-modal.
please have a look on tables.py
class AddSwitch(tables.LinkAction):
name = "addswitch"
verbose_name = _("Add Switch")
url = "horizon:project:sdncontroller:addswitch"
classes = ("ajax-modal", "btn-create",)
class Switches(tables.DataTable):
dpid = tables.Column("dpid",verbose_name=_("DPID"))
address = tables.Column('address', verbose_name=_("Address"))
vendor = tables.Column('vendor', verbose_name=_("Vendor"))
packets = tables.Column('packets', verbose_name=_("Packets"))
bytes = tables.Column('bytes', verbose_name=_("Bytes"))
flows = tables.Column('flows', verbose_name=_("Flows"))
connectedsince = tables.Column('connectedsince', verbose_name=_("ConnectedSince"))
detail= tables.Column('details', verbose_name=_("Detail"))
class Meta:
name = "Switches"
verbose_name = _("Switches")
table_actions = (AddSwitch,)
also i've created workflows.py and create class for AddSwitch
class AddSwitch(workflows.Workflow):
slug = "addswitch"
name = _("Add Switch")
finalize_button_name = _("Add")
success_message = _('Added switch "%s".')
failure_message = _('Unable to add switch "%s".')
success_url = "horizon:project:sdncontroller:index"
default_steps = (AddSwitchStep,)
def format_status_message(self, message):
name = self.context.get('name')
return message % name
def handle(self, request, context):
try:
#api.lbaas.pool_create(request, **context)
return True
except Exception:
return False
this is the point where i stuck. i don't how to code and where to code for rendering datatable and that too fill up dynamically through ajax-response.
Thanks, I hope someone who could lead me into this.

You forgot to mention the "columns" attribute in the Class Meta. Please follow the mechanism currently used by Horizon to render the "Instances" data table. You can find the detailed step by step tutorial to create and render a data table here: http://docs.openstack.org/developer/horizon/topics/tutorial.html
Hope it helps

Related

How to apply advance django query set filters based on two different columns?

I am new to django. I am working on a test project. Where I have a Model CollectFee with structure given below:
class CollectFee(models.Model):
boarder = models.ForeignKey(Boarder, on_delete=models.CASCADE)
feetype = models.ForeignKey(FeeType, on_delete=models.CASCADE)
amountdue = models.PositiveIntegerField("amount Due")
amountpaid = models.PositiveIntegerField("amount Paid")
balance = models.PositiveIntegerField("Balance")
class Meta:
verbose_name_plural = "Collect Fee"
def __str__(self):
return self.boarder.name
I want to apply a query set in the views which will display all the records where feetype_id is not 2, when this record is excluded then also exclude those records which have the same boarder_id as of already excluded record.
For example, Exclude the second row as it has feetype_id = 2 then also exclude the third row because it has the same boarder_id as of second row.
As I am new, I was able to just implement the filter below:
def feedue(request):
last_fee_type = FeeType.objects.last()
boarders = CollectFee.objects.exclude(feetype_id=last_fee_type)
context = {'boarders':boarders}
return render(request, 'fee-due.html', context)
You can exclude the many-to-one relationship with the through accessor like this:
CollectFee.objects.exclude(boarder__collectfee__feetype=last_fee_type)
This expression essentially gets the Boarder from a particular CollectFee object, then all CollectFees associated with that Boarder and their FeeTypes, allowing you to exclude accordingly.
May be this helps
def feedue(request):
excluded_objs = CollectFee.objects.filter(feetype_id=2)
border_ids = [id.border_id for obj in excluded_objs]
duefee = CollectFee.objects.exclude(boarder_id__in=border_ids)
context = {'duefee': duefee}
return render(request, 'fee-due.html', context)

Showing ads between posts django ? Trying to show ads after specific number of posts

I want to implement this thing, Like Facebook showing ads when we are scrolling posts, after 4th or 5th post we see some ads, how can I do that please can someone tell me? If any video link is available please share
Between two post like this
I am showing all the post by for loop, if any nested for loops available please share how can I loop two different model in single loop , showing 1st item of one model after 5th item of another model loop
**I am not using google ad sense, you can imagine its like I will create my own model , maybe same post model where is_ads=True be a field like that.
This is my post model-
class Post(models.Model):
postuuid = models.UUIDField(default=uuid.uuid4,unique=True,editable=False)
user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, null=True)
title = models.CharField(max_length=150,blank=False)
text = models.TextField(null=True,blank=False)
image = models.ImageField(upload_to='post_images/',null=True,blank=True,default="")
created_at = models.DateTimeField(auto_now_add=True, null=True)
likes = models.ManyToManyField(User, blank=True, related_name="post_like")
tag= models.CharField(max_length=150,blank=True)
post_url=models.URLField(max_length=150,blank=True)
video = models.FileField(upload_to='post_videos/',null=True,blank=True,default="")
# community = models.ForeignKey(communities,on_delete=models.CASCADE)
def __str__(self):
return self.title
Looking at this, I think your best option would be to create a view function that creates two querysets and merges them together into a single one that you can pass to the context. It would be something like this:
# settings.py
AD_POST_FREQUENCY = 5 # Use this to control the frequency of ad posts appearing in the list of posts.
# views.py
from settings import AD_POST_FREQUENCY
def post_list(request):
ad_posts = Post.objects.filter(is_ad=True)
non_ad_posts = Post.objects.filter(is_ad=False)
posts = []
non_ad_post_section_count = 0
for i, post in enumerate(non_ad_posts):
posts.append(post)
if i % AD_POST_FREQUENCY == 0:
ad_post = ad_posts[non_ad_post_section_count]
posts.append(ad_post)
non_ad_post_section_count += 1
context = {
'posts': posts,
}
return render(request, 'your_template.html', context=context)
Using this approach, you would be able to essentially create a single list of posts to return to your template. Then you would only need to loop through the list in the template to display all the posts.
I haven't tried this myself but hopefully, it helps you.

Selectable list of users in Django?

models.py
class EmployeeReportRequestForm(forms.Form):
EMPLOYEECHOICE = []
employees = User.objects.filter(group_name='rep')
for employee in employees:
EMPLOYEECHOICE.append([employee.get_username(), employee.get_full_name()])
employee_choice = forms.CharField(max_length=50, widget=forms.Select(choices=EMPLOYEECHOICE))
start_date = forms.DateField(widget=forms.SelectDateWidget())
end_date = forms.DateField(widget=forms.SelectDateWidget())
Trying make a form that allows someone to make a selection from a list of users in a particular group, I figured this would work, but it is not. The most info I'm able to get error wise is
"django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet."
I'm assuming my issue is trying to query the User database from within a Model and that I need to run the lines of code that generate the EMPLOYEECHOICE list in a view and then somehow pass that to the Model? Or just define the widget to be used in the View?
models.py
class EmployeeRequestForm(forms.Form):
def __init__(self):
self.choice_list = [('test', 'test'),]
self.employees = User.objects.filter(groups__name='rep')
for self.x in self.employees:
self.choice_list.append([self.x.get_username(), self.x.get_full_name()])
self.CHOICES = self.choice_list
super (EmployeeRequestForm, self).__init__()
self.fields['employee_choice'].widget = forms.Select(choices=self.CHOICES)
employee_choice = forms.CharField(max_length=100)
start_date = forms.DateField(widget=forms.SelectDateWidget())
end_date = forms.DateField(widget=forms.SelectDateWidget())
Figured out what I was doing wrong, needed to define the choices within the init method. Not sure if this is the best way to do it, but it works.

update django choice field with database results

I am developing an application using django where the UI needs to be updated when user interacts with it. For instance I have a Drop down field where the user selects a drink and submits it then based on that a dropdown with the places that drink is available, price and quantity at each place needs to be displayed. The user will then further submit the form for second process.
From my understanding the Forms in django are pre-defined and I am not able to think of a way using which I could achieve this.
What I could come up was defining a regular form class
class dform(forms.Form):
SOURCES_CHOICES = (
(A, 'A'),
(E, 'E'),
)
drink = forms.ChoiceField(choices = SOURCES_CHOICES)
location = forms.ChoiceField(choices = **GET THIS FROM DATABASE**)
quantity = forms.ChoiceField(choices = **GET THIS FROM DATABASE**)
.
.
.
My view is like,
def getdrink():
if request.method == 'POST':
#code for handling form
drink = dform.cleaned_data['drink']
#code to get values from database
I have no idea how to generate or populate or append the values i get from the database to the choicefield in my form. I did try looking up on SO but none of the solutions here explained properly how to do it. Also, due to certain requirements I am not using the models. So my database is not at all related to the models.
I am at a total loss Please help me out
class MyForm(forms.Form):
my_choice_field = forms.ChoiceField(choices=MY_CHOICES)
So if you want the values to be dynamic(or dependent of some logic) you can simply modify your code to something like this:
either
def get_my_choices():
# you place some logic here
return choices_list
class MyForm(forms.Form):
my_choice_field = forms.ChoiceField(choices=get_my_choices())
or
User_list = [ #place logic here]
class MyForm(forms.Form):
my_choice_field = forms.ChoiceField(choices=get_my_choices())
but once database value is updated, new data value will be popoulated only on restart of server.
So write a function like this in forms:
class MyForm(forms.Form):
def __init__(self, *args, **kwargs):
super(MyForm, self).__init__(*args, **kwargs)
self.fields['my_choice_field'] = forms.ChoiceField( choices=get_my_choices() )
or in place of the get_my_choices u can ad the USER_LIST too.
If you have models for location and quantity, a ModelChoiceField should work:
class dform(forms.Form):
location = forms.ModelChoiceField(queryset = Location.objects.all())
Otherwise, you'll need to query the database directly, for example:
class dform(forms.Form):
location = forms.ChoiceField(choices = get_location_choices())
# elsewhere
from django.db import connection
def get_location_choices():
cursor = connection.cursor()
cursor.execute("select location_id, name from location_table")
return cursor.fetchall()
The SQL query to use here depends on your database engine and table schema.
I think that, based on my understanding of your question, the best solution would be to include JSON objects with your form and load these using jQuery instead of submitting the form over and over. Included in your form, you should add something like:
class MyForm(forms.Form):
CHOICE_DICT = {
'choice_1': [
'option_1',
'option_2',
],
etc...
Then you should include form.CHOICE_DICT in your context, load that with jQuery, and render it depending on changes to other fields.

Django CMS Plugin using Inline InclusionTag results in Orphaned Plugin

I don't know what I am doing wrong as I have followed the documentation. I'm thinking it is some little thing. Here is the scenario:
The plugin is a Text Slideshow plugin. It allows the admin the ability to add text that will cycle like a slideshow.
The models are as follows:
class TextSlideshow(CMSPlugin):
label = models.CharField(max_length=128)
interval = models.IntegerField(
default=5000,
help_text=_('milliseconds between slides. (1000 equals 1 second)'))
def copy_relations(self, oldinstance):
for slide in oldinstance.text_slides.all():
slide.pk = None
slide.id = None
slide.text_slide_show = self
slide.save()
def __unicode__(self):
return self.label
class TextSlide(CMSPlugin):
text_slide_show = models.ForeignKey(TextSlideshow, related_name="text_slides")
display_value = models.CharField(max_length=128)
index = models.IntegerField(verbose_name=_("Display order"))
The inline is:
class TextSlideInline(admin.StackedInline):
model = TextSlide
fk_name = 'text_slide_show'
The plugin is:
class TextSlideshowPlugin(CMSPluginBase):
model = TextSlideshow
name = _("Text Slideshow")
render_template = "text_slideshow.html"
inlines = [TextSlideInline,]
module = _("Slideshow")
def __init__(self, model=None, admin_site=None):
super(TextSlideshowPlugin, self).__init__(model=model,
admin_site=admin_site)
for inline in self.inlines:
inline.placeholder = self.placeholder
inline.page = self.page
def render(self, context, instance, placeholder):
slides = instance.text_slides.all().order_by('index')
context.update({
'model': instance,
'placeholder': placeholder,
'slides': slides
})
return context
plugin_pool.register_plugin(TextSlideshowPlugin)
The plugin works and will run flawless, but when the admin user adds text slides like so:
When I run ./manage.py cms list plugins
I get this result:
==== Plugin report ====
There are 2 plugin types in your database
ERROR : not installed
instance(s): 2
TextSlideshowPlugin
model : cmsslideshow.models.TextSlideshow
instance(s): 1
As long as i don't run ./manage.py cms delete_orphaned_plugins my slideshow will stay in tact and will work fine.
The text slideshow itself is fine, it's just the inline'd elements which are orphaned.
Please help.
After reviewing my code with a microscope several times while re-reading the documentation and many examples, I found my issue.
The issue is the child model should inherit from models.Model, not CMSPlugin
change:
class TextSlide(CMSPlugin):
to:
class TextSlide(models.Model):