Django unique URL redirection issue - php

Having issues trying to redirect after from submission to edit more fields
Also with creating the hyperlink to the submission.
When submitting my form with the redirect i get the error below.
If i submit the form with the render request to another page the form saves ok.
Request Method: POST Request
URL: http://127.0.0.1:8000/resourcelib/add_pricebook Django
Version: 1.8.4 Exception Type: NoReverseMatch Exception Value:
Reverse for 'detail_pricebook' with arguments '()' and keyword
arguments '{'p_id': 22L}' not found. 0 pattern(s) tried: []
My Model.py
class PriceBook(models.Model):
pricebook_id = models.AutoField(primary_key=True)
pricebook_name = models.CharField(max_length=255,verbose_name='PriceBook Name')
discription = models.TextField(verbose_name='Discription')
date_created = models.DateTimeField(auto_now_add=True, blank=True)
active = models.SmallIntegerField(max_length=1, blank=True)
def __unicode__(self):
return self.pricebook_name
view.py
def new_pricebook(request):
if request.method == "POST":
pricebook_form = PricebookForm(request.POST)
if pricebook_form.is_valid():
post = pricebook_form.save(commit=False)
post.save()
#return render(request, 'resourcelib/thanks.html',)
return redirect('detail_pricebook', p_id=post.pricebook_id)
else:
pricebook_form = PricebookForm()
return render(request, 'resourcelib/pricebook_add.html', {'pricebook_form': pricebook_form})
def detail_pricebook(request, p_id):
pricebook_from = get_object_or_404(PriceBook, pk=p_id)
return render(request, 'resourcelib/pricebook_detail.html', {'pricebook_from':pricebook_from})
url.py
url(r'^add_pricebook', views.new_pricebook, name='new_pricebook'),
url(r'^list_pricebook', views.list_pricebook, name='list_pricebook'),
url(r'^detail_pricebook/(?P<p_id>[0-9]+)/$', views.detail_pricebook, name='detail_pricebook'),
I don't believe it's in url file, because i get no errors if i browse to the entry eg.
127.0.0.1:8000/resourcelib/detail_pricebook/3/ - works ok
However i can't get my links working either, i can list my entries ok. But the link won't work from the code below when you click on the link it just comes up 127.0.0.1:8000/resourcelib/%7B%%20url%20'detail_pricebook'%20p_id.pk%7D
{% if pricebooks %}
<ul>
{% for pricebook in pricebooks %}
<li><h1>{{ pricebook.pricebook_name }}</h1></li>
{% endfor %}
</ul>
{% else %}
<p>No price books have been created.</p>
{% endif %}
{% endblock %}
Any help would be greatly appreciated

% missing in the url tag. Be more careful.

thanks #ozgur, have the the idea that i have the wrong reference for the pk. I was able to sort out the issue. I had a name name space on the primary project urls.py ... probably information i should have give, forgot I used cookiecutter for this one
url(r'^resourcelib/', include('oneworksite.resourcelib.urls', namespace='resource')),
so i was then able to get the link working with
{{ pricebook.pricebook_name }}
Then in my redirect i changed to
return redirect('resource:detail_pricebook', p_id=post.pk)

Related

timber/twig how to pass `posts` php-object to JavaScript? Some values are lost

When I'm trying to pass the information contained in {{posts}} I cannot retrieve all of it, at least not the post.link information
{% for post in posts %}
<script>
var t = JSON.parse('{{post|json_encode(constant('JSON_HEX_APOS'))|e('js')}}')
t.link = '{{post.link}}'
console.log(t)
</script>
{% endfor %}
Without manually adding the link, it doesn't show up
Why is this happening and how could I workaround this?
EDIT: related https://github.com/timber/timber/issues/1434
You shouldn’t encode your whole post object. You should encode all the values you need separately.
The link for your post doesn’t show up, because link is not a property, but a method of the Timber\Post object. This might be a little bit confusing, because in Twig we use {{ post.link }}. It looks like it’s a property or maybe an array item. But we could also use {{ post.link() }}, which is the same as {{ post.link }}. You can read more about this in the Variables section in Twig for Template Designers.
So what I would do is build a new array with the data you need and encode it to JSON in PHP with wp_json_encode().
PHP
$posts_json = [];
foreach ( $posts as $post ) {
$posts_json[] = wp_json_encode( [
'title' => $post->title(),
'link' => $post->link(),
] );
}
$context['posts_json'] = $posts_json;
By only adding the data you need, you keep the output in the frontend small. Otherwise, you would end up with a lot of data that you will never and that only increases the page size unnecessarily.
And then in Twig, you could do it like this:
{% for post in posts_json %}
<script>
var t = {{ post }}
console.log(t)
</script>
{% endfor %}

update twig for loop in ajax

I'm doing chatroom project, and trying to update user status with ajax.
the problem is that a user may have multiple friends, so first i use twig for loop to show all friends, like this, function getLastActivity() is to get user's last online time, if it is bigger than current time, then show the user is online.
{% for user in users%}
{% if app.user.name != user.getName() %}
<div id="status">
{% if getLastActivity(user.getId()) > date("now + 8 hours - 10 seconds") %}
<span class="online_icon"></span>
{% else %}
<span class="online_icon offline"></span>
{% endif %}
</div>
{% endif %}
{% endfor %}
i am not really good at ajax, if there is something strange please let me know. my idea is to update status field every 3 sec. but it can only update the first friend.
My guess is that because, in twig template i only write one time, so it didn't update the rest of the friends.
$(document).ready(function () {
setInterval(function(){
update_status();
}, 3000);
function update_status()
{
$.ajax({
success:function(){
$('#status').load(" #status");
}
})
}
})
i have inspired by this article, Change Twig Template variable with AJAX, but not sure how to implement this in my problem.
my question is, is it possible to use ajax to update all the friends status, or there is a better way to achieve this.
thanks
The problem you have is that you create an element for each user with the ID status. An ID is a unique identifier, yet you use the same for each element.
What you could do is, for example, create the element with the id based on the user obj:
{% for user in users%}
{% if app.user.name != user.getName() %}
<div id="status-{{ user.id }}">
{* ... *}
</div>
{% endif %}
{% endfor %}
I don't know what exactly your update_status() function looks like, but you will need to get the user ID somehow. You can either return it in for the ajax, like so:
$.ajax({
success: function(userId){
$('#status-' + userId).load(" #status");
}
})
or you loop over all elements and you will have the id using el.attr('id').

ezplatform render links with url and object name from multi-relational content item in content type

does anyone know now to create a custom view type for ez platform? The default 3 have been exhausted and we need a new one for 'link'
Alternatively, does anyone know how to use the render( controller( with a custom template as this would also resolve out block right now.
Basically, we have a multi-relational field in a content object used and we need to print links to all the related contentIds, path works great but we cannot find a way to extract the name of the content object for the link without doing some fairly funky tpl logic of passing in params.
EG: As a hack for now we can pass in "embed_type" as a custom param with the render(controller("ez_content:viewAction" to pull in an alternate view for the content object for a specific content type and view type.
{% if embed_type is defined %}
{% include "embed/#{embed_type}.html.twig" %}
{% else %}
<h1>{{ ez_field_value( content, 'name') }}</h1>
{% endif %}
However, this is very ugly and all we really want to do is use 1 template for all content types, so all we need to do is loop through the relational field and print links (as the only thing available in the content field: "destination ids"). I am sure there used to be this option in the docs but i cannot find it anymore eg:
{% set links = ez_field_value( footer, "first_links_row" ).destinationContentIds%}
{% for id in links %}
{{ render(controller("ez_content:viewAction", {"contentId": id, "template": "link.html.twig"})) }}
{% endfor %}
Where the link.html.twig would simple print the link:
<a href="{{ path( "ez_urlalias", {"contentId": id} ) }}">
{{ ez_field_value( content, "name" ) }}
</a>
If using a custom tpl is not possible with the render (controller ( helper then a new custom view type would also fix this issue, but i cannot find documentation for either.
You can create a twig function that would do that. We have something like this:
Definition:
new Twig_SimpleFunction(
'content_name',
array($this, 'getContentName')
),
Implementation:
public function getContentName($content, $forcedLanguage = null)
{
if (!$content instanceof Content && !$content instanceof ContentInfo) {
$contentInfo = $this->repository->getContentService()->loadContentInfo($content);
} elseif ($content instanceof Content) {
$contentInfo = $content->contentInfo;
} else {
$contentInfo = $content;
}
return $this->translationHelper->getTranslatedContentNameByContentInfo($contentInfo, $forcedLanguage);
}
which enables you to provide either content id, content info or content itself, and it returns translated content name

Notifications on a new Route or with parameters?

easy simple question.
I made a register form. When you press the submit button the Controller handles the request and renders.
if($form->isSubmitted && $form->isValid()) {
return $this->render('x/register.html.twig', array(
'options' => 'userCreated',
'userName' => $user->getUsername()); }
in the .html.twig
{% if options=="userCreated" %}
user {{userName}} was successfully inserted into the database
{% else %}
//show the form
{% endif %}
This worked perfect but my "teacher" told me, that I have to do this more dynamic.
I did a new "Info.html.twig" now with 2 parameters (redirectUrl, redirectText) e.g.
$redirectUrl="/home"; $redirectText="Go to the home page"
in HTML
{{redirectText}}
and if there is a message at the top I use the flashMessage method ($this->addFlash).
Is that a good method or is there a way to get way more dynamical than this?

twig: create custom tag that calls a functions

SETUP:
Twig 1.13.1
PHP 5.4.3
PROBLEM:
I am needing help setting up a custom tag that calls a function that i have already built...
Current Code:
Template Code
{% set stories = get_latest_stories(2, sports) %}
{% for story in stories %}
{{ story.headline }} <br>
{% endfor %}
Controller
$function = new Twig_SimpleFunction('getViewStories', function (section, limit) {
return news_stories::getStories(section,limit);
});
$twig->addFunction($function);
$twig->render("storyList.html");
GOAL:
No with that said I would like to use a custom tag like
{% get_latest_stories 2 sports %}
to call the same function as above. The new way looks nicer and is easier to follow
Why not fetch your stories in the controller instead of the template? This does not seem like a job for the view layer...
So, something like this:
$twig->render("storyList.html", array(
'stories' => news_stories::getStories($section, $limit)
));
Then, you'll have a stories variable available in your template.
here is simple example how to write twig extension
Following code is taken from my unfinished project
function file_import($value){
//some code here
return $value;
}
$app['twig']->addFunction('file_import', new Twig_Function_Function('file_import'));
usage
{{ file_import('value') }}

Categories