Django model.objects.all does not show information - python

I am using django to make a webapp and I am trying to learn how to make queries.
I already connected my SQLServer database to django, and from the SQL Management studio added information for the 3 tables that I have. Then I ran python manage.py inspectdb, copied the results in my blog.models.pyand put python manage.py makemigrations and then migrate
However, when I open the python shell via python manage.py shell, import the models and make a `model.objects.all(), the result is the following:
<QuerySet [<Usuario: Usuario object (1)>, <Usuario: Usuario object (2)>]>
Django identifies that I have 2 objects created, but whenever I try to get specific information from one of them it shows the following:
>>> Usuario.objects.all()
<QuerySet [<Usuario: Usuario object (1)>, <Usuario: Usuario object (2)>]>
>>> user= Usuario.objects.all()
>>> user[0]
<Usuario: Usuario object (1)>
>>> user[0].ID_Usuario
Traceback (most recent call last):
File "<console>", line 1, in <module>
AttributeError: 'Usuario' object has no attribute 'ID_Usuario'
>>>
This is the information that I inserted via SQL Management studio
INSERT INTO Usuario(ID_Usuario,Nombre,Apellido,Edad,Email,Password,ID_Cargo,ID_Rol)
VALUES(1,'Pepe','Arana',36,'pepe#hotmail.com','pass',1,1),
(2,'Roquito','Velarde',40,'roquito#hotmail.com','pass',2,1)
Why isn't django recognizing the attributes but it is recognizing the fact that an object has been created?
Thanks
EDIT: This are the models in the blog.model.py file
class Cargo(models.Model):
id_cargo = models.IntegerField(db_column='ID_Cargo', primary_key=True) # Field name made lowercase.
nombre = models.CharField(db_column='Nombre', max_length=100, blank=True, null=True) # Field name made lowercase.
descripcion = models.CharField(db_column='Descripcion', max_length=100, blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'Cargo'
class Rol(models.Model):
id_rol = models.IntegerField(db_column='ID_Rol', primary_key=True) # Field name made lowercase.
nombre = models.CharField(db_column='Nombre', max_length=100, blank=True, null=True) # Field name made lowercase.
descripcion = models.CharField(db_column='Descripcion', max_length=100, blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'Rol'
class Usuario(models.Model):
id_usuario = models.IntegerField(db_column='ID_Usuario', primary_key=True) # Field name made lowercase.
nombre = models.CharField(db_column='Nombre', max_length=100, blank=True, null=True) # Field name made lowercase.
apellido = models.CharField(db_column='Apellido', max_length=100, blank=True, null=True) # Field name made lowercase.
edad = models.IntegerField(db_column='Edad', blank=True, null=True) # Field name made lowercase.
email = models.CharField(db_column='Email', max_length=100, blank=True, null=True) # Field name made lowercase.
password = models.CharField(db_column='Password', max_length=100, blank=True, null=True) # Field name made lowercase.
id_cargo = models.ForeignKey(Cargo, models.DO_NOTHING, db_column='ID_Cargo', blank=True, null=True) # Field name made lowercase.
id_rol = models.ForeignKey(Rol, models.DO_NOTHING, db_column='ID_Rol', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'Usuario'

user[0].ID_Usuario
You are getting an error because ID_Usario is not defined in the models. ID_Usario is an only a column name in the database.
But in the model, you have defined as id_usuario.
Replace this with
user[0].id_usuario

Related

InvalidCursorName : Django Admin error referencing wrong column in ForeignKey

I've setup a relationship using django's ForeignKey against 2 unmanaged tables like so:
class Product(BaseModel):
publish_name = models.CharField(unique=True, max_length=40)
# this works:
associated_country = models.ForeignKey('geonames.Countryinfo', models.DO_NOTHING, db_column='published_country', blank=True, null=True)
# this doesn't:
associated_continent = models.ForeignKey('geonames.Continentcodes', on_delete=models.DO_NOTHING, db_column='published_continent' blank=True, null=True)
class Meta:
managed = True
db_table = 'product'
class Continentcodes(models.Model):
code = models.CharField(max_length=2, primary_key=True, unique=True)
name = models.TextField(blank=True, null=True)
geoname_id = models.ForeignKey('Geoname', models.DO_NOTHING, blank=True, null=True, unique=True)
class Meta:
managed = False
db_table = 'geoname_continentcodes'
class Countryinfo(models.Model):
iso_alpha2 = models.CharField(primary_key=True, max_length=2)
country = models.TextField(blank=True, null=True)
geoname = models.ForeignKey('Geoname', models.DO_NOTHING, blank=True, null=True)
neighbours = models.TextField(blank=True, null=True)
class Meta:
ordering = ['country']
managed = False
db_table = 'geoname_countryinfo'
verbose_name_plural = 'Countries'
When I go to edit an entry in the django admin page for 'Products' I see this:
InvalidCursorName at /admin/product/6/change/ cursor
"_django_curs_140162796078848_sync_5" does not exist
The above exception (column geoname_continentcodes.geoname_id_id does
not exist LINE 1: ...ntcodes"."code", "geoname_continentcodes"."name",
"geoname_c...
^ HINT: Perhaps you meant to reference the column
"geoname_continentcodes.geoname_id"
It looks like it's trying to reference geoname_continentcodes.geoname_id_id for some reason. I have tried adding to='code' in the ForeignKey relationship, but it doesn't seem to effect anything.
Additionally, the associated_country relationship seems to work just fine if I comment out the associated_continent field. The associated_continent is the column that is giving some problem.
Here is some more context about what the table looks like in the database:
Removing the '_id' as the suffix is the fix. In this case geoname_id changed to geoname fixes this. Why? I have no idea. Django is doing something behind the scenes that is not clear to me. Here is the updated model:
class Continentcodes(models.Model):
code = models.CharField(max_length=2, primary_key=True, unique=True)
name = models.TextField(blank=True, null=True)
# remove '_id' as the suffix here
geoname = models.ForeignKey('Geoname', models.DO_NOTHING, blank=True, null=True, unique=True)
class Meta:
managed = False
db_table = 'geoname_continentcodes'
Django adds _id to the end to differentiate between the object and the id column in the table, geoname_id will return the table id where as geoname will return the object.

How to avoid error while using list_display in django

I need to get view of table in admin.
I imported table from Mysql. In models.py code is written:
class Stations2(models.Model):
id_stations = models.IntegerField(db_column='ID_stations', primary_key=True) # Field name made lowercase.
name = models.TextField(db_column='Name', blank=True, null=True) # Field name made lowercase.
type = models.TextField(db_column='Type', blank=True, null=True) # Field name made lowercase.
country = models.TextField(db_column='Country', blank=True, null=True) # Field name made lowercase.
latitude = models.FloatField(db_column='Latitude', blank=True, null=True) # Field name made lowercase.
longitude = models.FloatField(db_column='Longitude', blank=True, null=True) # Field name made lowercase.
elevation = models.IntegerField(blank=True, null=True)
site_gaw_id = models.TextField(blank=True, null=True)
stations_id = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'stations_2'
I wrote in admin.py:
from django.contrib import admin
from .models import Stations2
class data_admin(admin.ModelAdmin):
model = Stations2
list_display = ('Name', 'Type',)
admin.site.register(Stations2,data_admin)
and got an error:
ERRORS:
<class 'scrapping_2.admin.data_admin'>: (admin.E108) The value of 'list_display[0]' refers to 'Name', which is not a callable, an attribute of 'data_admin', or an attribute or method on 'scrapping_2.Stations2'.
<class 'scrapping_2.admin.data_admin'>: (admin.E108) The value of 'list_display[1]' refers to 'Type', which is not a callable, an attribute of 'data_admin', or an attribute or method on 'scrapping_2.Stations2'.
without data_admin code work well. How Should I solve my problem?

How can I add a button inside DetailView template that sends ID to a form?

I have a App called "Properties" and I've created a DetailView that is working. Inside my Properties models I have a Property model and a Bedroom model with a ForeignKey to Property.
#views.py
class PropertyDetailView(DetailView):
template_name = 'properties/property-detail.html'
model = Property
def get_context_data(self, **kwargs):
contacts = ContactsOwner.objects.filter(owner__property=self.object)
context = super().get_context_data(**kwargs)
context['contact'] = contacts
return context
My models.py:
class Property(models.Model):
property_reference = models.CharField(db_column='Property_Reference', max_length=10) # Field name made lowercase.
address = models.CharField(db_column='Address', max_length=250, blank=True, null=True) # Field name made lowercase.
post_code = models.CharField(db_column='Post_Code', max_length=15, blank=True, null=True) # Field name made lowercase.
type = models.CharField(db_column='Type', max_length=25, blank=True, null=True, choices=HOUSE_TYPE_CHOICES) # Field name made lowercase.
bedrooms = models.IntegerField(db_column='Bedrooms', blank=True, null=True) # Field name made lowercase.
bathrooms = models.IntegerField(db_column='Bathrooms', blank=True, null=True) # Field name made lowercase.
usual_cleaning_requirements = models.CharField(db_column='Usual_Cleaning_Requirements', max_length=250, blank=True, null=True) # Field name made lowercase.
notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase.
feature_image = models.ImageField(null=True)
class Meta:
db_table = 'Property'
def __str__(self):
return self.property_reference
def get_absolute_url(self):
return reverse("properties:property_detail",kwargs={'pk':self.pk})
class Bedroom(models.Model):
type = models.CharField(db_column='Type', choices=BEDROOM_TYPE_CHOICES, max_length=50)
bed_dimensions = models.CharField(db_column='Bed_Dimension', choices=BED_DIMENSION_CHOICES, max_length=30)
image = models.ImageField(null=True, blank=True)
ensuite = models.BooleanField(default=False)
notes = models.CharField(db_column='Notes', max_length=500, blank=True, null=True) # Field name made lowercase.
property = models.ForeignKey(Property, null=False, on_delete=models.CASCADE, related_name='bedroom')
What I need is to create a button named "Add Bedroom" inside the template "property-detail.html" that sends me to a form with pre filled Foreign Key. Could you please help me on this?
You need to redirect that button submit to a view that gets the required info you want and then redirect that to another template with context the info you received (your Foreign key per se)

Django BD error

Hi guys i´m using Django 1.7 and mysql to create an application and I´m receiving this error
ValueError at /Cannot create form field for 'radiotipo_idradiotipo' yet, because its related model u'Radioinfo' has not been loaded yet
I don´t know what is this. this error happenes on my forms.py, here´s the code:
forms.py
from django import forms
from models import Node, Datasource, Radio, Radiotipo, Snapshot, Tag, Taginfo, Valores
class NodeForm(forms.ModelForm):
class Meta:
model = Node
class DatasourceForm(forms.ModelForm):
class Meta:
model = Datasource
class RadiotipoForm(forms.ModelForm):
class Meta:
model = Radiotipo
class SnapshotForm(forms.ModelForm):
class Meta:
model = Snapshot
class TagForm(forms.ModelForm):
class Meta:
model = Tag
class TaginfoForm(forms.ModelForm):
class Meta:
model = Taginfo
class ValoresForm(forms.ModelForm):
class Meta:
model = Valores
class RadioForm(forms.ModelForm):
class Meta:
model = Radio
and here is my models.py
class Datasource(models.Model):
objects = GChartsManager()
idestacao_meteo = models.IntegerField(db_column='idDATASOURCE', primary_key=True, editable=False) # Field name made lowercase.
nome_estacao = models.CharField(db_column='NAME', max_length=45) # Field name made lowercase.
fabricante = models.CharField(db_column='MANUFACTURER', max_length=45, blank=True) # Field name made lowercase.
modelo = models.CharField(db_column='MODEL', max_length=45, blank=True) # Field name made lowercase.
node_idnode = models.ForeignKey('Node', db_column='site_idSITE', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'datasource'
class Node(models.Model):
objects = GChartsManager()
idnode = models.IntegerField(db_column='idSITE', primary_key=True, editable=False) # Field name made lowercase.
nome = models.CharField(db_column='NAME', max_length=45) # Field name made lowercase.
informacoes = models.CharField(db_column='DESCRIPTION', max_length=45, blank=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'site'
class Radio(models.Model):
objects = GChartsManager()
idradio = models.IntegerField(db_column='idRADIO', primary_key=True, editable=False)
endreal = models.CharField(db_column='ENDREAL', max_length=64, blank=True) # Field name made lowercase.
radiotipo_idradiotipo = models.ForeignKey('Radioinfo', db_column='radioInfo_idRADIOINFO') # Field name made lowercase.
datasource_idestacao_meteo = models.ForeignKey(Datasource, db_column='datasource_idDATASOURCE', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'radio'
class Radiotipo(models.Model):
objects = GChartsManager()
idradiotipo = models.IntegerField(db_column='idRADIOINFO', primary_key=True, editable=False) # Field name made lowercase.
nome = models.CharField(db_column='NAME', max_length=45)
descricao = models.CharField(db_column='DESCRIPTION', max_length=300, blank=True)
class Meta:
managed = False
db_table = 'radioinfo'
class Snapshot(models.Model):
objects = GChartsManager()
idsnap = models.IntegerField(db_column='idSNAP', primary_key=True, editable=False) # Field name made lowercase.
valor = models.FloatField(db_column='VALUE', blank=True, null=True) # Field name made lowercase.
snapshot = models.DateTimeField(db_column='SNAPSHOT', blank=True, null=True) # Field name made lowercase.
tag_idtag = models.ForeignKey('Tag', db_column='tag_idTAG') # Field name made lowercase.
class Meta:
managed = False
db_table = 'snapshot'
class Tag(models.Model):
objects = GChartsManager()
idtag = models.IntegerField(db_column='idTAG', primary_key=True, editable=False) # Field name made lowercase.
desvio = models.FloatField(db_column='DEVIATION', blank=True, null=True) # Field name made lowercase.
tempo_max = models.IntegerField(db_column='TIME_MAX', blank=True, null=True) # Field name made lowercase.
conv_rate = models.IntegerField(db_column='CONV_RATE', blank=True, null=True) # Field name made lowercase.
taginfo_idtaginfo1 = models.ForeignKey('Taginfo', db_column='tagInfo_idTAGINFO') # Field name made lowercase.
datasource_idestacao_meteo = models.ForeignKey(Datasource, db_column='datasource_idDATASOURCE', blank=True, null=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'tag'
class Taginfo(models.Model):
objects = GChartsManager()
idtaginfo = models.IntegerField(db_column='idTAGINFO', primary_key=True, editable=False) # Field name made lowercase.
nome = models.CharField(db_column='NAME', max_length=45) # Field name made lowercase.
descricao = models.CharField(db_column='DESCRIPTION', max_length=255, blank=True) # Field name made lowercase.
class Meta:
managed = False
db_table = 'taginfo'
class Valores(models.Model):
objects = GChartsManager()
idvalores = models.IntegerField(db_column='idVALUES', primary_key=True, editable=False) # Field name made lowercase.
valor = models.FloatField(db_column='VALUE') # Field name made lowercase.
datahora = models.DateTimeField(db_column='DATETIME') # Field name made lowercase.
tag_idtag = models.ForeignKey(Tag, db_column='tag_idTAG') # Field name made lowercase.
class Meta:
managed = False
db_table = 'values'
Thanks for helping.
The radiotipo_idradiotipo is a foreign key to a model called "RadioInfo", but you don't have any model called that: only one called "Radiotipo". Is that the one you meant?
Change:
radiotipo_idradiotipo = models.ForeignKey('Radioinfo', db_column='radioInfo_idRADIOINFO') # Field name made lowercase.
By:
radiotipo_idradiotipo = models.ForeignKey('Radiotipo', db_column='radioInfo_idRADIOINFO') # Field name made lowercase.
Notice that you are using the table_name instead of the Model_Name for the foreingkey

Can't update existing record in django

I need to update existing recode in the database.I'm using mysql.
this my model class
class SuSurey(models.Model):
#id = models.IntegerField(db_column='ID', primary_key=True) # Field name made lowercase.
su_name = models.CharField(db_column='su_Name', max_length=30) # Field name made lowercase.
description = models.CharField(db_column='Description', max_length=500, blank=True) # Field name made lowercase.
duration = models.IntegerField(db_column='Duration') # Field name made lowercase.
audience = models.CharField(db_column='Audience', max_length=20, blank=True) # Field name made lowercase.
start_date = models.CharField(db_column='Start_date', max_length=50, blank=True) # Field name made lowercase.
end_date = models.CharField(db_column='End_date', max_length=50, blank=True) # Field name made lowercase.
create_date = models.CharField(db_column='Create_date', max_length=50, blank=True) # Field name made lowercase.
update_date = models.CharField(db_column='Update_date', max_length=50, blank=True) # Field name made lowercase.
create_by = models.IntegerField(db_column='Create_by', blank=True, null=True) # Field name made lowercase.
update_by = models.IntegerField(db_column='Update_by', blank=True, null=True) # Field name made lowercase.
def __unicode__(self):
return self.su_name
class Meta:
managed = False
db_table = 'su_surey'
i didn't use any forms in my web application. In my view.py i have this
if request.method == 'POST':
date=request.POST.get('dates','').split('-')
survey_data=SuSurey.objects.get(id=survey_id)
survey_data.su_name=request.POST.get('Name','')
survey_data.description=request.POST.get('Description','')
survey_data.duration=request.POST.get('Duration','')
survey_data.audience=request.POST.get('Audience','')
survey_data.start_date=date[0]
survey_data.end_date=date[1]
survey_data.update_date=datetime.datetime.today()
survey_data.update_by=request.session['user_login_data']['id']
try:
survey_data.full_clean()
survey_data.save(update_fields=['su_name','description','duration','audience','start_date','end_date','update_date','update_by'])
messages={'success':'Successfuly data added'}
url = reverse('addQuestionSurveys', kwargs={'survey_id': survey_id })
return HttpResponseRedirect(url)
except ValidationError as e:
messages={'error':e.messages}
return render(request, 'pages/forms/newSurvey.html',{'dept_data': dept_data,'messages': messages},context_instance=RequestContext(request))
when i add data Django did update the recode that is find by survey_id recode. it will add new recode to database.how can i fix this problem ? need a quick help thank you.

Categories

Resources