django url pattern matching to display different pages [closed] - django

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I'm new to django and I'm kinda confused on how to use django's url pattern matching.
This is my intention. I have 4 pages to a website. Depending on the links, they would use the url to find what information to present to the user. Also the url knows which page the user is on.
So the person would choose a building based on links.
The person would then choose the floor they wish to go on.
Finally the person would then choose a room.
Ex. format: aaa.com/buildingname/floornumber/roomnumber
step0 aaa.com/
step1 aaa.com/django/
step2 aaa.com/django/2/
step3 aaa.com/django/2/201
So based on the url pattern, the website should load up differently every time.
Is this how I am supposed to use url pattern matching? I really would like to get some help on this. What should the url pattern look like? As of right now all I can think of is just matching the url into different apps that have views. I just don't know how to link them all together.
And I have a MySQL database with the building,floor,and room number.
Thanks in advance everybody. I appreciate your effort.

Define url pattern pointing to different views as follows:
urlpatterns = patterns('your_app.views',
(r'^/(?P<building_name>\w+)/$','function1'),
(r'^/(?P<building_name>\w+)/(?P<floor>\d+)/$','function2'),
(r'^/(?P<building_name>\w+)/(?P<floor>\d+)/(?P<room>\d+)/$','function3'),
)
Use this pattern and it will call different views and in each view you can use different template. Or if you want to use same view function check for available values in URL and render whichever template you need. You can get the URL value in views as follows:
def function1(request, building_name = None):
print building_name
Likewise do it for other views also.

If you want them to be handled in the same view , you can pass arguments to the same view,
r('/(?P<building>\w+)/','views.view1')
r('/(?P<building>\w+)/(?P<flat>\w+)/','views.view1')
r('/(?P<building>\w+)/(?P<flat>\w+)/(?P<room>\w+)/','views.view1')
your view,
def view1(buidling="",flat="",room=""):
return []

Related

Proper way to change language on website? [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 4 years ago.
Improve this question
I'm doing a website and would like to include language change. What is the proper way to handle this ? Just copy html's, rename and translate them and change links ? Or is there a better way ? I'm using django.
Edit:
Here are some good tutorials for anyone interested:
Documentation: https://docs.djangoproject.com/en/2.1/topics/i18n/translation/
Easy start: https://phraseapp.com/blog/posts/quick-guide-django-i18n/
Django offers settings to automatically update language options:
https://docs.djangoproject.com/en/2.1/ref/settings/
Django also has a full page on Internationalization (i.e. I18N) and Localization (i.e. L10N):
https://docs.djangoproject.com/en/2.1/topics/i18n/
Several topics are covered, one of which is:
Translation of Text
You will need to update your template files if they are not properly configured for translation:
from django.http import HttpResponse
from django.utils.translation import gettext
def my_view(request):
output = gettext("Welcome to my site.")
return HttpResponse(output)
I suggest you take a look at the option of using google translate to automatically translate your website to every lang https://translate.google.com/manager/website/.
Another option is to add a lang attribute to every text, and having all text a few times for etch lang. then using a javascript script to detect the user's lang like this :
navigator.userLanguage
and removing all text that don't have the right lang attribute.

One form across two pages django [closed]

Closed. This question needs to be more focused. It is not currently accepting answers.
Want to improve this question? Update the question so it focuses on one problem only by editing this post.
Closed 6 years ago.
Improve this question
I want to create a form that does the following: the user specifies the number of questions that they want to ask and then on the next page, the user is able to fill out the relevant details pertaining to the number of questions that they to ask. I was wondering if there is a simple way to do this using django forms?
My approach is as follows:
I use one form to record the number of questions that the user wants to ask with a general description, then when the user clicks submit/next, the next view would create a form with those number of questions; however, I'm running into a complication when trying to use this method. I want to link the first form to the second form, but not sure how to because I can't preserve any information in the view from each call.
Is there a better way of going about this problem?
You certainly can preserve information between views. Perhaps the easiest way to do this is in URL parameters; your first view can redirect to "/second_view/?number_of_questions=5" and the second view can access request.GET['number_of_questions'].
An alternative, which is particularly useful if you have a lot of data, would be to use the session; add the data to the session on submit in the first view, and pop it out in the second.
In Django 1.8, the django.contrib.formtools module was moved into a separate package, django-formtools. It includes the FormWizard, which is the standard tool you'd use to create a form that spans multiple pages and/or steps.

How could I allow copy editors for my Django site to create internal links in a DRY manner? [closed]

Closed. This question is off-topic. It is not currently accepting answers.
Want to improve this question? Update the question so it's on-topic for Stack Overflow.
Closed 10 years ago.
Improve this question
My Django site is an ecommerce store. Relatively nontechnical copy editors will be logging into the Django admin interface and writing the copy for each of the product pages. They have told me that they want to be able to create links in this copy to other pages on the site. For example, if a product references another product in its description, they want to link between the pages.
I see a couple of possible options:
They simply hardcode the urls in <a> tags in the copy. I've set up ckeditor for the admin textareas so this would be the simplest solution, but if the url structure of the site ever changed, (say we changed them for SEO purposes) all the links would break.
Introduce some sort of wiki syntax where they surround the text that they want the links to be in square brackets. Something like:
Widget A works really well with [[Widget B]]. It is good.
would produce:
Widget A works really well with Widget B. It is good.
Then you have the problem of what happens if the product's name changes?
Has anyone dealt with this problem before and come up with a solution that is flexible enough to allow changing links/names/etc?
I deal with this issue frequently. Ultimately, you have to be very persuasive to convince me to allow embedding links directly into the copy--especially with an e-commerce website.
What if the product name changes or is re-branded?
What if the product is discontinued... you don't want 404 errors from your internal links.
Do you really want to lead people away from your "add to cart" call to action that high up on the page?
Do they know your SEO strategy? Are they going to dilute your links? What verbiage will they use? Will they ensure the link is valid?
When I am asked to give copy/product development team the ability to add links I always start with a No. Ask them what they need them for, explain the problems that can arise (eg. extra cost in maintaining valid links, conversion rate considerations, SEO considerations), and offer alternative solutions.
For example, I usually offer the ability to allow them to associate products with products as "Associated Products", "Related Products", "Accessories", "More Information" etc. You can have these in tabs or lists at the bottom of the product page. These would be in models and thus you have control over not displaying discontinued products, the link names are the product names (which you have SEO control over), etc. Determine if they are going for cross-selling, up-selling, or providing the end user with more information.
As a last resort I have also used a custom code parser which is again based on the target object and not a hard-coded link. For example, let's say you give them the ability to do:
Widget A works really well with [product=123].
A custom template tag, parser in your model/view can replace that with a link to the the Product with id=123 (or use slug) based on get_absolute_url(). If the product is discontinued, the name can still show but no link. This only works if you have a policy of never deleting records. Even then, you may have to have some error handling for when they enter an invalid product ID or somebody does delete that product. That will happen.

how can i get a next form/page while submitting a form?

i am working with a django quiz application where one question per page. when i will answer one question selecting a radio button and click submit button how can i get the next question in the next page as well as the answer will submitted to database. If anyone help me it would be an outstanding solution for me. please
Thanks for the answer , would you please i need bit specific answer. I wrote a view to get the question and render the answer in the radio link . but when i submit the answer how can i map the url to get dynamically new question each. thank you so much.
You need to write a view to handle your request. You need to edit urls.py to map your quiz url to the function in views.py (for your quiz app). So when a request with that quiz url comes Django applies that view function. So basically what this view does is this -
Get the answer & store it to DB. The DB details you need to define in models.py
Get the next question from DB (or wherever you store your questions).
Have a template (for quiz questions) with place holders for quiz question.
Form the new url & fill your template.
Redirect the user to the new url.
That does it. If you need any specifics lemme know.

Best Practices: How to best implement Rating-Stars in Django Templates [closed]

As it currently stands, this question is not a good fit for our Q&A format. We expect answers to be supported by facts, references, or expertise, but this question will likely solicit debate, arguments, polling, or extended discussion. If you feel that this question can be improved and possibly reopened, visit the help center for guidance.
Closed 10 years ago.
I would like to have reusable ratings (typical layout with 5 stars).
I have found this http://www.thebroth.com/blog/119/css-rating-stars that explains how to display this using css.
For actually collecting the rating I was thinking of using an image map or maybe simple radio buttons.
I would like to use this on various different models.
How would you do this?
Shall I create a widget or can I do this with a template?
Actually I was pretty surprised not to find anything on this on the web. Is it that simple, or uncommon?
If received some interesting answers on the django-users mailing list:
by Mike:
Well you can create a widget, I like a seperate rating model myself. That
collects the value and then adds that to a total and creates a score or
average. The model stores the total votes and the total score, which I divide
and get my average, (I do the math in the view). Adding it to other models
with a foreign key relation. Enforcing that users vote only once is rarely
enforced outside of the current session or cookie lifetime. If you want it
persistance, I'm notfgv6gw33TT sure off the top of my head what is best for
this, but would require only registered users vote.
Now, you just display the rating form, I would do it as a template inclusion
tag and put the tag in my templates. This tag has the basic submit form, the
form it's self is two fields, with a select box (I went simple this way) and a
hidden field labeled next that points back to this page, that I can redirect
to. When the user submits, in my views to handle the forms action, I just
increment the votes and total score and redirect back to the page the vote was
taken on. This is using the traditional submit button, posting the form to a
url, returning a full view.
If you do something with javascript that illuminates the number of stars for
the rating and click on the stars to submit, here you might want to post it as
json object using xhr request, update the view and return a json object with
the updated rating values, if it's a 200, update the page with the new values
after voting (returned with the 200). If it's a 500, deal with the error,
letting the user know, there was a problem voting and reset the stars.
This is what I do, or would do in your position, if anyone has a better idea,
please speak up.
Hope this helps.
Mike
by Ethan:
I actually just did 5-star ratings for a project I'm working on, and have
been trying to figure out if I have anything reusable worth releasing as a
package (and trying to find the time to figure that out..) I'll outline
what I did and what I used to do it.
I used django-ratings[1,2] for the backend and hooked up its RatingField to
my rateable models.
I like jQuery, so for the frontend I used the jquery-star-rating plugin[3,4]
as a base. It turns a collection of radio buttons into a star widget. I
haven't looked closely at the implementation but I think it's basically
using the same CSS technique described in your link. To get started you
just need to include its JS and CSS and add class="star" to the radio
buttons in your form.
I then just wrote some view code that sends the request data from the radio
buttons to django-ratings. Super simple stuff, just used the django-ratings
RatingManager API and handled the exceptions it throws -- I've pasted the
snippet from my code at [5]. (I'm using a somewhat old version of
django-ratings b/c I haven't had the time to upgrade; it might look a little
different now, I'm not sure.)
Finally, I wanted two more things:
1) If a user has already rated an item and views the "rate this item" form
again, the "star widget" should be preset with the user's previous rating,
instead of just showing five blank stars. I realized the easiest way to do
this was from the client side: an onload event that simulates the user
clicking on the star he already clicked on. My view and template code for
that is at [6]; I just figured out the HTML formats that jquery-star-rating
sets and expects, and clicked on the appropriate star for the user's
existing rating.
2) When viewing the item, users' ratings should show up as non-interactive
stars, instead of as numbers. I wrote a dumb-as-nails template filter
designed to take a number (the rating) and return a bunch of star images.
Again, I just used the HTML formatting and CSS classes from
jquery-star-rating. My code for this is at [7].
I was thinking it'd be neat to put some of this in a django-form Field that
renders the radio buttons and triggers jquery-star-rating all in one go, and
handles the submission to the django-ratings backend. But I haven't had a
chance to figure that out yet.
Anyway, hope this helps,
Ethan
1 http://github.com/dcramer/django-ratings
[2] http://pypi.python.org/pypi/django-ratings
[3] http://www.fyneworks.com/jquery/star-rating/
[4] http://code.google.com/p/jquery-star-rating-plugin/
[5] http://pastebin.ca/1650596
[6] http://pastebin.ca/1650609
[7] http://pastebin.ca/1650616
There is a django-ratings app on PyPi. It can give you the rating as a percent 'myinstance.rating.get_percent()' to use in your template for the inner div width in the CSS trick you mentioned.