Display data with Django - mysql

I'm a beginner at Django and Python.
I'm trying to query a MySQL database.
Entering the data from the admin section works fine. Queering the database doesn't give an error, but it doesn't work.
I tried querying from shell, and it worked perfectly. However, querying from the code section doesn't.
The models.py looks like this:
class Courses(models.Model):
course_title = models.CharField(max_length=200)
course_image = models.ImageField(upload_to='course_images/')
course_duration = models.TimeField()
def __str__(self): return self.course_title
The views.py looks like this;
from django.shortcuts import render
from .models import Courses
def homepage(request):
cos = Courses.objects.all()
context={
'courses': cos
}
return render(request, "main/home.html", context)
The home.html looks like this:
{% for cos in courses %}
{{cos}}
{% endfor %}
I tried using Courses.objects.all and also Courses.objects.all() but it still won't work.
The urls.py looks like this:
from django.urls import path
from . import views
app_name = "main"
urlpatterns = [
path("", views.homepage, name="homepage"),
path('about/', views.about, name='about'),
path('home/', views.home, name'home'),
]
The projects urls.py is:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [ path('admin/', admin.site.urls),
path('', include('main.urls')),
]
I really need some assistance.

Related

Question for starting django web (beginner))

I have experienced problem in creating my own page on django. I follow the tutorial but get the different results. The error is page not found and Using the URLconf defined in djangonautic.urls, Django tried these URL patterns, in this order:
admin/
about/
^$
The empty path didn’t match any of these.It would be appreciate if someone can help me:
urls.py
from django.contrib import admin
from django.urls import path
from. import views
urlpatterns = [
path(r'^admin/', admin.site.urls),
path(r'^about/$', views.about),
path(r'^$', views.homepage),
path(r'^$', views.index),
]
views.py
from django.http import HttpResponse
from django.shortcuts import render
def about(request):
return HttpResponse('my name is Jacky')
def homepage(request):
return HttpResponse('welcome home')
def index(request):
return HttpResponse("Hello, world I am the king")
The web page will be display normally, no 404 is found
First, the import in urls.py (in your app directory) should be,
from . import views
Secondly, you do not really need to specify a URL path for the admin page, so better to get rid of that from your urls.py file as that is handled by django in the urls.py file in the appname/url.py file.
Third, ensure that in your projectname/urls.py file, you have included the path to your urls.py file in appname/urls.py file.
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('inventory.urls')),
]

Page not found (404) Request Method: GET trying to click to another .html file

I've done so much research I must have clearly missed something done or something wrong. The server I'm running is localhost:8000 It actually happens on all three .html files.
I've added the homepage everything works fine until I try to click on another html file and recieved.
Screenshot of the error message here Page not found (404) Request Method: GET trying to Using the URLconf defined in user.urls, Django tried these URL patterns, in this order:`
admin/
secret/
home/ [name='home']
home/ [name='contact']
home/ [name='Project']
^static/(?P<path>.*)$
index/Project.html.
Here's the root urls.py:
from django.contrib import admin
from django.urls import path, include
from django.conf.urls import url
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic import RedirectView
from portfolio_django import views
admin.autodiscover()
urlpatterns = [
path('admin/', include('admin_honeypot.urls', namespace='admin_honeypot')),
url('secret/', admin.site.urls),
path('home/', include("portfolio_django.urls")),
]+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
from django.urls import path
from portfolio_django import views
urlpatterns = [
path('', views.home, name='home'),
path('', views.contact, name='contact'),
path('', views.Project, name='Project')
views.py
from django.shortcuts import render
# Create your views here.
def home(request):
return render(request, 'home.html')
def Portfolio(request):
return render(request, 'Project.html')
def contact(request):
return render(request, 'contact.html')
You are receiving error 404 because you haven't defined a url pattern for http://localhost:8000
You need to change path('home/', include("portfolio_django.urls")) to path('', include("portfolio_django.urls"))
and change the following:
path('', views.home, name='home'),
path('contact/', views.contact, name='contact'),
path('project/', views.Project, name='Project')

How to filter database table using link <a href=''> in django?

I try to show a page with posts from that category when the user clicks on a link to a certain category
This is mine urls.py file:
from django.urls import path
from .views import PostHomeView,PostDetail,NavFooter,PostPageView
urlpatterns = [
path('navbar', NavFooter, name='Nav_Footer'),
path('', PostHomeView.as_view(), name ='home'),
path('PostDetail/<int:pk>', PostDetail.as_view(), name ='post_detail'),
path('PostPage/', PostPageView, name ='post_page'),
]
This is mine view.py file
from django.shortcuts import render
from django.http import HttpResponse
from django.views.generic import ListView,DetailView
from .models import Post, TaskCategory
def NavFooter(request):
return render(request,"nav_footer.html", {})
class PostHomeView(ListView):
model = Post
context_object_name = 'post'
template_name = 'home.html'
def get_queryset(self):
return Post.objects.order_by('task_title')[:9]
def PostPageView(reguest):
posts = Post.objects.all()
category = TaskCategory.objects.all()
return render(reguest,'post_page.html',{'posts':posts,'category':category})
class PostDetail(DetailView):
model = Post
template_name = 'post_detail.html'
This is models.py file:
from django.contrib.auth.models import User
from django.db import models
class TaskCategory(models.Model):
category_title = models.CharField(max_length=50)
def __str__(self):
return self.category_title
class Post(models.Model):
task_category = models.ForeignKey(TaskCategory, on_delete=models.CASCADE)
recommended_tools = models.CharField(max_length=250)
budget = models.CharField(max_length=250)
def __str__(self):
return self.task_title + ' | ' + self.task_discription + ' | ' + str(self.task_category) + ' |
' + self.recommended_tools + ' | ' + self.budget
The fastest way to access this file via html
first add another url route for category_detail
path('CategoryDetail/<int:pk>', CategoryDetail.as_view(), name ='category_detail'),
Next, add a view for this route
class CategoryDetail(DetailView):
model = TaskCategory
template_name = 'category_detail.html'
In the category_detail.html you can use something like this to display the posts:
<ul>
{% for post in object.post_set.all %}
<li>{{ post.id }}</li>
{% endfor %}
</ul>

html template show me empty page

when I try to run server th project th 1st pg which contains a list of names after I check one of them its suppose to show me details for this name but actually it does not work the pg was empty
can you please tell me what is my mistake?
thank u
project urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('new2/', include('new2.urls')),
]
app (new2) urls.py:
from django.contrib import admin
from django.urls import path,re_path
from new2 import views
urlpatterns = (
# path('admin/', admin.site.urls),
path('', views.index, name='index'),
re_path(r'(?P<task_id>[0-9]+)/$', views.details, name='details')
)
views.py:
from django.shortcuts import render
from django.http import HttpResponse
from .models import Task
from django.template import loader, RequestContext
from django.template.response import TemplateResponse
def index(request):
list_task = Task.objects.all()
template = loader.get_template('new2/index.html')
RequestContext = {
'list_task': list_task
}
return HttpResponse(template.render(RequestContext,request))
def details(request, task_id):
detail = Task.objects.get(pk=task_id)
RequestContext = {
'detail' : detail
}
return render(request,'new2/details.html',RequestContext)
models.py:
from django.db import models
class Task(models.Model):
def __str__ (self):
return self.Name_task
Name_task = models.CharField(max_length=200)
Age_task = models.CharField(max_length=200)
details.html:
{{Task.Name_task}}</br>
{{Task.Age_task}}
You passed the Task object as detail variable:
def details(request, task_id):
detail = Task.objects.get(pk=task_id)
context = {
'detail' : detail
}
return render(request,'new2/details.html', context)
so that means you render it in the template as:
{{ detail.Name_task }}</br>
{{ detail.Age_task }}

Getting an error 'redirect' on views.py of django project

All the registration form is running fine.The problem is on the redirect of function addUser.I am getting the error on redirect.I am trying to save the data in the admin panel but i am stuck on this.
from django.shortcuts import render,redirect
from django.http import HttpResponse
from .forms import RegistrationForm
from .models import RegistrationData
#from django.contrib.auth.form import UserCreationForm
# Create your views here.
def index(request):
return render(request, "Yatri/home.html")
def SignUp(request):
context= {"form":RegistrationForm}
return render(request,"Yatri/register.html",context)
def addUser(request):
form=RegistrationForm(request.POST)
if form.is_valid():
register=RegistrationData(username=form.cleaned_data['username'],
password=form.cleaned_data['password'],
email=form.cleaned_data['email'],
phone=form.cleaned_data['phone'],
register.save()
return redirect('index')
I expect the username,password,email and phone to be saved in database but i get the error the site cant be reached.
Urls.py
from django.contrib import admin
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.index, name='index'),
path('Signup/',views.SignUp,name='Signup'),
path('addUser/',views.addUser,name='addUser'),
]
missed parentheses in addUser view:
def addUser(request):
form=RegistrationForm(request.POST)
if form.is_valid():
register=RegistrationData(username=form.cleaned_data['username'],
password=form.cleaned_data['password'],
email=form.cleaned_data['email'],
phone=form.cleaned_data['phone'],)
register.save()
return redirect('index')