Find Django Database in the PC - python

I am trying to create a django project and I created a simple model and ran the django server, entered the fields. I can see all the data on the django server. I was wondering if there is any other way to see the data entered.
This is the data I entered. Can I view it anywhere else in tabular form or database form?
This is what I do in command window:
sqlite3 db.sqlite3
followed by
.tables
Where db.sqlite3 is the file that was created when I migrated. I am not sure if the data I entered on django server is in this file.
Thanks in advance.
EDIT
This is my models.py:
class Site(models.Model):
# Site ID
siteID = models.CharField(max_length=255, null=False)
# End Device ID
edevID = models.CharField(max_length=255, null=False)
After running python
manage.py runserver
I am directed to the django page where I enter the following data
And I save this. My question is how can I access this saved data in a database. I tried what you recommended Satya, it only shows me the superuser id.
I hope the question is clear now.

You can install this software. After installation, select your sqlite and see your complete database.
DB Browser for SQLite
Download from here: DB Browser

The question doesn't give enough information as to what you're trying to look for. I am assuming that you want more information out of the tables you've created and that you are using the default sqlite3 database. In your models.py file, you can use the special __str__ method to make your objects more descriptive
def __str__(self):
return self.title #if your using 'title' as the attribute to identify your objects
Also,
enter this command in cmd
python manage.py shell
and then in the shell, import the Model whose database you want to view
for e.g.
>>> from django.contrib.auth.models import User
>>> User.objects.all()
This will display all the data associated with your table. Unfortunately, not in tabular form. You can aso use the command python manage.py inspectdb to view all the classes associated with all tables. To view in proper tabular form, you might need phpmyadmin.

Related

How to create a cron job in Django to run a script that scrapes data from a website and updates a PostgreSQL database?

So I am currently implementing my very first Django-based web app. However, I figured that I only need Django to perform a backend cron job to scrape data from a website and then update existing data in a PostgreSQL database. Then I just use a React frontend to retrieve data from the database and visualize it on the webpage.
My issue now is that I don't know how to conceptually tackle this challenge. Currently, I have a model in my models.py file that successfully created my empty table in PostgreSQL:
from django.db import models
# Create your models here.
class rainAreas(models.Model):
Country = models.CharField(max_length=100)
HasRain= models.BooleanField()
Since = models.DateField()
class Meta:
app_label = "rain_areas"
I also filled the table manually with dummy data. Finally, I have a script in my admin.py file, which successfully creates the desired list of data scraped from a website. It looks like this:
my_data = [{"country": "Germany", "HasRain": True, "Since": "2020-08-11"}, {"country": "France",....
But now I am stuck. What is the next move to
make an SQL UPDATE on the table I created with the data I have in admin.py
transform this script to a cron job which should run every hour
there are basically two options:
try to use celery
write a custom admin comand
Adding celery might add to much complexity.
if you go for the second option you have to ensure to use the correct python environment in your script/ in the cronjob check this answer
Updating the entries would be first retrieving and then saving the new value
for d in my_data:
rainArea = RainArea.objects.get(country=d['country'])
rainArea.has_rain = d['HasRain']
rainArea.since = datetime.strptime(d['Since'], '%y-%m-%d')
rainArea.save()
Please note that i slightly refactored the wording to better follow pep8:
in python classes start uppercase
django models are singular named and not plural (RainArea)
attributes usually don't start with uppercase

django table has no column named Exception

Git Repository
Request to guide me on what to do.
I work on an e-commerce website with the help of Django. and I'm a beginner in Django
The following image provides a table of my database. It helps to add a product
Shows me an error in the browser. This error shows me when I add a product inside the admin panel. It helps to add a product but when I add the product the following error occurs.
An error occurred while migrating
Request to guide me on what to do.
After first migrations,if you add any field that can not be null you must provide a default value. Your desc field is not nullable, so you must add default='some_value' inside your desc field.
Do you have the table ready and set up? Because the error says, that there is a table named shop_product, but it does not have a column named product_name.
So the structure of your table would get us closer to the solution of your problem.
Edit:
I have just seen, that you supplied your Git repo. I looked at the database and what I wrote above holds true. Your shop_product table has no columns. I did not look through your code to see if it would be set up automatically, but I suppose you were supposed to create the columns by hand, right?
Take a look at here (Django Migrations Workflow)
I've seen your migrations folder on your Github repo and there was no sign of any of the fields you mentioned.
Every time you add fields to your models, you need to run following commands in terminal
python manage.py makemigrations <app name>
python manage.py migrate
These commands are going to modify your tables.
Please markdown your question instead of putting a picture from your code.
Check this out: How do I ask a good question?
EDIT:
In your Product model, there is a field named desc. You need to set a default value for it; Otherwise, you need to update the records in your database manually.
desc = models.CharField(max_length=300, default='')
After you do that, this error will happen to the pub_date field too. So, if your current Product objects in your database are not important, you can simply delete the database file db.sqlite3 and delete your migrations file from this address shop/migrations/0001_initial.py and try the migration commands again.

Add data to custom django user model

I am new to web devolopment and django. Currently I am developing a simple dashboard web application for our computational cluster and have configured a custom user model, which looks like this:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
processor_hours = models.FloatField(null=True, blank=True)
All of the default user fields are taken from our ldap server, and authentication works. However, I want to add data to the custom field for each user. I have a text file with the information in columns,
username1 hours
username2 hours
I tried using the manage.py shell to run a python script and add the data to the corresponding fields but it doesn't seem to be saving it to the database. What am I missing?
Edit: I wasn't saving the user with .save(). The issue is resolved, thanks for the help.

sqlite configuring with django

I have been assigned the task of setting up an online database with sqlite via django- where it will contain columns of information. My problem is that I can't figure out which is establishing table where the information will go- my models.py script or should I do it with a "CREATE TABLE" command?
An example of the code in my models.py script is below:
class Person(models.Model):
firstname=models.CharField(max_length=100)
lastname=models.CharField(max_length=100)
The tutorial that I was given recommended this command:
insert into freezer_person (firstname,last name) values('Louis','Pasteur')
However upon executing this command I naturally got an error saying "table does not exist" i.e. I have to use the "CREATE TABLE" command.
so when I tried:
"CREATE TABLE in freezer_person(...)"
It returned that "in" was syntactically incorrect.
So my question is how do I go about creating a table that will intake info from models.py?- I can't seem to find any info on this...
You don't create the tables; Django does it for you, through the migrations system.
This is all fully covered in the tutorial.
Your model classes from models.py define your tables: each model class will be transposed in a table. Each property of a model class will be a column in the corresponding table. Each instance of the model class will be a row in that table.
So when you want to create a table you define a model class in the models.py file of your app, then run
python manage.py makemigrations
which tracks the changes made to the model class and generate a migration file which contains the sql statements to be applied to the database, and then to apply them to the database, you run
python manage.py migrate

Django 1.6: Clear data in one table

I've a table name UGC and would like to clear all the data inside that table. I don't want to reset the entire app which would delete all the data in all the other models as well. Is it possible to clear only one single model? I also have South configured with my app, if that would help.
You could use raw SQL :
cursor.execute(“DROP TABLE UGC”)
or you could just use the ORM directly inside a Django shell :
UGCModel.objects.all().delete()
That would erase the data (not the table, though), so you have to be careful :)
Another way (for completeness and to make use of South) would be to comment out the model in your models declaration, migrate and then put it back again (assuming there are no models with a reference to it.)
HTH
In the admin interface, you can go to the list page for that model, then you can select all models and use the Delete selected ... action at the top of the table.
Remember that, in whatever way you delete the data, foreign keys default to ON DELETE CASCADE, so any model with a foreign key to a model you want to delete will be deleted as well. The admin interface will give you a complete overview of models that will be deleted.
Faced such issues today with django 2.0.2 because i created my model with
class Front(models.Model):
pass
and migrated it but when i later updated the model, i couldn't run
python manage.py makemigrations because it was saying
You are trying to add a non-nullable field 'update' to front without a default; we can't do that (the database needs something to populate existing rows).
Please select a fix:
1) Provide a one-off default now (will be set on all existing rows
with a null value for this column)
2) Quit, and let me add a default in models.py
Select an option:
What was my solution?
I choose option 2 which is to quit
I commented out the troublesome model/table which is Front in my case
I ran python manage.py makemigrations which deleted the troublesome table/model
I uncommented my model and ran python manage.py makemigrations again which recreated the table/model and finally
I migrated my changes with python manage.py migrate and everyhing was resolved!
Note: Be careful with the above instruction cause it will delete all references/foreign keys to the table/model with on_delete=models.CASCADE which is the default!
Django 3.1.14
If you're interested in doing it on the command line, and you'll be doing this type of cleaning of your db frequently, I do this:
# project_name/app_name/management/commands/clear_test_models.py
from django.core.management.base import BaseCommand
from django.apps import apps
keep_models = ['KeepModel0', 'KeepModel1']
class Command(BaseCommand):
"""
clear all in app_name app except listed in keep_models list
"""
help = 'clear all models except those listed in keep_models list'
def handle(self, *args, **kwargs):
my_app = apps.get_app_config('app_name')
my_models = my_app.get_models()
for model in my_models:
if model.__name__ not in keep_models:
model.objects.all().delete()
To run on the command line:
DJANGO_SETTINGS_MODULE=app_name.settings.local python manage.py clear_test_models

Categories