dimanche 28 juin 2015

python manage.py runserver, shell, dbshell freezes on git-bash

I'm trying to run the interactive shell in python virtualenv in windows, on git-bash, but it isn't running. Strange thing is, it doesn't seem to do anything, just the cursor is blinking on the next line, giving no output.

$ python manage.py shell
|

However, I'm able to run commands like - migrate, makemigrations, sqlmigrate. Problem is occurring with the commands - shell, dbshell, runserver.

This seems to be some git-bash related issue, because I'm able to run shell from command line. I'm using PortableGit-2.4.3.1-2nd-release-candidate-64-bit.7z.exe on windows.

Customize UserAdmin multiple times

I'd like to display custom models in the user admin backend from multiple apps. I can do that for just one app with the classical admin.py commands :

from django.contrib import admin
from django.contrib.auth.admin import UserAdmin
from django.contrib.auth.models import User

from my_user_profile_app.models import Employee

class EmployeeInline(admin.StackedInline):
    model = Employee
    can_delete = False
    verbose_name_plural = 'employee'

# Define a new User admin
class UserAdmin(UserAdmin):
    inlines = (EmployeeInline, )

# Re-register UserAdmin
admin.site.unregister(User)
admin.site.register(User, UserAdmin)

However, the following app replaces all the previous registered models with its own, and so on… Is there a clean way to append models in the user admin backend ? It's like the app's admin.py must be aware of all previous customizations made, and register them all again.

Django turn lists into one list

Hello i want to put this data into one list so i can sort it by timestamp. I tried itertools chain but that didn't really work. Thank you for your help :)
`

for i in user:
    name.append(i['name'])

for i in next_level:
    rating_values.append(i['rating'])

for i in comment_values:
    comments_count.append(i['count'])

for i in likes_values:
    likes_count.append(i['count'])

for s in rating_values:
    ratings.append(s['value'])

for s in date:
    ratings.append(s['date'])   




ab = itertools.chain([name], [rating_values], [comments_count], [likes_values], [comment_values], [date])
list(ab)

How to include js and css only once

I'm currently working on a template tag that renders forms nicely. Therefore, I use some JavaScript libraries and css files. In the template I added the scripts:

<link rel="stylesheet" href="{% static 'xyz.css' %}"/>
<script lang="javascript" src="{% static 'xyz.js' %}"></script>
<div>
   ...
</div>

When rendering multiple forms on a singe site, those <links> and <script> are multiple times in the html document.

One possibility is to include them in the base template inside the <head> tag. But then they are in the html file even when they aren't needed.

Adding a {{ block head }} to the base template inside the <head> doesn't work either. For this {{ block.super }} is needed to append new js and css files, but {{ block.super }} doesn't work in includes (see http://ift.tt/1GUhHpR).

DJANGO ADDING NULL ON SAVE - IntegrityError at /****/ (1048, "***' cannot be null")

I am trying to save a record of an entity call 'Persona' using Django's save function but when I try to insert the new object I get a 1048 IntegrityError because for any reason Django is adding NULL on a field that can not be null and is foreign key (the field is GeneroID that is a foreign key of the table Genero), this during the insert statement even when I am passing the value correctly. The odd thing is that I have values on the 'Genero' table and I am capturing correctly the value passed on the POST even if I print the value I get the value passed but for any strange reason DJango is adding Null on GeneroID field.

I am using MySQL with InnoDB and Django 1.8. And my model is generated from a legacy DB.

MODEL GENERO

class Genero(models.Model):
id = models.AutoField(db_column='ID', primary_key=True)  # Field name made lowercase.
genero = models.CharField(db_column='Genero', max_length=50)  # Field name made lowercase.

class Meta:
    managed = False
    db_table = 'Genero'

MODEL PERSONA

class Persona(models.Model):
id = models.AutoField(db_column='ID', primary_key=True)  # Field name made lowercase.
nombre = models.CharField(db_column='Nombre', max_length=50)  # Field name made lowercase.
apellido1 = models.CharField(db_column='Apellido1', max_length=50)  # Field name made lowercase.
apellido2 = models.CharField(db_column='Apellido2', max_length=50)  # Field name made lowercase.
numeroidentificacion = models.CharField(db_column='NumeroIdentificacion', unique=True, max_length=50)  # Field name made lowercase.
observaciones = models.CharField(db_column='Observaciones', max_length=255)  # Field name made lowercase.
fechanacimiento = models.DateField(db_column='FechaNacimiento')  # Field name made lowercase.
direccionfoto = models.CharField(db_column='DireccionFoto', max_length=500)  # Field name made lowercase.
genero = models.ForeignKey(Genero, db_column='GeneroID',null=False)  # Field name made lowercase.
pais = models.ForeignKey(Pais, db_column='PaisID')  # Field name made lowercase.
lugarnacimiento = models.CharField(db_column='LugarNacimiento', max_length=100)  # Field name made lowercase.
direccion = models.ForeignKey(Direccion, db_column='DireccionID')  # Field name made lowercase.
profesion = models.CharField(db_column='Profesion', max_length=200)  # Field name made lowercase.
puesto = models.CharField(db_column='Puesto', max_length=200)  # Field name made lowercase.
lugartrabajo = models.CharField(db_column='LugarTrabajo', max_length=100)  # Field name made lowercase.

class Meta:
    managed = False
    db_table = 'Persona'

VIEW.PY

def guardarpersona(request):
direccion = json.loads(request.POST['direccion[]'])
persona = json.loads(request.POST['persona[]'])
temp = Direccion()
temp.descripcion = direccion[1]['value']
temp.distrito = Distrito.objects.get(pk=direccion[0]['value'])
temp.save()

p = Persona()
p.nombre = persona[1]['value']
p.apellido1 = persona[2]['value']
p.apellido2 = persona[3]['value']
numeroidentificacion = persona[4]['value']
observaciones = persona[12]['value']
fechanacimiento = persona[6]['value']
direccionfoto = ''
genero = Genero.objects.get(pk=persona[5]['value'])
print(genero)
pais = Pais.objects.filter(id=persona[8]['value'])
print(pais)
lugarnacimiento = persona[7]['value']
direccion = temp
profesion = persona[9]['value']
puesto = persona[10]['value']
lugartrabajo = persona[11]['value'] 

try:
    p.save()
except Exception:
    from django.db import connection
    print (connection.queries[-1])
return HttpResponse('Success!')      

DJANGO SQL STATEMENT BEEN GENERATED:

System check identified no issues (0 silenced). June 28, 2015 - 17:26:12 Django version 1.8.2, using settings 'WhiteKoala.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C.

Genero object

Pais: Pais object

{'sql': "INSERT INTO Persona (Nombre, Apellido1, Apellido2, NumeroIdentificacion, Observaciones, FechaNacimiento, DireccionFoto, GeneroID, PaisID, LugarNacimiento, DireccionID, Profesion, Puesto, LugarTrabajo) VALUES ('ANDREW', 'FONSECA', 'RIVAS', '', '', NULL, '', NULL, NULL, '', NULL, '', '', '')", 'time': '0.000'} [28/Jun/2015 17:26:13]"POST /guardarpersona/ HTTP/1.1" 200 8

ERROR:

IntegrityError at /guardarpersona/ (1048, "Column 'GeneroID' cannot be null")

Also, here is a folder with some pics about my models, view.py, SQL statement been generated and the error: http://ift.tt/1TXJQ65

Any idea about what I am doing wrong? I am new on Django and I would appreciate help and recommendations.

Issue storing multi valued json format dictionary into mysql table in DJango

I have below ajax call in my template

temp.html

function saveprof() {
            $.ajax({
                type: "POST",
                url: "saveprof",
                async: true,
                data: {
                    'radinput_Aj' : fun(),
                    'csrfmiddlewaretoken': $("input[name=csrfmiddlewaretoken]").val()
                },
                success: function (data, textStatus, jqXHR) {
                    $('#message').html(data);
                }
            });
        }

fun() returns a json format object v - which is as below :

example :

var v = [
             { axis: "", value: 4, order: 0 },
             { axis: "", value: 4, order: 1 },
             { axis: "", value: 4, order: 2 },
             { axis: "", value: 4, order: 3 },
             { axis: "", value: 4, order: 4 },
             { axis: "", value: 4, order: 5 },
             { axis: "", value: 4, order: 6 }
    ];

Views.py

def saveprof(request):
if request.method == "POST":
    radinputV=[]
    radinputV = request.POST['radinput_Aj']
else:
    response_data = 'Nothing to update!'
    return HttpResponse(response_data, content_type="text/plain")
response_data = ''
try:
*(Here, I would like to insert the incoming dictionary (radinputV) rows into my model skills)*
except:
    response_data = 'Ouch! Something went wrong!'
return HttpResponse(response_data, content_type="text/plain")

Below is the skills model :

class skills(models.Model):
id = models.CharField(max_length=300,blank=True)
skill = models.CharField(max_length=300,blank=True)
rating = models.CharField(max_length=300,blank=True)
ordernum = models.CharField(max_length=300,blank=True)

Here is the mapping of incoming json dictionary from template with the fields in skills model - skill is axis, rating is value, ordernum is order

However, when I run the code, it fails with MultivaluDictKeyError at below line

radinputV=[]
radinputV = request.POST['radinput_Aj']

What could be the problem and how to handle this scenario of inserting multiple rows into mysql table from template JSON object - Django view ?

Edit : I tried using .get() method already in the view.. but I'm not sure how to insert dictionary rows into my skills table.. can you pls help me with the approach ?

Django Inclusion Tag doesn't post to database

I'm trying to build a form to save Names and Email Adresses to my database. However, it doesn't save... I've used an Inclusion Tag because I want to use the same form in different templates. This is my models.py:

class Contact(models.Model):
    FRAU = 'FR'
    HERR= 'HR'
    GENDER_CHOICES = (
        (FRAU, 'Frau'),
        (HERR, 'Herr'),
    )
    gender = models.CharField(max_length=2, choices=GENDER_CHOICES, default=FRAU)
    first_name = models.CharField(max_length=100)
    last_name = models.CharField(max_length=200)
    email = models.EmailField()

    def __unicode__(self):
        return "%s %s" %(self.first_name, self.last_name)

This is my forms.py:

class FragenContactForm(ModelForm):
    class Meta:
        model = Contact
        fields = ['gender', 'first_name', 'last_name', 'email']

This is my custom tags module:

from django import template
from django.http import HttpResponseRedirect
from django.core.urlresolvers import reverse
from fragen.forms import FragenContactForm


register = template.Library()

@register.inclusion_tag('fragen/askforoffer.html', takes_context=True)
    def askforoffer(context):
    form = FragenContactForm(context['request'].POST or None)
    if context['request'].method=='POST':
        if form.is_valid():
            form.save()
        return HttpResponseRedirect(reverse('fragen/thanks.html'))
    else:
        messages.error(context['request'], "Error")
    return {'form': FragenContactForm()}

After I fill in and submit the form, I see nothing in my database. Am I missing something? Thanks!

Django SESSION_COOKIE_NAME ignored in Request

I have changed my SESSION_COOKIE_NAME value in my settings and restarted my webserver, unfortunately it still asks for the default 'sessonid' in the http requests - though the browser already sends the updated version. Therefore there is no match and a user cannot login.

Is there any reason why this is the case ?

I am using Django 1.8 and the default session manager (DB)

django server runerror about mysql

first try django ,when I do './manage.py runserver' it shows:

  File "/Library/Python/2.7/site-packages/django/db/backends/mysql/base.py", line 27, in <module>
    raise ImproperlyConfigured("Error loading MySQLdb module: %s" % e)
django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module: dlopen(/Library/Python/2.7/site-packages/MySQL_python-http://ift.tt/137FXWA, 2): Library not loaded: /usr/local/opt/mysql/lib/libmysqlclient.18.dylib
  Referenced from: /Library/Python/2.7/site-packages/MySQL_python-http://ift.tt/137FXWA
  Reason: image not found

I have set default database of mysql and I installed mysql-Python dev.No idea what's going on.Somebody help...

What is the most SEO friendly CMS platform as your experience?

Mainly i like a web engineer. I'm comfortable with php, JavaScript, jQuery, Python, Ruby programming languages. I have created hand coded admin panels for my all projects. But this time I have decided to use a pre-built Content Management System for my next project ( video and photography Website ). Please help me to choose best and SEO friendly CMS as your experience.

  • django
  • Concrete5
  • Joomla
  • WordPress
  • Drupal
  • MODx
  • magento

django bootstrap modal form closes on invalid form data

I am working on django + bootstrap modal where I am rendering ModelForm to the modal dialog.

The problem which I am facing is the modal form closes as soon as I click on submit button, it's showing errors on the modal form but it closes and the errors can be seen when the modal dialog is opened again.

I am not using any javascript or jquery, I am simply using html tag and handling post in the django view.

Please let me know what can be done to stop closing the dialog if the form is invalid.

Regards, Adarsh.

what literally defines a django app?

I have read a few questions about what an "app" is supposed to mean in django, but they go into the general purpose/use of an app, which is important, but not what an app literally "is". For example, I felt my curiosity today when

  1. I deleted a folder that I installed as an app with django-admin startapp, and received a certain error that stackO told me was due to a deleted app name residing in my INSTALLED_APPS. After clearing the name, my app worked again

  2. When making a folder cold (just mkdir, no startapp) in the highest level of a project, when trying to import names from real apps, I have to add my project to the sys.path list to be able to import. After remaking this folder as an app, imports are no longer an issue

My question is, 1. what leeway do I have to modify the apps django makes? Can I delete all the files that come with it (except init) and make it a cold library with no views and models? Are any files besides init required to function correctly?

  1. What does django do when I run startapp that causes an app to be importable automatically, which effect is not there when I make a folder with an init in it (as I said about needing to add the project path to sys.path within that folder)

Thank you

Django on Heroku: customizing django.po

I used to run Mezzanine on Heroku. Recently, I need to customize some data in the django.po. As Mezzanine is installed from requirements.txt, how do I upload my own django.po in order to overwrite Django's standard django.po?

Trouble understanding Django Forms

I'm currently learning django from the 'How to tango with django' site and i'm unable to understand the chapter dealing with forms. Appreciate it if someone would help me out.

http://ift.tt/1z119ta

the first step is to create a forms page which maps to models.py. I seem to understand this part. I also understand that we create a view to process the data acquired from these forms. I'm not able to understand the below code in the views page.

from rango.forms import CategoryForm

def add_category(request):
    # A HTTP POST?
    if request.method == 'POST':
        form = CategoryForm(request.POST)
    else:
        # If the request was not a POST, display the form to enter details.
        form = CategoryForm()

  1. How do the urlmapper know that a request method is POST or GET before the user actually enters any data in the form? On a similar note, when would a form have a get method?

  2. form = CategoryForm(request.POST) - would someone explain this to me? CategoryForm looks to be a class which is already inheriting from another class what does the request.POST argument convey ?

Gchart in Django

I´m developing a project in Django with Gchart and by this documentation i can creat a line chart with a specifc number of lines, like 2, 5, 1... but i have no idea of how create a view that returns a line chart with n lines, n like variable. So what i really want to is create a generic view to any number of lines in a chart.

So any ideas?

This is the model:

class Tag(models.Model):

    objects = GChartsManager()

    idtag = models.IntegerField(db_column='idTAG', primary_key=True, editable=False, verbose_name = 'Id')  # Field name made lowercase.
    desvio = models.FloatField(db_column='DEVIATION', blank=True, null=True, verbose_name = 'Diversion')  # Field name made lowercase.
    tempo_max = models.IntegerField(db_column='TIME_MAX', blank=True, null=True, verbose_name = 'Max time')  # Field name made lowercase.
    conv_rate = models.IntegerField(db_column='CONV_RATE', blank=True, null=True, verbose_name = 'Convertion rate')  # Field name made lowercase.
    taginfo_idtaginfo1 = models.ForeignKey('Taginfo', db_column='tagInfo_idTAGINFO', verbose_name = 'Tag')  # Field name made lowercase.
    datasource_idestacao_meteo = models.ForeignKey(Datasource, db_column='datasource_idDATASOURCE', blank=True, null=True, verbose_name = 'Datasource')  # Field name made lowercase.

    def __unicode__(self):
        return u'id = %s / id tagInfo => %s' % (self.idtag, self.taginfo_idtaginfo1)

    class Meta:
        managed = False
        db_table = 'tag'


class Taginfo(models.Model):

    objects = GChartsManager()

    idtaginfo = models.IntegerField(db_column='idTAGINFO', primary_key=True, editable=False, verbose_name = 'Id')  # Field name made lowercase.
    nome = models.CharField(db_column='NAME', max_length=45, verbose_name = 'Name')  # Field name made lowercase.
    descricao = models.CharField(db_column='DESCRIPTION', max_length=255, blank=True, verbose_name = 'Details')  # Field name made lowercase.

    def __unicode__(self):
        return u'name = %s / description = %s' % (self.nome, self.descricao)

    class Meta:
        managed = False
        db_table = 'taginfo'


class Valores(models.Model):

    objects = GChartsManager()

    idvalores = models.IntegerField(db_column='idVALUES', primary_key=True, editable=False, verbose_name = 'Id')  # Field name made lowercase.
    valor = models.FloatField(db_column='VALUE', verbose_name = 'Value')  # Field name made lowercase.
    datahora = models.DateTimeField(db_column='DATETIME', verbose_name = 'Date time')  # Field name made lowercase.
    tag_idtag = models.ForeignKey(Tag, db_column='tag_idTAG', verbose_name = 'Tag')  # Field name made lowercase.

    def __unicode__(self):
        return u'Tag = %s  / DATETIME = %s / Value = %s' % (self.tag_idtag, self.datahora, self.valor)

    class Meta:
        managed = False
        db_table = 'values'

This is the view that creat a chart with one line:

def tag(request, tag_id = 1):
# if there is
if Tag.objects.filter(idtag=tag_id).count()>0 :
    result = Tag.objects.get(idtag=tag_id)

    hasInfo = False
    tagInfo = None
    #if there is information about this tag
    if Taginfo.objects.filter(idtaginfo = result.taginfo_idtaginfo1.idtaginfo).count() > 0:
        tagInfo = Taginfo.objects.get(idtaginfo = result.taginfo_idtaginfo1.idtaginfo)
        hasInfo = True
    #if there is values on this tag 
    if Valores.objects.filter(tag_idtag = tag_id).count>0:
        aux = Valores.objects.filter(tag_idtag = tag_id)
        #this verify is only to put the description on the graph
        if hasInfo:
            values = aux.order_by('-datahora').to_json(order=("datahora", "valor"),
                                                    labels={"valor": tagInfo.descricao})
        else:
            values = aux.order_by('-datahora').to_json(order=("datahora", "valor"),
                                                    labels={"valor": "Values"})
    else:
        values = None
    return render_to_response('Tag/tag.html',
        {'tag' : result, 'values' : values, 'tagInfo' : tagInfo}
    )
else:
    return render_to_response('Tag/tagDoesNotExist.html',
        {'tag_id' : tag_id }
    )

Django. A list of MulitpleChoiceFileds

Here's a a code snippet that used a for loop to generate a list of 3 MultipleChoiceFields. Notice, that each field has to explicitly named for django-cripsy-forms to render them, but there has got to be a way to iterate through these with Crispy Forms so I don't have to know in advance how big the list of MultipleChoiceFieds will be. Any ideas??

    items = tuple(items)
    locations.append(forms.MultipleChoiceField(widget=forms.SelectMultiple, label = '', choices=items))


field1 = locations[0]
field2 = locations[1]
field3 = locations[2]

def __init__(self, *args, **kwargs):

    self.helper = FormHelper()
    self.helper.form_id = 'id-qkview-form'
    self.helper.form_show_errors = True
    self.helper.form_action = 'F5-fetch-qkview'
    self.helper.form_method = 'POST'
    self.helper.form_class = 'form-vertical'
    self.helper.label_class = 'col-lg-2'
    self.helper.field_class = 'col-lg-4'
    self.helper.add_input(Submit('submit', 'Submit'))

    self.helper.layout = Layout(
        Fieldset(
            'LOC01',
            'field1',
        ),
        Fieldset(
            'LOC02',
            'field2',
        ),
        Fieldset(
            'LOC01',
            'field3',
        ),
     )

    super(F5qkviewForm, self).__init__(*args, **kwargs )

How to make two Django models with cross relationship?

I need two Django models: first with Users, second with Projects.

Between them I need many-to-many relationship with an additional field(s).

How to make the below code working?

from django.db import models

class User(models.Model):

    name = models.CharField('Name', max_length=50)
    projects = models.ManyToManyField(Project, through='UserProjects')

    def __str__(self):
        return self.name

class Project(models.Model):

    name = models.CharField('Name', max_length=50)
    users = models.ManyToManyField(User, through='UserProjects')

    def __str__(self):
        return self.name

class UserProjects(models.Model):

    user = models.ForeignKey(User)
    project = models.ForeignKey(Project)
    is_active = models.BooleanField('Active')

At the end User.projects should return Projects for specified User and in the same way Project.users should return Users for specified Project.

Deploy Django project on heroku (python 3.4.3)

Im folowing this guide step by step. Except im using python 3.4.3 and pyvenv instead of virtualenv. I have installed:

  • Python 3.4.3
  • Django 1.8.2
  • python-psycopg2
  • libpq-dev

My steps are:

  1. mkdir hellodjango && cd hellodjango
  2. pyvenv venv
  3. source venv/bin/activate
  4. pip install django-toolbelt (success)
  5. django-admin.py startproject hellodjango .
  6. created Procfile (web: gunicorn hellodjango.wsgi --log-file -)
  7. foreman start (success and check working app in browser)
  8. pip freeze > requirements.txt
  9. add runtime.txt (python-3.4.3)
  10. filled settings.py and wsgi.py as guide says
  11. Init and commit git repo
  12. heroku create (success)
  13. git push heroku master (error!)

So git push heroku master says that:

Counting objects: 14, done.
Delta compression using up to 8 threads.
Compressing objects: 100% (10/10), done.
Writing objects: 100% (14/14), 2.90 KiB | 0 bytes/s, done.
Total 14 (delta 0), reused 0 (delta 0)
remote: Compressing source files... done.
remote: Building source:
remote: 
remote: -----> Python app detected
remote: -----> Installing runtime ( 
remote: python-3.4.3)
remote:  !     Requested runtime ( 
remote: python-3.4.3) is not available for this stack (cedar-14).
remote:  !     Aborting.  More info: http://ift.tt/1k3izyT
remote: 
remote:  !     Push rejected, failed to compile Python app
remote: 
remote: Verifying deploy...
remote: 
remote: !       Push rejected to cryptic-thicket-7510.
remote: 
To http://ift.tt/1SUTPaR
 ! [remote rejected] master -> master (pre-receive hook declined)
error: failed to push some refs to 'http://ift.tt/1SUTPaR'

As you can see main error is Requested runtime (remote: python-3.4.3) is not available for this stack (cedar-14). What am i doing wrong?

I am trying to use AzureStorage to for connecting azure storage with django 1.7 app .

models.py

from django.db import models
from myproject.storage import AzureStorage

class MyModel(models.Model):
    my_file = models.FileField(upload_to="files", storage=AzureStorage(container="media"))
    my_image = models.ImageField(upload_to="images", storage=AzureStorage(container="media"))

But when I try to makemigrations I am getting :

ValueError: Cannot serialize: <myproject.storage.AzureStorage object at 0x7f85185e66d0>
There are some values Django cannot serialize into migration files.
For more, see http://ift.tt/1p5jGfR

What exactly its not able to serialize ?

Django: render_to_response doesn't work

I have a template perfil.html and want to send this to it:

return render_to_response('perfil.html', query_data,  context_instance=RequestContext(request), {'pseudonimo': usuario.pseudonimo,'seguidores': seguidores(usuario.pseudonimo), 'sigue':sigue(usuario.pseudonimo), 'posts':"En pruebas"})

but it doesn't work. This is the error I have:

Request Method: GET
Request URL:    http://localhost:8000/mi_perfil/
Django Version: 1.8
Exception Type: SyntaxError
Exception Value: non-keyword arg after keyword arg (views.py, line 181)
Exception Location: /home/rebecca/DSI/pretec/pretec/urls.py in <module>, line 3
Python Executable:  /home/rebecca/DSI/env-pretec/bin/python
Python Version: 2.7.3

If I do this:

return render(request,'perfil.html', {'pseudonimo': usuario.pseudonimo,'seguidores': seguidores(usuario.pseudonimo), 'sigue':sigue(usuario.pseudonimo), 'posts':"En pruebas"})

it works, and if I do this:

return render_to_response('perfil.html', query_data, context_instance=RequestContext(request))

it works too but I want to include the two options in the render_to_response

This is my function in the views.py:

def mi_perfil(request):
   usuario = Usuario.objects.get(pseudonimo = request.session['member_id'])
   query = Usuario.objects.all()

   query_data = {
       "user_data" : query
   }
   print query_data
   return render_to_response('perfil.html', query_data, context_instance=RequestContext(request), {'pseudonimo': usuario.pseudonimo,'seguidores': seguidores(usuario.pseudonimo), 'sigue':sigue(usuario.pseudonimo), 'posts':"En pruebas"})

What i am doing wrong? How can I fix it?

Arbitrary Amount of Fields for Django Model

Is there a way to store an arbitrary number of a particular Field in a Django Model such that a user can specify as many as he or she deems necessary? This would be useful for tags or image uploads.

Django Migration: Can't create table errno: 150

I have a brand new MariaDB serve (version: 5.5.41-MariaDB) and created a new database for my Django (1.8.2) application. The database was created using innoDB by default.

I have a model that looks like this:

class UserProfile(models.Model):
    user = models.OneToOneField(User, unique=True)  # django's default user model

When I run python manage.py migrate. I get the following error:

  File "/home/vagrant/envs/leo/lib/python2.7/site-packages/MySQLdb/cursors.py", line 205, in execute
    self.errorhandler(self, exc, value)
  File "/home/vagrant/envs/leo/lib/python2.7/site-packages/MySQLdb/connections.py", line 36, in defaulterrorhandler
    raise errorclass, errorvalue
django.db.utils.OperationalError: (1005, "Can't create table 'leo.#sql-bcd_1f' (errno: 150)").

What am I doing wrong and how can I fix it?

Django + Gunicorn + nginx yields very poor performance. Can't get even 8 qps

I am using nginx + gunicorn for serving a django app.

I have this view:

def hi(request):
    return HttpResponse('hi', content_type='text/plain')

mapped to url /hi/. So it basically just returns hi at [myurl]/hi.

Now when I load test this application from loader.io, this doesn't even pass the 250 clients over 30 secs test. (Approx 8 requests per second)

This is (part of) my nginx access.log file. It basically just gives 499s after few 200s. (Timeout in loader.io is set to 10 secs)

I must be doing something seriously wrong. How do I find out?

How to add request id in Django logs without modifying logger call?

I want to add request and user ids with logs of my Django project. Ways I found on internet need me to send extra request with every logger call like this,

logger.info('This is my info log line', extras={ 'request', request })

But I don't want to modify every existing logger call. Is it possible to this with handlers/formatters?

Django. Problems with User model

I got problem when updated project from django 1.6 to django 1.8

I have model Profile

class Profile(AbstractUser):
    middle_name = models.CharField(max_length=70, blank=True, verbose_name=_("Middle name"))
    gender = models.CharField(max_length=2, choices=GENDER_CHOICES)
    phone = models.CharField(max_length=150, blank=True, verbose_name=_("Phone"))
    status = models.CharField(max_length=500, blank=True, verbose_name=_("Status"))
    education = models.CharField(max_length=350, blank=True, verbose_name=_("Education"))
    progress_display = models.BooleanField(default=True, blank=True, verbose_name=_("Display progress"))
    about = models.TextField(blank=True, verbose_name=_("description about"))
    city = models.CharField(max_length=75, blank=True, verbose_name=_("City"))
    current_city = models.CharField(max_length=75, blank=True, verbose_name=_("Current city"))
    birth = models.DateTimeField(blank=True, null=True, verbose_name=_("Birthday"))
    registered = models.DateTimeField(auto_now=True, help_text=_('Registration date'),
                                      verbose_name=_("registration date"))
    is_teacher = models.BooleanField(default=False, blank=True, verbose_name=_("is_teacher"))
    hide_fields = models.CharField(max_length=255, blank=True)
    subscription = models.BooleanField(default=False, blank=True, verbose_name='Подписка на рассылку')
    main_photo = models.ForeignKey('avatar.Photo', blank=True, verbose_name=_("user main-photo"), related_name='avatar', default=None, null=True)

    class Meta:
        verbose_name = _('User')
        verbose_name_plural = _('Users')
        ordering = ('-registered', 'id')
        get_latest_by = 'registered'

My applications are located in separated folder ("applications"). path to folder i define in settings like this:

BASE_DIR = os.path.abspath(os.path.dirname(__file__))
sys.path.append(os.path.join(BASE_DIR, 'applications'))

I also define my custom User-model in settings (located in Profile application)

AUTH_USER_MODEL = 'profile.Profile'

it's my install apps:

INSTALLED_APPS = (
    'social',
    'photo',
    'profile',
    'qa',
    'main',
    'learn',
    'donate',
    'notifications',
    'articles',
    'django.contrib.auth',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.contenttypes',
    'grappelli',
    'django_extensions',
    'django.contrib.admin',
    'rest_framework',
    'djkombu',
    'autofixture',
    'crispy_forms'    
)

commands "runserser", 'makemigrations' or 'migrate' work good but createsuperuser return this

Traceback (most recent call last):
  File "/opt/pycharm-3.0.2/helpers/pycharm/django_manage.py", line 23, in <module>
    run_module(manage_file, None, '__main__', True)
  File "/usr/lib/python2.7/runpy.py", line 176, in run_module
    fname, loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 82, in _run_module_code
    mod_name, mod_fname, mod_loader, pkg_name)
  File "/usr/lib/python2.7/runpy.py", line 72, in _run_code
    exec code in run_globals
  File "/home/camaro/programming/imedrese/master/manage.py", line 14, in <module>
    execute_from_command_line(sys.argv)
  File "/home/camaro/programming/imedrese/master/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line
    utility.execute()
  File "/home/camaro/programming/imedrese/master/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute
    self.fetch_command(subcommand).run_from_argv(self.argv)
  File "/home/camaro/programming/imedrese/master/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 190, in fetch_command
    klass = load_command_class(app_name, subcommand)
  File "/home/camaro/programming/imedrese/master/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 41, in load_command_class
    return module.Command()
  File "/home/camaro/programming/imedrese/master/local/lib/python2.7/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 28, in __init__
    self.UserModel = get_user_model()
  File "/home/camaro/programming/imedrese/master/local/lib/python2.7/site-packages/django/contrib/auth/__init__.py", line 155, in get_user_model
    "AUTH_USER_MODEL refers to model '%s' that has not been installed" % settings.AUTH_USER_MODEL
django.core.exceptions.ImproperlyConfigured: AUTH_USER_MODEL refers to model 'profile.Profile' that has not been installed

Migrating from auth_user in Django

I created a custom user model in Django and it worked up fine. However, I decided to create a custom model to suit my needs after the project was up and running.

As a result, I will need to migrate the schema (Currently, when I register a user, the code is still referencing to the the auth_user database tables where as the new custom user table is user.)

I have set the AUTH_USER_MODEL in settings.py to userapp.User, where userapp is my custom user app and User is the Model that inherits from the AbstractUser model.

I am fairly new to Django and cannot understand how to achieve this. One obvious way to clean install the database, which is not something that I'm looking to do as it will remove all my data.

How do I migrate then? I've heard South is used for that but I don't know how to use it. Besides I think South isn't required in the recent versions of Django.

My version of Django is 1.8.2.

Getting spesific data from three models in django

I am starting working with django and i want get specific data from three related models. my models are

class Institution(models.Model):
    name = models.CharField(max_length=100, unique=True)
    ...

class Certification(models.Model):
    name = models.CharField(max_length=100)
    ...

class Course(models.Model):
    name = models.CharField(max_length=100)
    institution = models.ForeignKey(Institution)
    certification = models.ForeignKey(Certification)

in my html page i want display the courses offered by a particular institution ordered by certification. like this

name of a particular institution I 
    certification 1
         list courses that offer certification 1
    certification 2
         list courses that offer certification 2
    ...

my current template is

{{institution.name}}
{% for certification in preselected_certifications %}
    <h1> {{ certification.name }} </h1>
    <ul>
          {% for course in courses %}
            <li>{{ course.name }}</li>
          {% endfor %}
    </ul>
{% endfor %}

my view

def detail(request, slug):
    context = RequestContext(request)
    context_dict = {'slug_requested': slug}
    try:
      institution = Institution.objects.get(slug=slug)
      courses = Course.objects.filter(etablissement=etablissement)

      context_dict['courses'] = courses
      context_dict['etablissement'] = etablissement

    except Etablissement.DoesNotExist:
      pass

    return render_to_response('institutition/details.html', context_dict, context)

i know the problem is in preselected_certification and courses but dont know how to fix it.

help please

Local templates not loading in django-oscar

I want to customize the layout of my Django-Oscar site according to my requirements(changing header etc)

I tried method 1 as described in Django Oscar documentation How to customise templates

But it is not loading the templates from my local directory(templates/oscar)even though I have copied them instead it is loading templates from the main installation directory.

I think their could be some problem in my settings.py file but I am not able to find it.

Settings.py

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)

import os
import sys
from oscar import get_core_apps
from oscar import OSCAR_MAIN_TEMPLATE_DIR
from oscar.defaults import *
from django.core.urlresolvers import reverse_lazy

BASE_DIR = os.path.dirname(os.path.dirname(__file__))
location = lambda x: os.path.join(os.path.dirname(os.path.realpath(__file__)), '..', x)

# sys.path.insert(0, os.path.join(BASE_DIR, 'apps'))  # to store apps in apps/ directory


# Quick-start development settings - unsuitable for production
# See http://ift.tt/WG84IC

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []


# Application definition
TEMPLATE_LOADERS = (
    'django.template.loaders.filesystem.Loader',
    'django.template.loaders.app_directories.Loader',
    'django.template.loaders.eggs.Loader',
)

TEMPLATE_DIRS = (
    location('templates'),
    os.path.join(BASE_DIR, 'templates').replace('\\', '/'),
    OSCAR_MAIN_TEMPLATE_DIR,
)

INSTALLED_APPS = [
    'django.contrib.auth',
    'django.contrib.admin',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'django.contrib.flatpages',
    'apps.users',
    'apps.doorstep',
    'apps.cars',
    'django_markdown',
    'social.apps.django_app.default',
    # 'crispy_forms',
    'django.contrib.sites',
    # 'zinnia_threaded_comments',   # app for zinnia threaded comments
    'django_comments',  # zinnia-blogging prerequisite
    'mptt',             # zinnia-blogging prerequisite
    'tagging',          # zinnia-blogging prerequisite
    'zinnia',           # zinnia itself
    'compressor',
    ] + get_core_apps()
# specifying the comments app
# COMMENTS_APP = 'zinnia_threaded_comments'

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
    'oscar.apps.basket.middleware.BasketMiddleware',
    'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware',
)

# Authentication backend used by python-social-auth
AUTHENTICATION_BACKENDS = (
    'social.backends.facebook.FacebookOAuth2',
    'social.backends.google.GoogleOAuth2',
    'django.contrib.auth.backends.ModelBackend',
    'oscar.apps.customer.auth_backends.EmailBackend',
)

TEMPLATE_CONTEXT_PROCESSORS = (
    "social.apps.django_app.context_processors.backends",
    "social.apps.django_app.context_processors.login_redirect",
    "django.contrib.auth.context_processors.auth",
    "django.contrib.messages.context_processors.messages",
    "django.core.context_processors.i18n",
    "django.core.context_processors.request",
    "zinnia.context_processors.version",
    "django.core.context_processors.debug",
    "django.core.context_processors.media",
    "django.core.context_processors.static",
    "django.core.context_processors.tz",
    'oscar.apps.search.context_processors.search_form',
    'oscar.apps.promotions.context_processors.promotions',
    'oscar.apps.checkout.context_processors.checkout',
    'oscar.apps.customer.notifications.context_processors.notifications',
    'oscar.core.context_processors.metadata'
)



ROOT_URLCONF = '{project_name}.urls'

WSGI_APPLICATION = '{project_name}.wsgi.application'


# Database
# http://ift.tt/1s34S6b

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': "",
        'USER': '',
        'PASSWORD': '',
        'HOST': 'localhost',
        'PORT': '3306'
    }
}

# Internationalization

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True

LOGIN_URL = '/users/login/'

# Static files (CSS, JavaScript, Images)
# http://ift.tt/1s34R23

STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, '/static/')
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
MEDIA_URL = "/media/"



STATICFILES_DIRS = (
    os.path.join(BASE_DIR, 'staticfiles'),


)
REGISTRATION_INVALID = 50
MESSAGE_TAGS = {
    REGISTRATION_INVALID: 'InvalidDetails',
}
# temporary , should not be in settings file
SOCIAL_AUTH_FACEBOOK_KEY = ""
SOCIAL_AUTH_FACEBOOK_SECRET = ""
SOCIAL_AUTH_FACEBOOK_SCOPE = ['email']

SOCIAL_AUTH_GOOGLE_OAUTH2_KEY = ""
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET = ""

LOGIN_REDIRECT_URL = '/blog/'

# ------------------------------------ #
# Settings for sending email #

EMAIL_USE_TLS = True
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_PORT = 587
EMAIL_HOST_USER = ''
EMAIL_HOST_PASSWORD = ''
DEFAULT_FROM_EMAIL = EMAIL_HOST_USER
SERVER_EMAIL = EMAIL_HOST_USER
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
# ------------------------------------ #


# site id for django sites framework
SITE_ID = 1

# configuration settings for  django-zinnia
ZINNIA_PING_EXTERNAL_URLS = False
ZINNIA_SAVE_PING_DIRECTORIES = False
ZINNIA_MARKUP_LANGUAGE = 'markdown'
ZINNIA_UPLOAD_TO = 'uploads/zinnia/'
# TimeZone Settings
USE_TZ = True

# ------------------------ #
# django oscar search settings
HAYSTACK_CONNECTIONS = {
    'default': {
        'ENGINE': 'haystack.backends.simple_backend.SimpleEngine',
    },
}
# django oscar settings
OSCAR_SHOP_NAME = ''
OSCAR_DEFAULT_CURRENCY = 'INR'

Any idea what could be the issue here?

Django installed in dist-packages

I am working on an Amazon Linux AMI (version 2013.09). My goal, among other things, is to have Django up and running. So here's what I do:

  1. Install pip using yum (it installs pip 7.0.3 in Python2.7/dist-packages)
  2. Install virtualenv using pip
  3. Create a virtualenv (with --no-site-packages)
  4. Install Django using pip inside the virtualenv (this installs Django in the virtenv's Python directory, inside dist-packages)

This seems fine, until I try to use manage.py. The following line:

python manage.py collectstatic --noinput -c -l > /dev/null

Invokes the following error:

OSError: [Errno 2] No such file or directory: '...my-env/lib/python2.7/site-packages/django/contrib/admin/static'

Which is true, because the entire Django infrastructure is in dist-packages, not site-packages. What is the correct way of fixing this dependency?

Thanks!

UPDATE 28.06.15 The reason Django attempts to access site-packages is the 'STATIC_ROOT' definition in its settings.py file. Thing is, I installed Django in the exact same way, using the same settings, a couple of years ago, and it worked perfectly. So what's changed? Why has pip suddenly moved to dist-packages?

Django - initial checked CheckboxInput

I want my CheckboxInput was checked by default :

My models :

class Sub(models.Model):
    user = models.OneToOneField(User)
    batata = models.BooleanField(default=False)

class presentationForm(forms.ModelForm):
    class Meta : 
        model = Sub
    widgets = {
        'batata': forms.CheckboxInput(attrs={'id':'batata'}),
    }
    def __init__(self, *args, **kwargs):
        self.valbata = kwargs.pop("arg_bata")
        super(presentationForm, self).__init__(*args, **kwargs)
        self.fields['batata'].initial = True

My view :

def theview(request):
    form = presentationForm(arg_bata="Azerty")
    return render(request,"le_site/page-batata.html",locals())

My template :

...
{{ form.batata|bootstrap }}
...

But in my page, the checbkoxInput "batata" isn't checked...

How to confirm Gunicorn is using Nginx as proxy?

I am using django as my web framework, gunicorn as the server and Nginx as the proxy server. I have gunicorn running at localhost:8080 & nginx at localhost:80.

Now how do I confirm that gunicorn is indeed using nginx as the (proxy) server? Also is my site supposed to be hosted at 8080?

gunicorn_start.sh:

APPNAME=comments
APPDIR=/home/ubuntu/$APPNAME/

LOGFILE=$APPDIR'gunicorn.log'
ERRORFILE=$APPFIR'gunicorn-error.log'

NUM_WORKERS=3

ADDRESS=0.0.0.0:8000

cd $APPDIR

source ~/.bashrc
# workon $APPNAME

exec gunicorn $APPNAME.wsgi:application \
-w $NUM_WORKERS --bind=$ADDRESS \
--log-level=debug \
--log-file=$LOGFILE 2>>$LOGFILE  1>>$ERRORFILE &

/etc/nginx/sites-available/example:

upstream hello_app_server {
  server unix:/home/ubuntu/nis_comments/run/gunicorn.sock fail_timeout=0;
}

server {
    listen   80;
    server_name ec2-[myip].compute-1.amazonaws.compute-1;

    client_max_body_size 4G;

    access_log /var/log/nginx/access.log;
    error_log /var/log/nginx/error.log;

    location /static/ {
        alias   /home/ubuntu/comments/static;
    }

    location /media/ {
        alias   /home/ubuntu/comments/;
    }

    location / {
        proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for;

        proxy_set_header Host $http_host;

        proxy_redirect off;

        if (!-f $request_filename) {
            proxy_pass http://hello_app_server;
            break;
        }
    }
}

PyCharm can't find Django test

I'm running into this very same issue, but I can't find a solution for this.

Find the dummy Django project I created for this here.

This is my test configuration:

enter image description here

This is the project structure:

enter image description here

Trying to run the test results in:

AttributeError: 'super' object has no attribute 'run_tests'

Process finished with exit code 137
Empty test suite.

Obviously, running this from the shell gives no errors:

(django)mosquito@mosquito-X550LD ~/python_projects/django_test $ python manage.py test 
Creating test database for alias 'default'...
.
----------------------------------------------------------------------
Ran 1 test in 0.000s

OK
Destroying test database for alias 'default'...

Any idea what I'm doing wrong??

Thanks, Alejandro

django assign value to positiveIntegerField programmatically

I am working on a little django application where the model contains a TextField and a PositiveIntegerField.

I need the PositiveInegerField to be populated with the number of words in the TextField.

This could be done via custom javascript code that count the number of words in the TextField's text area and put the value to the word count field text box before submitting the form but I do not want to play with custom javascript in the admin.

How to assign a value to a PositiveIntegerField programmatically?

how to use if and print in django?

how i can use this code in django i want to use use raw input and print in my django python code thats are the code i tried to use the code in html template {% %} but it not work

import time
while True:
    a = raw_input()
    if a == 'mark':
         time.sleep(7)
         print('nice name')
    if a == 'seco':
         time.sleep(7)
         print('great name')
    else:
    print('i didnnot now this name')
    time.sleep(10000)
    if a == "":       # If it is a blank line...
        break     

Uploading files/contents of a local folder to S3 in Django framework

I have very limited experience with Django framework. I am trying to create a website in Django so users (for now assume any user) can upload contents of a local folder to a particular folder in S3. He/she can choose out of a few locations on a s3 bucket where they want to upload. I am using django-storage and followed the steps http://ift.tt/1sJyJfR to upload a single file in S3 bucket. That works, but now I want to adapt this code to upload multiple files at a time, if possible with a progress bar. Can someone suggest the best yet simple way to do it. It would be even great if you can point me to some code snippets for it. Is django-storage the best option or shall I look into other packages.

Thanks in advance your help :)

Django form not visible

Only the button is visible and headings are visible cannot see CharField

forms.py

from django import forms

class NameForm(forms.Form):
    your_name = forms.CharField(label='Your name', max_length=100)

views.py

from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from compare.forms import NameForm

def get_name(request):
   if request.method == 'POST':
      form = NameForm(request.POST)
   if form.is_valid():
      return HttpResponseRedirect('/thanks/')

   else:
      form = NameForm()

   return render(request, 'name.html', {'form': form})

index.htm

    <form action="/your-name/" method="post">
        {% csrf_token %}
        {{ form }}
    <input type="submit" value="Submit" />
    </form>

Django: Form and many2many relationship using through relationshiop

I am trying to sort out a specific problem that involve "many2many" relationship using through specification. I've already tried to use inline_factory but I was not able to sort out the problem.

I have these tables

class Person(models.Model):
    id = models.AutoField(primary_key=True)  
    fullname = models.CharField(max_length=200)
    nickname = models.CharField(max_length=45, blank=True)

    class Meta:
        db_table = 'people'

class Role(models.Model):
        role = models.CharField(max_length=200)
    class Meta:
        verbose_name_plural = 'roles'
        db_table = 'roles'

class Study(models.Model):
    id = models.AutoField(primary_key=True) 
    title = models.CharField(max_length=255)
    description = models.CharField(max_length=1000)
    members = models.ManyToManyField(Person, through='Studies2People')

    class Meta:
        db_table = 'studies'

class Studies2People(models.Model):
    person = models.ForeignKey(Person)
    role = models.ForeignKey(Role)
    study = models.ForeignKey(Study)

    class Meta:
        verbose_name_plural = 'studies2people'
        db_table = 'studies2people'
        unique_together = (('person', 'role', 'study'),)
#forms.py
from .models import Study, Person, Role, Studies2People
class RegisterStudyForm(ModelForm):
    class Meta:
        model = Study
        fields = '__all__'

#View.py
class StudyCreateView(CreateView):
    template_name = 'managements/register_study.html'
    model = Study
    form_class = RegisterStudyForm
    success_url = 'success/'

    def get(self, request, *args, **kwargs):
        self.object = None
        form_class = self.get_form_class()
        form = self.get_form(form_class)
        return self.render_to_response(self.get_context_data(form=form))

The code above creates a form like:

Study.Title
Study.description
List of People

I want to create a form to fill in all fields that involve Studies2People Something like this:

Study.Title
Study.description
Combo(people.list)
Combo(Role.list)

Maybe I should start from Studies2People but I don't know how to show the "inline" forms involved.

Thanks in advance C.

Check whether the query is not exist or has a specific value

For instance we have Example model and we want to do something like below:

ex = Example.objects.filter(Q(participant__tries=0) | Q(participant__tries=*THERE IS NO EXAMPLE RECORD*), courses=course)

What should we replace in between two stars?

Django filter queryset in Annotation

I have the following models.

1. City
2. Picture
3. Video

I want to get the counts of Picture and Video for every city using annotate. The only problem I am facing is I do not know a way how to filter on annotated object.

cities = City.objects.filter(pro=pro).annotate(
        img_count=Count('city_pictures', distinct=True),
        video_count=Count('city_videos', distinct=True)).order_by('-img_count').values('name', 'img_count', 'video_count')

Problem

Right now, I can not filter images which are verified

Patch Solution

cities = City.objects.default().filter(pro=pro)

for city in cities:
    city.image_count = Picture.objects.filter(verified=True).count()
    city.video_count = Vidoe.objects.filter(verified=True).count()

But that would make additional queries into the database. I need way by which I can make minimum db queries and achieve what I am looking for.

Thanks.

what I am meant to do with a github-based bugfix? (python-django on Win OS)

Not used to working collaboratively! I am gradually learning the mysteries of Git, but how you use github is still beyond me.

This relates to a bug with Django and Selenium as documented here: http://ift.tt/1NpIwUD

This takes us to this page on github: http://ift.tt/1NpIvQB

I "manually" added the new line ("refresh") to the file ...\admin\tests.py, and this seems to stop some of the ConnectionResetErrors occurring... but I don't know how to use this commit on github: in particular, the other file shown here, tests\view_tests\tests\test_i18n.py, doesn't exist, nor its path.

Am I meant somehow to "git pull" from github? And sort of replace my django file structure under "site-packages"?

I have a book on github (yes, an entire book!) and I will read it as soon as I can, promise.

How can I change the username and the password of a user in django programatically?

I am creating an application in django and I have a user who can change the passwords and usernames of the other users.

In my views.py I have a view that controls this.

I get the user of a concrete username this way:

user = User.objects.get(username=user_name)
user.username = request.POST['username']

user.set_password(request.POST['password'])
user.save()

But when I save all, I see that the selected user's username didn´t changed.

How can I set the username and the password of the selected user "user_name"?

Thank you!

Django: How to prevent model form fields from rendering but include them in validation?

Let's say I have the following model:

class Folder(models.Model):
    name = models.CharField(default='untitled', max_length=255)
    parent = models.ForeignKey('self', null=True, blank=True)
    root = models.ForeignKey('self', null=True, blank=True)
    user = models.ForeignKey(settings.AUTH_USER_MODEL)

In my app, this class is used to represents two types of folders: a normal folder-object and a so called root_folder-object, which does not have a parent nor a root-FK set.

I created a custom ModelForm with custom clean(), which is working like a charm (according to unittests and manual testing):

class FolderForm(ModelForm):

    def __init__(self, *args, **kwargs):
        try:
            data = kwargs.get('data', None).copy()
        except AttributeError:
            data = None
        self.prefix = kwargs.get('prefix')
        user = kwargs.pop('user', None)

        if data is not None:
            if user is not None:
                data[self.add_prefix('user')] = user.id
            kwargs['data'] = data

        super(FolderForm, self).__init__(*args, **kwargs)

    def clean(self):
        # just working fine, so I won't include it here
        pass

    class Meta:
        model = Folder
        fields = '__all__'

So, because my root-folder is just a normal Folder-object with blank FKs, I don't want to even show these fields to the user while creation. I created another form for this:

class AddRootFolderForm(FolderForm):
    class Meta:
        model = Folder
        exclude = ['parent', 'root', 'user']

As you can see, I exclude user aswell, this value will be set in the view. Currently, this is my view code:

@login_required
def create_rootfolder(request):
    if request.method == 'POST':
        form = FolderForm(data = request.POST,
                          user = request.user)
    else:
        form = AddRootFolderForm()

    if form.is_valid():
        new = form.save()
        return redirect('show_rootfolder', root_id = new.id)

    return render(request, 'create_rootfolder.html',
                  { 'form': form })

This whole setup is working, but seems awful hackerish. Is there any better approach to hide certain fields from the user (meaning: Don't even show them as hidden fields), but include them in validation? My main problem is, that I can't use the same form for displaying and validating, because the excluded fields will not be validated, if I use AddRootFolderForm as single form instance.

I am aware that I can exclude the fields dynamically in the constructor, I even tried this, but it got my constructor bloated to 50 LOC, which seemed unclean.

So what would be the best approach to validate the model with all fields, even if they were not included in the form shown to the user?

How to use Django ORM to function on a field

This question is a follow-up to this one.

I'm running a Django application on top of a MySQL (actually MariaDB) database.

My Django Model looks like this:

from django.db import models
from django.db.models import Count, Sum

class myModel(models.Model):
    my_string = models.CharField(max_length=32,)
    my_date = models.DateTimeField()

    @staticmethod
    def get_stats():            
        logger.info(myModel.objects.values('my_string').annotate(
                count=Count("my_string"), 
                sum1=Sum('my_date'),
                sum2=Sum(# WHAT GOES HERE?? #),
            )
        )

When I call get_stats, it gives me the count and the sum1. However, for sum2, I want the sum of the following Database expression for each matching row: my_date + 0 (this converts it to a true integer value).

What should I put in the expression above to get that sum returned in sum2?

Django UpdatView - custom form fields

I have my UpdateView for updating some of my data.

class WpisUpdate(UpdateView):
model=ProdukcjaStanTb
fields=[
        'temat',
        'podtemat',
        'proc_wym',
        'proc_auto',
        'proc_palnik',
        'proc_uruch',
        'proc_pakowanie',
        ]

Now, in my template I'd like to have only :

'proc_wym',
'proc_auto
'proc_palnik',
'proc_uruch',
'proc_pakowanie',

Fields, but also have access to fields "temat" and "podtemat" (to make big titles or web page title for example). In template i'm using {{form.temat.value}} tags, which are ok, but requires those fields in field list in UpdateView. I don't want user to change that. Is there any quick way to have those fields hidden in form but accessible while using easy:

{{ form.as_p }}

in template ? Or do i have to manually edit my form and add some html attributes, like read-only or input type="hidden" ?

ImportError: no module named guardian

I'm new to Django, so generally I am the cause of most of my problems, but I can't figure out why the django-guardian 1.3 app won't install. I'm using Django 1.7 in a virtual environment, my OS is Windows 8.1.

I followed the installation directions at http://ift.tt/1TSMzxP and configuration at http://ift.tt/1LLuNHg, but I get an error when I attempt to run the program.

I added 'guardian', ANONYMOUS_USER_ID, and the backends to my settings.py

"""
Django settings for VolunteerManager project.
For more information on this file, see
http://ift.tt/WG84IA
For the full list of settings and their values, see
http://ift.tt/1s34S5Z
"""

# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
import os
BASE_DIR = os.path.dirname(os.path.dirname(__file__))


# Quick-start development settings - unsuitable for production
# See http://ift.tt/WG84IC

# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'Super Super Secret'

# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True

TEMPLATE_DEBUG = True

ALLOWED_HOSTS = []
ANONYMOUS_USER_ID = -1

# Application definition

INSTALLED_APPS = (
#DEFAULT APPS
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',

#THIRD PARTY APPS
    'guardian',
    'registration',
        #Copyright (c) 2007-2012, James Bennett
        #All rights reserved.
    'django.contrib.sites',

#LOCAL APPS
    'Volunteer',
)

ACCOUNT_ACTIVATION_DAYS = 7 # One-week activation window;
REGISTRATION_AUTO_LOGIN = True # Automatically log the user in.

MIDDLEWARE_CLASSES = (
    'django.contrib.sessions.middleware.SessionMiddleware',
    'django.middleware.common.CommonMiddleware',
    'django.middleware.csrf.CsrfViewMiddleware',
    'django.contrib.auth.middleware.AuthenticationMiddleware',
    'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
    'django.contrib.messages.middleware.MessageMiddleware',
    'django.middleware.clickjacking.XFrameOptionsMiddleware',
)

AUTHENTICATION_BACKENDS = (
    'django.contrib.auth.backends.ModelBackend', 
    'guardian.backends.ObjectPermissionBackend',
)

ROOT_URLCONF = 'VolunteerManager.urls'


#ANONYMOUS_USER_ID = 'VOLUNTEER_USER_ID'

WSGI_APPLICATION = 'VolunteerManager.wsgi.application'


# Database
# http://ift.tt/1s34S6b

DATABASES = {
    'default': {
        'ENGINE': 'django.db.backends.mysql',
        'NAME': 'volunteer',
        'USER': 'root',
        'PASSWORD': '$',
        'HOST': 'localhost',   # Or an IP Address that your DB is hosted on
        'PORT': '3306',
    }
}

# Internationalization
# http://ift.tt/WG863i

LANGUAGE_CODE = 'en-us'

TIME_ZONE = 'UTC'

USE_I18N = True

USE_L10N = True

USE_TZ = True


# Static files (CSS, JavaScript, Images)
# http://ift.tt/1s34R23

STATIC_URL = '/static/'

TEMPLATE_DIRS = [os.path.join(BASE_DIR, 'templates')]

LOGIN_REDIRECT_URL = '/home/'

SITE_ID = 1

Error picture available on IMGUR

Django-guardian appears to be installed in my virtual environment, but it's still not finding it. Any ideas what I might have done wrong? (Or other suggestions for per-object permissions in Django?) Thank You!

UPDATE: I narrowed the problem down to the virtualenv. When I installed the modules without using virtualenv, then django finds them like it should. I'm still not sure what exactly I did wrong, but this works for now, considering that I'm only working on one project at the moment.

Why is serving static files insecure

This might be a stupid question and have an obvious answer, but I was testing my 404 and 500 error handlers meaning that I had to switch debug to False. I went to Django admin page and noticed that static files are not being served.

I understand that they should be routed through Apache as serving static files through Django is insecure. However, I don't quite understand why is it a security risk to serve static files through Django directly?

Django] I don't understanding about Nginx's advantages

I'm newbie in the dev world. I had developed small project by using Django And now trying to deploying the project from my local dev environment to the AWS EC2 instance. In addition I've choose Nginx server for performance up.

But I've a question. The role of Nginx is to serve efficiently a static files and a media files to the client. If I using AWS S3 storages for serving them, Is nginx has necessary? If so, Is there others features?

samedi 27 juin 2015

Error import spatial data in GeoDjango - KeyError for mpoly field

I was following the tutorial on http://ift.tt/1NnlWfX for setting up GeoDjango on my machine. But it seems like there is some issue there. While importing data using LayerMapping using load.run() from python shell, I get the following error:

Traceback (most recent call last):
  File "<console>", line 1, in <module>
  File "/home/ubuntu/src/django/world/load.py", line 23, in run
    lm = LayerMapping(WorldBorder, world_shp, world_mapping, transform=False, encoding='iso-8859-1')
  File "/home/ubuntu/Envs/vir-env/local/lib/python2.7/site-packages/django/contrib/gis/utils/layermapping.py", line 105, in __init__
    self.check_layer()
  File "/home/ubuntu/Envs/vir-env/local/lib/python2.7/site-packages/django/contrib/gis/utils/layermapping.py", line 178, in check_layer
    ogr_field_types = self.layer.field_types
  File "/home/ubuntu/Envs/vir-env/local/lib/python2.7/site-packages/django/contrib/gis/gdal/layer.py", line 153, in field_types
    for i in range(self.num_fields)]
KeyError: 12

Then I found out that, there is no 'MULTIPOLYGON' field in the .shp file:

>>> from django.contrib.gis.gdal import DataSource
>>> ds = DataSource('world/data/TM_WORLD_BORDERS-0.3.shp')
>>> layer = ds[0]
>>> layer.fields
[u'FIPS', u'ISO2', u'ISO3', u'UN', u'NAME', u'AREA', u'POP2005', u'REGION', u'SUBREGION', u'LON', u'LAT']

So, definitely in the world_mapping file, importing will fail for the 'mpoly': 'MULTIPOLYGON' mapping. Has anyone else faced this issue? I hope so, as I've followed the tutorial step-by-step. But it doesn't say anything about such issue.

Here's my load.py file:

  1 import os
  2 from django.contrib.gis.utils import LayerMapping
  3 from models import WorldBorder
  4
  5 world_mapping = {
  6     'fips' : 'FIPS',
  7     'iso2' : 'ISO2',
  8     'iso3' : 'ISO3',
  9     'un' : 'UN',
 10     'name' : 'NAME',
 11     'area' : 'AREA',
 12     'pop2005' : 'POP2005',
 13     'region' : 'REGION',
 14     'subregion' : 'SUBREGION',
 15     'lon' : 'LON',
 16     'lat' : 'LAT',
 17     'mpoly' : 'MULTIPOLYGON',
 18 }
 19
 20 world_shp = os.path.abspath(os.path.join(os.path.dirname(__file__), 'data/TM_WORLD_BORDERS-0.3.shp'))
 21
 22 def run(verbose=True):
 23     lm = LayerMapping(WorldBorder, world_shp, world_mapping, transform=False, encoding='iso-8859-1')
 24
 25     lm.save(strict=True, verbose=verbose)

django listing files instead of showing home page

I'm not able to figure out what's going wrong. I'm using pycharm and bitnami django stack for developing my first web application.

Here is my directory structure:

project name: myapp

location: C:\Bitnami\djangostack-1.7.8-0\apache2\htdocs\myapp

Directory structure:

myapp
    manage.py
    app
          admin.py
          models.py
          settings.py
          tests.py
          urls.py
          views.py
          wsgi.py

          migrations
    templates
          home.html

my settings.py has following data:

INSTALLED_APPS = (
    'django.contrib.admin',
    'django.contrib.auth',
    'django.contrib.contenttypes',
    'django.contrib.sessions',
    'django.contrib.messages',
    'django.contrib.staticfiles',
    'app',
)

ROOT_URLCONF = 'app.urls'

TEMPLATE_DIRS = (
    os.path.join(BASE_DIR, 'templates'),
)

my urls.py has following data:

from django.conf.urls import url

from . import views

urlpatterns = [
    url(r'myapp/', views.homepage, name='home'),
]

my views.py has following data:

from django.http import HttpResponse


def homepage(request):
    return HttpResponse("Hello, world!")

Now when I try to run:

http://localhost/myapp

It simply displays the list of files in the myapp directory

I'm not able to find why it is not executing from urls.py

Does Django ManyToManyField create table with a redundant index?

If I have a model Foo that has a simple M2M field to model Bar:

class Foo(Model):
    bar = ManyToManyField(Bar)

Django seems to create a table foo_bar which has the following indices:

index 1: primary, unique (id)
index 2: unique (foo_id, bar_id)
index 3: non_unique (foo_id)
index 4: non_unique (bar_id)

I recall from my basic knowledge of SQL, that if a query needs to look for conditions on foo_id, index 2 would suffice (since the left-most column can be used for lookup). index 3 seems to be redundant.

Am I correct to assume that index 3 does indeed take up index space while offering no benefit? That I'm better off using a through table and manually create a unique index on (foo_id, bar_id), and optionally, another index on (bar_id) if needed?