Csv upload and import in python django

Posted In: , . By CreativeSolutions


 if request.method == 'POST':
        srcfile = request.FILES.get("file", None)
        reader = csv.DictReader(srcfile) # read rows into a dictionary format
        for row in reader:
   print row

 

How to show django cursor execute query

Posted In: . By CreativeSolutions


 We can use the variable _executed with the cursor object ie. cursor._executed

 cursor = connection.cursor()
 cursor.execute(sql, (params))
 print cursor._executed
 rows = cursor.fetchall()

 

Using for loop counter in django template

Posted In: . By CreativeSolutions


 Django has the function forloop.counter to use the index for the row in template

 Ex:
 {% for question in questions %}
{{ forloop.counter }}
  {% endfor %}

 

Get python django model choice in View

Posted In: , . By CreativeSolutions


Suppose you have a model

 class User(models.Model):

   TYPES = (
('Admin', 'Admin'),
('Staff', 'Staff'),
  )


 You can access this in the view using the following code

 In your view file

 from app.core.models import User

 def save(request):
     user_types = User.TYPES

    render('user/form.hrml', {user_types:user_types})

If you want to use this variable in the template, Assign that value user_types as a dictionary variable then use the below code
{% for value, text in user_types %}
{{ value }} {{ text }}
{% endfor %}