Tanaka Ryuu

Tanaka Ryuu


Creating sitemap of Dynamic URLs in your Django Application

A site map can be a hierarchical list of pages, an organization chart, or an XML document that provides instructions to search engine crawl bots.

Why sitemaps are required:

XML Sitemaps are important for SEO because they make it easier for Google to find your site’s pages—this is important because Google ranks web PAGES, not just websites. There is no downside of having an XML Sitemap and having one can improve your SEO, so we highly recommend them.


The sitemap for this blog can be found at http://thepythondjango.com/sitemap_index.xml .

Steps to add Sitemaps to your Django Application:

Create a file sitemap.py in your app.

Create two different classes in sitemap.py file, one for static pages and another for Dynamic URLs.

Let’s assume your website sell some product where product details are stored in the database. Once a new product is added to the database, you want that product page to be searchable by search engines. We need to add all such product pages/URLs to sitemaps.

Static Sitemap:

Define a class StaticSitemap in your sitemap.py file. Define the mandatory function items in it which will return the list of objects.

These objects will be passed to the location method which will create URL from these objects.

from django.contrib.sitemaps import Sitemap
from django.core.urlresolvers import reverse

class StaticSitemap(Sitemap):

    def items(self):
        return [

    def location(self, item):
        return reverse(item)

Here in items function, we are returning appname:url_name which will be used by location method to convert into an absolute URL.

Refer you app’s urls.py file for URL names.

Dynamic Sitemap:

Similarly, we will create Dynamic sitemap by fetching values from DB.

from mystore.models import ProductDetailsModel

class ProductSitemap(Sitemap):

    def items(self):
        return ProductDetailsModel.objects.all()

    def location(self, item):
        return reverse('myapp:product', args=[item.product_id])

Here we are getting all products from the database and generating URLs like http:example.com/product/12.

Adding sitemaps in URLconf:

Now add these sitemap class in URLconf. Edit the project’s urls.py file and add below code in it.

from mystore.sitemap import  StaticSitemap, ProductSitemap
from django.contrib.sitemaps.views import sitemap

sitemaps = {
 'pages': StaticSitemap,
 'products': ProductSitemap,

urlpatterns += [
Now reload your server and go to ```localhost:8000/sitemap.xml``` and you will be able to see your sitemap there.  

*Originally published **** ****at *[***pythoncircle.com***](https://www.pythoncircle.com/post/584/creating-sitemap-of-dynamic-urls-in-your-django-application/ "***pythoncircle.com***")


Thanks for reading :heart: If you liked this post, share it with all of your programming buddies! Follow me on [**Facebook**](https://www.facebook.com/Pythontutorial4u "**Facebook**") | [**Twitter**](https://twitter.com/codek_tv "**Twitter**")
## Learn More

☞ [Complete Python Bootcamp: Go from zero to hero in Python 3](http://learnstartup.net/p/S15_M7e-l "Complete Python Bootcamp: Go from zero to hero in Python 3")

☞ [Python and Django Full Stack Web Developer Bootcamp](http://academy.learnstartup.net/p/r1-quFMgce "Python and Django Full Stack Web Developer Bootcamp")

☞ [Python for Time Series Data Analysis](http://learnstartup.net/p/OqjO6VL2y "Python for Time Series Data Analysis")

☞ [Python Programming For Beginners From Scratch](http://learnstartup.net/p/d3qnutpk4 "Python Programming For Beginners From Scratch")

☞ [Python Network Programming | Network Apps & Hacking Tools](http://learnstartup.net/p/QRQDxXvpZ "Python Network Programming | Network Apps & Hacking Tools")

☞ [Intro To SQLite Databases for Python Programming](http://learnstartup.net/p/7u6CWaas2 "Intro To SQLite Databases for Python Programming")

☞ [Ethical Hacking With Python, JavaScript and Kali Linux](http://learnstartup.net/p/aRaBXiAoZ "Ethical Hacking With Python, JavaScript and Kali Linux")

☞ [Beginner’s guide on Python: Learn python from scratch! (New)](http://learnstartup.net/p/szT1QzYPf "Beginner’s guide on Python: Learn python from scratch! (New)")

☞ [Python for Beginners: Complete Python Programming](http://learnstartup.net/p/LMc19YJl6 "Python for Beginners: Complete Python Programming")

☞ [Django 2.1 & Python | The Ultimate Web Development Bootcamp](http://academy.learnstartup.net/p/rJmJxyM9M "Django 2.1 & Python | The Ultimate Web Development Bootcamp")

☞ [Python eCommerce | Build a Django eCommerce Web Application](http://academy.learnstartup.net/p/H19Qb1nkf "Python eCommerce | Build a Django eCommerce Web Application")

☞ [Python Django Dev To Deployment](http://academy.learnstartup.net/p/9yr7V_-O8 "Python Django Dev To Deployment")
, sitemap, {'sitemaps': sitemaps})

Now reload your server and go to localhost:8000/sitemap.xml and you will be able to see your sitemap there.

#python #django #web-development

What is GEEK

Buddha Community

Creating sitemap of Dynamic URLs in your Django Application
Easter  Deckow

Easter Deckow


PyTumblr: A Python Tumblr API v2 Client



Install via pip:

$ pip install pytumblr

Install from source:

$ git clone https://github.com/tumblr/pytumblr.git
$ cd pytumblr
$ python setup.py install


Create a client

A pytumblr.TumblrRestClient is the object you'll make all of your calls to the Tumblr API through. Creating one is this easy:

client = pytumblr.TumblrRestClient(

client.info() # Grabs the current user information

Two easy ways to get your credentials to are:

  1. The built-in interactive_console.py tool (if you already have a consumer key & secret)
  2. The Tumblr API console at https://api.tumblr.com/console
  3. Get sample login code at https://api.tumblr.com/console/calls/user/info

Supported Methods

User Methods

client.info() # get information about the authenticating user
client.dashboard() # get the dashboard for the authenticating user
client.likes() # get the likes for the authenticating user
client.following() # get the blogs followed by the authenticating user

client.follow('codingjester.tumblr.com') # follow a blog
client.unfollow('codingjester.tumblr.com') # unfollow a blog

client.like(id, reblogkey) # like a post
client.unlike(id, reblogkey) # unlike a post

Blog Methods

client.blog_info(blogName) # get information about a blog
client.posts(blogName, **params) # get posts for a blog
client.avatar(blogName) # get the avatar for a blog
client.blog_likes(blogName) # get the likes on a blog
client.followers(blogName) # get the followers of a blog
client.blog_following(blogName) # get the publicly exposed blogs that [blogName] follows
client.queue(blogName) # get the queue for a given blog
client.submission(blogName) # get the submissions for a given blog

Post Methods

Creating posts

PyTumblr lets you create all of the various types that Tumblr supports. When using these types there are a few defaults that are able to be used with any post type.

The default supported types are described below.

  • state - a string, the state of the post. Supported types are published, draft, queue, private
  • tags - a list, a list of strings that you want tagged on the post. eg: ["testing", "magic", "1"]
  • tweet - a string, the string of the customized tweet you want. eg: "Man I love my mega awesome post!"
  • date - a string, the customized GMT that you want
  • format - a string, the format that your post is in. Support types are html or markdown
  • slug - a string, the slug for the url of the post you want

We'll show examples throughout of these default examples while showcasing all the specific post types.

Creating a photo post

Creating a photo post supports a bunch of different options plus the described default options * caption - a string, the user supplied caption * link - a string, the "click-through" url for the photo * source - a string, the url for the photo you want to use (use this or the data parameter) * data - a list or string, a list of filepaths or a single file path for multipart file upload

#Creates a photo post using a source URL
client.create_photo(blogName, state="published", tags=["testing", "ok"],

#Creates a photo post using a local filepath
client.create_photo(blogName, state="queue", tags=["testing", "ok"],
                    tweet="Woah this is an incredible sweet post [URL]",

#Creates a photoset post using several local filepaths
client.create_photo(blogName, state="draft", tags=["jb is cool"], format="markdown",
                    data=["/Users/johnb/path/to/my/image.jpg", "/Users/johnb/Pictures/kittens.jpg"],
                    caption="## Mega sweet kittens")

Creating a text post

Creating a text post supports the same options as default and just a two other parameters * title - a string, the optional title for the post. Supports markdown or html * body - a string, the body of the of the post. Supports markdown or html

#Creating a text post
client.create_text(blogName, state="published", slug="testing-text-posts", title="Testing", body="testing1 2 3 4")

Creating a quote post

Creating a quote post supports the same options as default and two other parameter * quote - a string, the full text of the qote. Supports markdown or html * source - a string, the cited source. HTML supported

#Creating a quote post
client.create_quote(blogName, state="queue", quote="I am the Walrus", source="Ringo")

Creating a link post

  • title - a string, the title of post that you want. Supports HTML entities.
  • url - a string, the url that you want to create a link post for.
  • description - a string, the desciption of the link that you have
#Create a link post
client.create_link(blogName, title="I like to search things, you should too.", url="https://duckduckgo.com",
                   description="Search is pretty cool when a duck does it.")

Creating a chat post

Creating a chat post supports the same options as default and two other parameters * title - a string, the title of the chat post * conversation - a string, the text of the conversation/chat, with diablog labels (no html)

#Create a chat post
chat = """John: Testing can be fun!
Renee: Testing is tedious and so are you.
John: Aw.
client.create_chat(blogName, title="Renee just doesn't understand.", conversation=chat, tags=["renee", "testing"])

Creating an audio post

Creating an audio post allows for all default options and a has 3 other parameters. The only thing to keep in mind while dealing with audio posts is to make sure that you use the external_url parameter or data. You cannot use both at the same time. * caption - a string, the caption for your post * external_url - a string, the url of the site that hosts the audio file * data - a string, the filepath of the audio file you want to upload to Tumblr

#Creating an audio file
client.create_audio(blogName, caption="Rock out.", data="/Users/johnb/Music/my/new/sweet/album.mp3")

#lets use soundcloud!
client.create_audio(blogName, caption="Mega rock out.", external_url="https://soundcloud.com/skrillex/sets/recess")

Creating a video post

Creating a video post allows for all default options and has three other options. Like the other post types, it has some restrictions. You cannot use the embed and data parameters at the same time. * caption - a string, the caption for your post * embed - a string, the HTML embed code for the video * data - a string, the path of the file you want to upload

#Creating an upload from YouTube
client.create_video(blogName, caption="Jon Snow. Mega ridiculous sword.",

#Creating a video post from local file
client.create_video(blogName, caption="testing", data="/Users/johnb/testing/ok/blah.mov")

Editing a post

Updating a post requires you knowing what type a post you're updating. You'll be able to supply to the post any of the options given above for updates.

client.edit_post(blogName, id=post_id, type="text", title="Updated")
client.edit_post(blogName, id=post_id, type="photo", data="/Users/johnb/mega/awesome.jpg")

Reblogging a Post

Reblogging a post just requires knowing the post id and the reblog key, which is supplied in the JSON of any post object.

client.reblog(blogName, id=125356, reblog_key="reblog_key")

Deleting a post

Deleting just requires that you own the post and have the post id

client.delete_post(blogName, 123456) # Deletes your post :(

A note on tags: When passing tags, as params, please pass them as a list (not a comma-separated string):

client.create_text(blogName, tags=['hello', 'world'], ...)

Getting notes for a post

In order to get the notes for a post, you need to have the post id and the blog that it is on.

data = client.notes(blogName, id='123456')

The results include a timestamp you can use to make future calls.

data = client.notes(blogName, id='123456', before_timestamp=data["_links"]["next"]["query_params"]["before_timestamp"])

Tagged Methods

# get posts with a given tag
client.tagged(tag, **params)

Using the interactive console

This client comes with a nice interactive console to run you through the OAuth process, grab your tokens (and store them for future use).

You'll need pyyaml installed to run it, but then it's just:

$ python interactive-console.py

and away you go! Tokens are stored in ~/.tumblr and are also shared by other Tumblr API clients like the Ruby client.

Running tests

The tests (and coverage reports) are run with nose, like this:

python setup.py test

Author: tumblr
Source Code: https://github.com/tumblr/pytumblr
License: Apache-2.0 license

#python #api 

Ahebwe  Oscar

Ahebwe Oscar


Django admin full Customization step by step

Welcome to my blog , hey everyone in this article you learn how to customize the Django app and view in the article you will know how to register  and unregister  models from the admin view how to add filtering how to add a custom input field, and a button that triggers an action on all objects and even how to change the look of your app and page using the Django suit package let’s get started.


Custom Titles of Django Admin

Exclude in Django Admin

Fields in Django Admin

#django #create super user django #customize django admin dashboard #django admin #django admin custom field display #django admin customization #django admin full customization #django admin interface #django admin register all models #django customization

How to create a Django project and a Django application

To start off create a new folder for the Django project and move into it
Here I called django-quick-start the main folder that will hold the project. Pay attention, this is not the actual Django project, but just its “home”. Once inside the new folder create a Python virtual environment and activate it (note, these are two distinct commands)
Pay attention again: django_quick_start now is the actual Django project created inside the django-quick-start folder. The name of this home folder doesn’t matter, but Django projects cannot have dashes in the name. That’s the reason for these underscores in django_quick_start.
Pay also attention to the dot in django-admin startproject django_quick_start … With the dot we can avoid additional folder nesting.

#django #django application #create a django

Ahebwe  Oscar

Ahebwe Oscar


How model queries work in Django

How model queries work in Django

Welcome to my blog, hey everyone in this article we are going to be working with queries in Django so for any web app that you build your going to want to write a query so you can retrieve information from your database so in this article I’ll be showing you all the different ways that you can write queries and it should cover about 90% of the cases that you’ll have when you’re writing your code the other 10% depend on your specific use case you may have to get more complicated but for the most part what I cover in this article should be able to help you so let’s start with the model that I have I’ve already created it.

**Read More : **How to make Chatbot in Python.

Read More : Django Admin Full Customization step by step

let’s just get into this diagram that I made so in here:

django queries aboutDescribe each parameter in Django querset

we’re making a simple query for the myModel table so we want to pull out all the information in the database so we have this variable which is gonna hold a return value and we have our myModel models so this is simply the myModel model name so whatever you named your model just make sure you specify that and we’re gonna access the objects attribute once we get that object’s attribute we can simply use the all method and this will return all the information in the database so we’re gonna start with all and then we will go into getting single items filtering that data and go to our command prompt.

Here and we’ll actually start making our queries from here to do this let’s just go ahead and run** Python manage.py shell** and I am in my project file so make sure you’re in there when you start and what this does is it gives us an interactive shell to actually start working with our data so this is a lot like the Python shell but because we did manage.py it allows us to do things a Django way and actually query our database now open up the command prompt and let’s go ahead and start making our first queries.

#django #django model queries #django orm #django queries #django query #model django query #model query #query with django

7 Mistakes You Should Avoid While Building a Django Application

Django…We all know the popularity of this Python framework. Django has become the first choice of developers to build their web applications. It is a free and open-source Python framework. Django can easily solve a lot of common development challenges. It allows you to build flexible and well-structured web applications.

A lot of common features of Django such as a built-in admin panel, ORM (object-relational mapping tool), Routing, templating have made the task easier for developers. They do not require spending so much time on implementing these things from scratch.

One of the most killer features of Django is the built-in Admin panel. With this feature, you can configure a lot of things such as an access control list, row-level permissions, and actions, filters, orders, widgets, forms, extra URL helpers, etc.

Django ORM works with all major databases out of the box. It supports all the major SQL queries which you can use in your application. Templating engine of Django is also very, very flexible and powerful at the same time. Even a lot of features are available in Django, developers still make a lot of mistakes while building an application. In this blog, we will discuss some common mistakes which you should avoid while building a Django application.

#gblog #python #python django #building a django application #django #applications