Valentin Valentin - 8 days ago 3
Python Question

'unicode' object has no attribute '_meta' with Django

I spent all the day and this night in order to solve this error :

AttributeError at /Identity/formulaire_edit
'unicode' object has no attribute '_meta'
Request Method: GET
Request URL: http://localhost:8000/Identity/formulaire_edit?csrfmiddlewaretoken=DvKCCaaAYsiWykEtYHrpgNu4AKlXS16DttEc5csQOT9BtQs4Ll4AviLDhi3MaBId&q4=2
Django Version: 1.10
Exception Type: AttributeError
Exception Value:
'unicode' object has no attribute '_meta'
Exception Location: /Library/Python/2.7/site-packages/django/forms/models.py in model_to_dict, line 82
Python Executable: /usr/bin/python
Python Version: 2.7.10
Python Path:
['/Users/valentinjungbluth/Desktop/Django/Etat_civil',
'/Library/Python/2.7/site-packages/pip-9.0.1-py2.7.egg',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python27.zip',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-darwin',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/plat-mac/lib-scriptpackages',
'/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-tk',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-old',
'/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/lib-dynload',
'/System/Library/Frameworks/Python.framework/Versions/2.7/Extras/lib/python/PyObjC',
'/Library/Python/2.7/site-packages']
Server time: jeu, 1 Déc 2016 07:48:15 +0000
Traceback Switch to copy-and-paste view

/Library/Python/2.7/site-packages/django/core/handlers/exception.py in inner
response = get_response(request) ...
▶ Local vars
/Library/Python/2.7/site-packages/django/core/handlers/base.py in _get_response
response = self.process_exception_by_middleware(e, request) ...
▶ Local vars
/Library/Python/2.7/site-packages/django/core/handlers/base.py in _get_response
response = wrapped_callback(request, *callback_args, **callback_kwargs) ...
▶ Local vars
/Users/valentinjungbluth/Desktop/Django/Etat_civil/Identity/views.py in Identity_Update
form = IdentityForm(request.POST or None, instance = query_update)


I cannot use my function and I think that's because the attempt value should be a raw integer, but I need to put this variable which is an integer. It's the value returned by user :

# models.py

#-*- coding: utf-8 -*-

from django.db import models

######################################
# Choix à l'utilisateur pour le sexe #
######################################

SEX_CHOICES = (
('M', 'Mâle'),
('F', 'Femelle')
)
##########################################
# Choix à l'utilisateur pour la civilité #
##########################################

TITLE_CHOICES = (
('Mr', 'Monsieur'),
('Mlle', 'Mademoiselle'),
('Mme','Madame'),
('Dr','Docteur'),
('Me','Maître'),
)

###################################################
# Création d'une table répertoriant tous les pays #
###################################################

class Country(models.Model):

code = models.CharField(max_length=3, null=False) # Example : 'FR' - 'US'
pays = models.CharField(max_length=50, null=False) # Example : 'France' - 'Etats-Unis'

def __unicode__(self):
#return '%s %s %s' % (self.id, self.code, self.pays)
return self.pays

####################################################################################
# Création d'une table permettant de renseigner toutes les informations concernant #
# les parents et reprise de celles des enfants #
####################################################################################

class Identity(models.Model):

title = models.CharField(max_length=12,choices=TITLE_CHOICES, verbose_name='Civilité')
lastname = models.CharField(max_length=30, verbose_name='Nom de famille')
firstname = models.CharField(max_length=30, verbose_name='Prénom(s)')
sex = models.CharField(max_length=1, choices=SEX_CHOICES, verbose_name='sexe')
birthday = models.DateField(verbose_name='Date de naissance')
birthcity = models.CharField(max_length=30, verbose_name='Ville de naissance')
birthcountry = models.ForeignKey(Country, related_name='Pays_naissance', verbose_name='Pays de Naissance')
nationality = models.CharField(max_length=30, verbose_name='Nationalité')
job = models.CharField(max_length=30, verbose_name='Profession')
adress = models.CharField(max_length=30, verbose_name='Adresse')
city = models.CharField(max_length=30, verbose_name='Ville')
zip = models.IntegerField(verbose_name='Code Postal')
country = models.ForeignKey(Country, related_name='Pays1', verbose_name='Pays')
mail = models.CharField(max_length=30, verbose_name='Email', blank=True)
phone = models.CharField(max_length=20, verbose_name='Téléphone', blank=True)

def __unicode__(self):
return '%s %s %s %s %s %s %s %s %s %s %s %s %s %s %s %s' % (self.id, self.title, self.lastname, self.firstname, self.sex, self.birthday, self.birthcity, self.birthcountry,
self.nationality, self.job, self.adress, self.city, self.zip, self.country, self.mail, self.phone)


My forms.py file :

#-*- coding: utf-8 -*-

from django import forms
from .models import *

class IdentityForm(forms.ModelForm) :

class Meta :
model = Identity
fields = '__all__'


My views.py file about
Identity_Update()
function :

def Identity_Update(request) :

query_update = request.GET.get('q4')
print query_update

if query_update :
query_update_list = Identity.objects.filter(pk=query_update) #Identity.objects.only('id').filter(pk=query_update) to get only the ID number
print query_update_list

else :
query_update_list = Identity.objects.none() # == []

form = IdentityForm(request.POST or None, instance = query_update)

if form.is_valid():
form.save()
return HttpResponseRedirect('accueil')

template_name = 'edit.html'

context = {
"query_update" : query_update,
"query_update_list" : query_update_list,
"form":form
}
return render(request, template_name, context)


And this is my html template :

<!-- ############################################## -->
<!-- Modifier un formulaire dans la Base de Données -->
<!-- ############################################## -->

<h2 align="center"> Modification des fiches individuelles </align> </h2>

{% block content %}

<h4> ID du formulaire à modifier : </h4>

<form method="GET" action="">{% csrf_token %}
<input type="text" name="q4" placeholder="Entrer un ID" value="{{ request.GET.q4 }}">
<input type="submit" value="Valider l'ID">
</form>

<ul>
{% for item in query_update_list %}
<li>{{item}}</li>
{% endfor %}
</ul>
<br></br>

<h4> Modification du formulaire : </h4>

<form method='POST' action= "" > {% csrf_token %}

{{form.as_ul}}

<input type ="submit" value="Valider" />
</form>

{% endblock %}


Could you help me to find a solution ? I blocked on this problem since yesterday.

Answer

The problem is that you're passing in a string for an instance (query_update).

form = IdentityForm(request.POST or None, instance = query_update)

Instead you need to pass in the single instance that your form is supposed to be updating

query_update_list.first() would probably get the one you need.