how can I change the order of the values in the ModelChoiceField billing_company?
models.py
class Company(models.Model):
name = models.CharField(max_length=30, unique=True)
forms.py
billing_company = forms.ModelChoiceField(Company.objects, required=True)
Thanks for your help.
Tom
ModelChoiceField takes a QuerySet as its first parameter, so you should be able to pass an ordered set:
forms.ModelChoiceField(Company.objects.order_by('-pk'), required=True)
If you want to sort it in the template, you can manually render the form and iterate over the options and sort them using the dictsort templatetag (or any other templatetag that sorts according to what you like), e.g.
{% for value, option in form.fields.billing_company.choices|dictsort:1 %}
<option value="{{ value }}">{{ option }}</option>
{% endfor %}
Related
This my first time to use OctoberCMS, and they provide the Builder Plugin in order to help the developer builds plugin in minutes.
I try to use this plugin to show the data on the front end especially when using Components > Builder > Record list, but the documentation didn't give enough example to get data from some fields. The example on the internet is just show how to get the data from one field.
My code is shown below:
[builderList]
modelClass = "Budiprasetyo\Employees\Models\Employee"
scope = "-"
displayColumn = "name"
noRecordsMessage = "No records found"
detailsPage = "-"
detailsUrlParameter = "id"
pageNumber = "{{ :page }}"
in my case, I want to get the data not only "name" field, but I also want to add "email", "facebook" fields.
I have tried to make it into:
displayColumn = "name", "email", "facebook"
but it returns no data shown and I have tried to make it into array:
displayColumn = ["name", "email", "facebook"]
and it's the same result, no data is shown.
I appreciate any helps, thank you.
Actually I don't like to use plugins' components. Sometimes it doesn't retrieve any data. I don't know why maybe it's just because of wrong using.
Anyway, The best way to retrieve the data from your plugin is to navigate to the code section and then write onStart() function and start to retrieve to data.
function onStart()
{
$data = \Authorname\Pluginname\Models\Model::find(1);
$this['data'] = $data;
}
And this way you'll have a data variable in the markup section.
On the frontend cms page, you need to replace the component call with your custom partial. Your partial file should look something like this:
*podcastList is the component name
{% set records =podcastList.records %}
{% set displayColumn =podcastList.displayColumn %}
{% set noRecordsMessage =podcastList.noRecordsMessage %}
{% set detailsPage =podcastList.detailsPage %}
{% set detailsKeyColumn =podcastList.detailsKeyColumn %}
{% set detailsUrlParameter =podcastList.detailsUrlParameter %}
{% for record in records %}
<span class="date">{{ attribute(record, 'date') }}</span>
<span class="title">{{ attribute(record, 'title') }}</span>
<p>{{ attribute(record, 'description') }}</p>
{% endfor %}
Obviously, this is simplified version, but you get the point. You can easily define more columns without touching the page component settings.
I am creating an example to learn more about using inline formsets with SessionWizard. Eventually, I want to integrate dynamic formsets in order to add and delete individual forms via the template before submitting. However, when data is absent from the second form, it fails to validate unlike like a regular ModelForm.
Is there a method within SessionWizard that needs to be overridden? Is it something that is inherently handled within Django?
Guidance and examples would be greatly appreciated.
models.py
class Parent(models.Model):
name = models.CharField(max_length=256)
def __unicode__(self):
return name
class Child(models.Model):
name = models.CharField(max_length=256)
parent = models.ForeignKey(Parent)
def __unicode__(self):
return name
urls.py
test_forms = [['parent', ParentForm],['child', ChildFormSet]]
urlpatterns = patterns('example.views',
url(r'^$', TestWizard.as_view(test_forms)),
)
forms.py
class ParentForm(ModelForm):
class Meta:
model = Parent
class ChildForm(ModelForm):
class Meta:
model = Child
exclude = ('parent',)
ChildFormSet = inlineformset_factory(Parent, Child, extra=1)
class TestWizard(SessionWizardView):
"""
This WizardView is used to create multi-page forms and handles all the
storage and validation stuff using sessions.
"""
#template_name = ''
# def get_template_names(self):
# """
# Returns a list of template names to be used for the request.
# Overridden TemplateResponseMixin for specifying template for step.
# """
# return 'survey/forms/wizard_form.html'
#
# def get_context_data(self, form, **kwargs):
# context = super(TestWizard, self).get_context_data(form=form, **kwargs)
# return context
#
# def get_form_initial(self, step):
# """
# Returns dict (list of key, values) for initial form data.
# Useful for populating form fields with data from prior form, with extra
# logic for dealing with formsets.
# """
# return self.initial_dict.get(step, {})
#
# def get_form(self, step=None, data=None, files=None):
# """
# Constructs the form for a given step - overridden to add extra arguments
# """
# form = super(TestWizard, self).get_form(step, data, files)
# return form
def done(self, form_list, **kwargs):
return render_to_response('survey/thanks.html', {
'form_data': [form.cleaned_data for form in form_list],
})
wizard-form.html
{% extends "base.html" %}
{% load i18n %}
{% block head %}
{{ wizard.form.media }}
{% endblock %}
{% block content %}
<p>DEFAULT WIZARD FORM Step {{ wizard.steps.step1 }} of {{ wizard.steps.count }}</p>
<form action="" method="post">{% csrf_token %}
<table>
{{ wizard.management_form }}
{% if wizard.form.forms %}
{{ wizard.form.management_form }}
{% for form in wizard.form.forms %}
{{ form }}
{% endfor %}
{% else %}
{{ wizard.form }}
{% endif %}
</table>
{% if wizard.steps.prev %}
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.first }}">{% trans "first step" %}</button>
<button name="wizard_goto_step" type="submit" value="{{ wizard.steps.prev }}">{% trans "prev step" %}</button>
{% endif %}
<input type="submit" value="{% trans "submit" %}"/>
</form>
{% endblock %}
I sometimes will add model methods like so:
class Company(models.Model):
name = CharField(length=64)
#classmethod
def dropdown(cls, classes="" id_prefix=""):
"""
Prints out a select box with every company
"""
if id_prefix:
id_prefix = id_prefix + '_'
t = Template("""
<select class="{{ classes }}" id="{{ id_prefix }}company_id">
{% for company in companies %}
<option value="{{ company.id }}">{{ company.name }}</option>
{% endfor %}
</select>
""")
companies = cls.objects.all()
c = {'companies': companies, 'classes': classes, 'id_prefix': id_prefix}
return t.render(c)
A lot of my coworkers tell me that this is wrong because outputting HTML is something that should always be done in the view, but my thinking is that since it's just a single HTML element, it's OK.
It doesn't matter whether it's a single < or a whole page; the model is supposed to return display neutral data. How that data is displayed is entirely the job of the view. Just think about alternative views. What if you want to make an API that receives and returns JSON? You'll still use the same model to manipulate the data, but there's no HTML involved whatsoever. So what is the HTML specific method doing in the model?
I have a quite simple doctrine entity that represent a news ; this news can be linked with many pictures, so I decided to use a Doctrine Collection. The thing is, I want to retrieve this pictures and display them in my template... But it didn't seem to work. Do you know how I can do that ?
Here is what I tried :
{% for annonce in annonces %}
<div class="annonce_item">
{% for photo in annonce.photo %}
<img src="{{ photo.path }}" alt="" />
{% endfor %}
</div>
<!-- End .annonce_item -->
{% endfor %}
annonce is the news class, and photo is the collection :
/**
* #ORM\OneToMany(targetEntity="Photo", mappedBy="id",cascade={"persist"})
*/
private $photo;
When I try to display this page in my browser, I get this exception:
An exception has been thrown during the rendering of a template ("Notice: Undefined index: >id in >/Applications/MAMP/htdocs/ApacheImmobilier/vendor/doctrine/lib/Doctrine/ORM/Persisters/Basi>cEntityPersister.php line 1274") in "APPagesBundle:Index:index.html.twig" at line 45.
Thanks!
Read this article of the doc. It says:
The mappedBy attribute designates the field in the entity that is the
owner of the relationship.
which, in your case, must be the news field of your Photo entity.
I am trying to implement an ajax view to create an object and then return it and insert it into the template. It is almost working except I cannot seem to get render_to_string() to work to render the html to insert. The object is being created and html is being returned and inserted into the template however the variables are not included in the html. My view is below.
def tr_create_xhr(request, person, slug):
if request.method == "POST":
form = TopicResourceForm(request.POST)
if form.is_valid():
try:
r = Resource.objects.get(url=form.cleaned_data['resource'])
except Resource.DoesNotExist:
r = Resource.objects.create(url=form.cleaned_data['resource'], rtype=form.cleaned_data['rtype'])
r.save()
obj = form.save(commit=False)
obj.resource = r
try:
topic = Topic.objects.get(person__user=request.user, slug__iexact=slug)
except Topic.DoesNotExist:
return Http404
obj.topic = topic
objs = obj.save()
html = render_to_string('includes/tr_inc.html',{"r":objs, "topic":topic})
res = {'html':html}
if request.is_ajax():
return HttpResponse(simplejson.dumps(res), mimetype="application/json")
else:
return HttpResponseRedirect("../..")
return Http404
This is the template "includes/tr_inc.html":
{% load markup %}
{% load people_tags %}
<li>
<h5>{{ r.title }}</h5>
<p><a class="tru" href={{ r.resource.url }}>{{ r.resource.url|sliceit:70 }}</a></p>
<span class="oc"><p>Added {{ r.added }}{% if r.rtype %} |<a href={% url resource_type_detail r.rtype.slug %}>{{ r.rtype }}</a>{% endif %}
| Delete Edit
{{ r.note|markdown }}</span>
</li>
The html string that is returned is the template without any variables inserted.
Model method 'save' doesn't return an object. So you 'objs' variable is empty. You should write
html = render_to_string('includes/tr_inc.html',{"r":obj, "topic":topic})
I had exact the same problem today. It is quite easy. Please check the Django document for this method, there is actually a third optional parameter: context_instance=RequestContext(request). Therefore your render_to_string should be like this:
html = render_to_string(
'includes/tr_inc.html',{"r":obj, "topic":topic},
context_instance=RequestContext(request))
Then everything should work properly.