Displaying MySQL data on HTML page in Django - data not displaying - python

I am totally new to Django and I'm having a problem displaying data from a MariaDB MySQL database on a HTML page.
I have a legacy database called Vision which has a table within it called SensorResult. I have added this database to the settings.py file and made a routings folder with a router_db.py file to tell the app when to use the Vision database.
From this, I ran the following command:
python manage.py inspectdb --database=Vision
This returned a printout of each table within the database and all columns. I then used this to create a standard models.py file using this information as shown below:
from django.db import models
class Sensorresult(models.Model):
sensorresult = models.AutoField(db_column='SensorResult', primary_key=True) # Field name made lowercase.
sensorid = models.IntegerField(db_column='SensorID') # Field name made lowercase.
visionid = models.IntegerField(db_column='VisionID') # Field name made lowercase.
userinputid = models.IntegerField(db_column='UserInputID', blank=True, null=True) # Field name made lowercase.
value = models.FloatField(db_column='Value') # Field name made lowercase.
timestamp = models.DateTimeField(db_column='TimeStamp') # Field name made lowercase.
class Meta:
db_table = 'SensorResult'
From this, I used makemigrations and migrate commands to submit this model. Now I can open the Django Shell and query the database and get a response, which makes me think that the models.py, settings.py and db_routings.py files are all working correctly (please tell me if this is not the case)? An example of the shell commands and printout response I get is as follows:
python manage.py shell
>>> from authenticate.models import Sensorresult
>>> qs = Sensorresult.objects.using('Vision').get(sensorresult="1")
>>> qs.value
556746.0
From this I have created the following views.py file, which has an identical SQL command as that used in the shell:
from django.http import HttpResponse
from django.shortcuts import redirect, render
from .models import Sensorresult
def db(request):
qs = Sensorresult.objects.using('Vision').get(sensorresult='1')
return render(request, 'authenticate/instruments.html',{'qs':qs})
and then an instruments.html which is as follows:
<div class="overviewcard">
<div class="overviewcard__icon">Engine</div>
<div class="overviewcard__info">{{qs.value}}</div>
However for some reason I dont get any data displaying, just blank. I also have a URLs.py page which is as follows:
from django.urls import path, include
from . import views
from . import models
#used for routing within the app
#use the below format to add further pages
urlpatterns = [
path('instruments/', views.instruments, name="instruments"),
path('instruments/',views.db, name='db'),
]
I've been through loads of online tutorials and YouTube videos; however, none have worked so far. If anyone has any suggestions as to what is going wrong that would be greatly appreciated.

You should use unique paths for your url patterns or you will get conflicts, the first path is always matching so your db view is never called.
urlpatterns = [
path('instruments/', views.db, name='db'),
path('instruments/foo/', views.instruments, name="instruments"),
]
The url dispatcher iterates over your urlpatterns in order and returns the first one that matches the incoming path, if you have two patterns that could match the path then the first one will always be used

Related

Access Django DB objects without shell?

I have a request - can you help me access and manage django DB objects without using shell ?
I have created my models, but now (for example) i want to make a login system. I store users and passes(again, only an example), and i want to get the info from the DB, but i dont want to use shell.
What can i do in this case, im quite new to Django ?!
Best Regards
Why not use django-admin?
Maybe this is what you want:https://docs.djangoproject.com/en/3.0/ref/contrib/admin/
In views.py you can import
from .models import modelname
data = modelname.objects.all() - using this you can get all the data from the Database
Eg:-
for d in data:
print (d.email)
Will give all emails in the database
You can also use
t = modelname.objects.get(email='name#lk.com')
By this you can get the data of the person who's email is name#lk.com
Django already has database support where you can register your models and access them with a graphical interface.
See the documentation: django-admin-site
First you need to create a super user account, if you don't have one, create it with the terminal in the project directory, use this row:
python manage.py createsuperuser
For your model to appear on the admin site you need to register it
# models.py
class MyModel(models.Model)
field1 = models.CharField()
field2 = models.TextField()
# ...
# admin.py
from django.contrib import admin
from .models import MyModel
admin.site.register(MyModel)
So it's the basic way to register your model, if you want to personalize you need to check the documentation ModelAdmin.fieldsets
with this done, just access the admin site at the link http://localhost:8000/admin/ and log in with the super user account and you will see the model registered.

The distribution Django project runs different with the local project, get 1366, "Incorrect string value Error

The distribution Django project runs different with the local project.
I have a Django project, in it there is a create APIView, in my local repo, it works fine, but when I push the repo to the remote, then run it with
screen -d -m python3 -m Qy.wsgi
and if I access the create url, there comes the 500 Server Error error.
but in my local repo, it works fine.
related code are bellow:
model:
class Currency(models.Model):
name = models.CharField(max_length=16)
desc = models.CharField(max_length=128, null=True, blank=True)
standard_symbol = models.CharField(max_length=8)
ex_rate = models.DecimalField(decimal_places=4, default=0.0000, max_digits=10)
class Meta:
ordering = ['-standard_symbol']
def __str__(self):
return self.name
def __unicode__(self):
return self.name
apiview:
class CurrencyCreateAPIView(CreateAPIView):
serializer_class = CurrencySerializer
permission_classes = [IsSuperAdminOrFinanceAdmin]
queryset = Currency.objects.all()
serializer:
class CurrencySerializer(ModelSerializer):
class Meta:
model = Currency
fields = "__all__"
I just don't know why in the distribution it can not create with Chinese characters.
I means if I write in all number, such as:
name: 123, desc: 123, standard_symbol: 123, ex_rate:1233
it will create success.
or if there is English Characters it will works too, but if there is Chinese Character it will report the 500 Server Error. I use MySQL as database.
but in the local repo it will works if it contains Chinese Characters.
the remote repo code is as same as the local repo.
My local repo operation system: MacOS
My remote repo operation system: CentOS7.2
EDIT-1
My settings of wsgi.py is bellow:
import os
from django.core.wsgi import get_wsgi_application
os.environ.setdefault("DJANGO_SETTINGS_MODULE", "qy.settings")
import django
print("django.setup()")
django.setup()
from socketio import Middleware
from qysio.views import sio
django_app = get_wsgi_application()
application = Middleware(sio, django_app)
import eventlet
import eventlet.wsgi
eventlet.wsgi.server(eventlet.listen(('', 8000)), application)
EDIT-2
I set the DEBUG=True in settings.py, and I get the bellow error when edit(the same as use create ):
OperationalError at /api/productconfig/price_system/currency/1/edit/
(1366, "Incorrect string value: '\\xE4\\xBA\\xBA\\xE6\\xB0\\x91...' for column 'name' at row 1")
I see your Error 1366, "Incorrect string value:.
There is a famous error of charset error.
So, make sure of your database and table use utf-8 character set.
you can use
SHOW CREATE DATABASE your_database_name;
ALTER DATABASE your_database_name DEFAULT CHARACTER SET utf8;
check and alter the database character set.
use bellow for check and alter character set of table:
SHOW CREATE TABLE your_table_name;
ALTER TABLE your_table_name DEFAULT CHARACTER SET utf8;
and change your table field character set:
ALTER TABLE `your_table_name` CHANGE `table_field` `table_field ` VARCHAR( 45 ) CHARACTER SET utf8 COLLATE utf8_bin NOT NULL

Saving a Form to a Database (Django Python)

In my Django app I have a form with an email and a text area that needs to go into the database but am struggeling to do so. At the moment I have 2 different solutions in my code:
OK, let me write this from the beginning. Maybe it is better if you do the below steps with me now for an exercise.
Now, the correct way to do the above task (I try to clear this subject a little more because I know that many other people will read this problem and they can learn from this too. And it is important to understand it for your future tasks.
If you want to create a Form and you know that you will want to save the submitted data from that Form to the database, then of course you should start the whole task with creating a Model, thus a table for that in the database.
So, first you create a Model (which you will call ie. “Questions” in this case, since you want to call your Form ie. QuestionForm, so it is better if your Model and table will be related to that with their names too).
So your Model will be in your models.py file:
from django.db import models
# Create your models here.
class Questions(models.Model):
contact_email = models.EmailField(max_length=60)
question = models.CharField(max_length=600)
Then you will create a ModelForm from this in your forms.py file the following way:
from django import forms
from django.forms import ModelForm, Textarea
from . import models
class QuestionForm(ModelForm):
class Meta:
model = models.Questions
fields = ['contact_email', 'question']
widgets = {
'question': Textarea(attrs={'cols': 40, 'rows': 20}),
}
Then you create your view function in your views.py file:
from django.shortcuts import render, redirect
from . import forms
from . import models
from django.http import HttpResponse
def get_question(request):
form = forms.QuestionForm()
if request.method == 'POST':
form = forms.QuestionForm(request.POST)
if form.is_valid():
form.save()
return redirect(‘success.html’) # or you redirect anywhere you want to
else:
form = forms.QuestionForm()
return render(request, 'contact.html', {'form':form})
And at this point you will create your urlpattern in your urls.py to call the get_question view function. It will look like the following:
from django.conf.urls import url
from basic_app import views
# app_name = 'basic_app' # Important for referencing urls in HTML pages(use your own app_name here). But for this example task this is not important.
urlpatterns = [
url(r'^$', views.home, name='home'),
url(r'^questions/', views.get_question, name="questions_page"),
]
I hope I did not confuse you more. If you do the above steps, it should work for you. And you can create as many Forms as you want with the above steps and saving them easily in the Database.
The only other thing you have to have to run the above, is your 'contact.html' page which you already have and you already created.
(do not forget to run: python manage.py migrate)
So, I hope that you see, in the above example you do not mismatch fields and field names, and you do not get confused about what to save where. Since the Model and the Form is working together and created together with the same field names.

Creating a django rest API for my python script

I have a JSON file with data as such :
['dbname' : 'A', 'collection' : 'ACollection', 'fields' : ['name', 'phone_no', 'address']}
['dbname' : 'B', 'collection' : 'BCollection', 'fields' : ['name', 'phone_no', 'address', 'class']}
These are 2 examples amongst many other dictionaries of the same format.
I have a python code that does the following : Accepts 2 inputs from the user - phone_no and dbname. For example, the user enters phone_no as xxxxxxxxxx and dbname as A. The python code then reads the JSON file and matches the user input with the dictionary element having the name of the database as 'A'. It then opens the database 'A', opens the respective collection 'ACollection' and prints the respective fields of posts within the collection that have the phone_no value as xxxxxxxxxx. The databases are implemented with mongoDB.
I need to build a django rest api for this code. The end goal is to access the code from a browser. The user provides the 2 inputs in the browser and the code is executed, returning the data, which is displayed on the browser. I have gone through the django-rest framework documentation but I'm new to this whole concept and would like some guidance.
How do I implement these functions and create an API? What code should the models, serializers, views and urls files have related to my program?
models.py
from django.db import models
class App(object):
def __init__(self, phone_no, name, address, categories):
self.phone_no = phone_no
self.name = name
self.address = address
self.categories = categories
This is what I'm working with so far, to get started. The problem, however, is that the models class should essentially be dynamic. Ex: If 'A' is the database, the program returns 3 fields but if 'B' is the database, the program returns 4 values so I'm not sure what the models class would be like.
views.py
from django.views.decorators.csrf import csrf_exempt
from rest_framework.decorators import api_view
from rest_framework.response import Response
from pymongo import Connection
from models import App
from serializers import AppSerializer
import json
import pymongo
from os import listdir
import re
from django import forms
#csrf_exempt
#api_view(['GET'])
def pgs(request):
#connect to our local mongodb
db = Connection('localhost',27017)
#get a connection to our database
dbconn = db.general
dbCollection = dbconn['data']
if request.method == 'GET':
#get our collection
items = []
for r in dbCollection.find():
post = App(r["phone_no"],r["name"],r["address"],r["categories"])
items.append(post)
serializedList = AppSerializer(items, many=True)
return Response(serializedList.data)
Let's say you have identical tables in two different databases. We'd start by creating two db connections in settings.py. Let's say those are called db_a and db_b. We might model this as so:
class PhoneGenome(models.Model):
phone_no = models.CharField(length=255)
name = models.CharField(length=255)
# and so on...
class Meta:
# if database pre-exists, may want to use managed=False
managed = False
This gives us a model. Now we choose which database to pull from based on user input. In a view, you might have something like:
db_used = request.GET.get('database')
db_conns = {'a': 'db_a', 'b': 'db_b'}
if db_conns.has_key(db_used):
records = PhoneGenome.objects.using(db_conns[db_used]).filter( user_criteria_here)
The using() method in your queryset is what allows you to select which database to run the query against.
There's a lot to manage here potentially, so this would be a good time to look at the docs: https://docs.djangoproject.com/en/1.7/topics/db/multi-db/
And if you haven't already, you really should work through the Django tutorial at the very least before going much further.

How to set menus in Mezzanine Django

I have created a model.py file in which I define my classes like:
from django.db import models
from mezzanine.pages.models import Page
class Author(Page):
dob = models.DateField("Date of birth")
class Book(models.Model):
author = models.ForeignKey("Author")
cover = models.ImageField(upload_to="authors")
Then my HTML page and place it into templates folder define URL in urls.py file.
I run command python manage.py collecttemplates to get all templates
Now I browse 127.0.0.1/8000/page1/ to get my page view.
**Question 1: How to place this page in menu of home page using admin interface?
Question 2: How to solve this error 'NoneType' object has no attribute 'split' generates if I browse http://127.0.0.1:8000/admin/conf/setting/?
Question3 : How to access POST DATA from forms created in mezzanine interface?**
UPDATE:
from django.db import models
from mezzanine.pages.models import Page
class Author(Page):
dob = models.DateField("Date of birth")
class Book(models.Model):
author = models.ForeignKey("Author")
cover = models.ImageField(upload_to="authors")
and admin.py with these:
from django.contrib import admin
from mezzanine.pages.admin import PageAdmin
from .models import Author
admin.site.register(Author, PageAdmin)
Now i write these commands: python manage.py syncdb, python manage.py migrate,
and then open python shell to write Author.objects.create(dob = "12/12/2014")
That generates error that author is not defined. It's true because no tables created in my database.?!
I assume you're working through the Content Architecture tutorial on the Mezzanine site. The tutorial assumes a lot on your part, which is not ideal for a beginner. If you haven't seen it, you might want to take a look anyway. Here it is: http://mezzanine.jupo.org/docs/content-architecture.html
To answer Question#1: You add the new content type via the Pages admin: http://127.0.0.1:8000/admin/pages/page/ Select from the drop-down menus that read "Add..." to select its type and on the following configuration page you can select where you want it displayed as a menu link.
In response to your UPDATE:
At the Djanog/Mezzanine Python shell:
from <your app> import models
Then try models.Author.objects.create(title="Dr. Seuss")
No ideas on Questions #2 & #3 right now.

Categories

Resources