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.
Related
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
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.
I'm new to Django and I'm using Pycharm Community 2018.1 to do my project.
While I was doing the first tutorial where you set up a model and corresponding admin page, Pycharm keeps showing this reference error which is perfectly fine when you look at the directory and the structure.
Is this what I get for using free Pycharm instead of paid Professional edition?
However, I know I'm a newb so I might be wrong here. Is it normal to get this error message in this situation?
I took a screenshot of error message(the left screen) and working Admin page(right screen) and here are my codes for models.py and admin.py
models.py (there is no problem with it)
from __future__ import unicode_literals
from django.db import models
from django.utils.encoding import python_2_unicode_compatible
# Create your models here.
#python_2_unicode_compatible
class Bookmark(models.Model):
title = models.CharField(max_length = 100, blank = True, null = True)
url = models.URLField('url', unique = True)
def __str__(self):
return self.title
admin.py (you can see unresolved reference error)
from django.contrib import admin
from bookmark.models import Bookmark
# Register your models here.
class BookmarkAdmin(admin.ModelAdmin):
list_display = ('title', 'url')
admin.site.register(Bookmark, BookmarkAdmin)
This warning can be solved by opening your actual project directory
Go to File->Open. Then choose your project directory, that is mysite and you are opened pyneer_django directory
It's nothing with the community edition
I have created an app in a django project. This app has four models. I can add/modify/delete from admin site for all four models. But for one of the four models (say - ModelXYZ), I need to add a custom button for each entry in this table. Currently, I can see "Save", "Delete", etc. buttons for each entry present in ModelXYZ table.
I need to add another button "Run", clicking on it will execute a python script written in that app only. Currently, I am running that script like this -
python manage.py shell
>>> execfile("my_app/my_script_1.py")
>>> execfile("my_app/my_script_2.py")
The script name is also stored in ModelXYZ table for each entry.
Django docs say that the admin site is customizable, but I am not very sure how can I run a python script by clicking on a button.
You can write a custom command:
https://docs.djangoproject.com/en/1.9/howto/custom-management-commands/
Then from your code call the command with call_command:
https://docs.djangoproject.com/en/1.9/ref/django-admin/#django.core.management.call_command
To call from the admin, you can create a custom action: https://docs.djangoproject.com/en/1.9/ref/contrib/admin/actions/
I solved it like this and it solves my purpose :-
class Site(models.Model):
name = models.CharField(null=False, blank=False, max_length=256, unique=True)
script = models.CharField(null=False, blank=False, max_length=256)
def __unicode__(self):
return u"{0}".format(self.name)
Then in my_app/admin.py, I wrote:-
from django.contrib import admin
from .models import *
def run(self, request, queryset):
id=request.POST.get('_selected_action')
siteObj=self.model.objects.get(pk=id)
self.message_user(request, "Running: " + siteObj.script)
execfile(siteObj.script)
run.short_description = "Run the script"
class SiteAdmin(admin.ModelAdmin):
actions = [run]
model = Site
# Register your models here.
admin.site.register(Site, SiteAdmin)
I have to make some modification to a website built with the django framework (version 1.6).
The problem I am having is that I can not transfer the modification I made offline to the online server. I can see the new page, the database has been modified, but in the administration website the new category I created does not appear, thus i can not fill the fields with the new information.
The steps I went through are:
create the new model in models.py,
import the model in admin.py,
execute the command: touch wsgi.py
in order to reload the file.
In the offline version everything is working fine. I do not know that to do!
Code I added in admin.py file (I added the "Article" section):
from active.models import x, z, y, j, Article
class ArticleAdmin(admin.ModelAdmin):
ordering = ["title"]
list_display = ('title',)
search_fields = ['title']
admin.site.register(Article, ArticleAdmin)
Solved.
There was no problem at all, simply the user I access the administration site with did not have the right access to see the new section!
Have you imported admin in the admin.py file?
from django.contrib import admin