I am using MYSQL for the database. I want to upload my imagefield files in media folder that I have created in my project. I am getting "empty path didn't exist".
settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
models.py
class Product(models.Model):
category = models.ForeignKey(Category, related_name='product', on_delete=models.CASCADE)
created_by = models.ForeignKey(User, on_delete=models.CASCADE, related_name='product_creator')
title = models.CharField(max_length=255)
author = models.CharField(max_length=255, default='admin')
description = models.TextField(blank=True)
image = models.ImageField(upload_to='images/')
slug = models.SlugField(max_length=255)
price = models.DecimalField(max_digits=4, decimal_places=2)
in_stock = models.BooleanField(default=True)
is_active = models.BooleanField(default=True)
created = models.DateTimeField(auto_now_add=True)
updated = models.DateTimeField(auto_now=True)
class Meta:
verbose_name_plural = 'Products'
ordering = ('-created',)
def __str__(self):
return self.title
urls.py
from django.contrib import admin
from django.urls import path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I have registered the model successfully in admin.py.
your code:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
test this:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
I fixed this error by deleting the 'MEDIA_URL' and 'MEDIA_ROOT' path in settings.py file that I had previously added. The above code is then working.
Related
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')
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>
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 }}
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.
I get this error "employee_directory.thumbnail_kvstore' doesn't exist" when I use sorl-thumbnail to try and format my django admin profile image. Has anyone ran into this while working with sorl-thumbnail and django admin changelist?
DatabaseError at /directory/employee/
(1146, "Table 'employee_directory.thumbnail_kvstore' doesn't exist")
I doubled checked my sorl-thumbnail installation, and made sure I did a syncdb. Below is the code from my models.py and admin.py
models.py:
from django.db import models
from sorl.thumbnail import ImageField
# Department Table
class Department(models.Model):
department_name = models.CharField(max_length=128)
def __unicode__(self):
return self.department_name
# Employee Directory Table
class Employee(models.Model):
last_name = models.CharField(max_length=32)
first_name = models.CharField(max_length=32)
profile_image = models.ImageField(upload_to="images/profile_image", blank=True)
department_name = models.ForeignKey('Department')
job_title = models.CharField(max_length=64)
office_number = models.CharField(max_length=8, blank=True)
fax_number = models.CharField(max_length=8, blank=True)
mobile_number = models.CharField(max_length=8, blank=True)
intercom_number = models.CharField(max_length=3, blank=True)
email = models.CharField(max_length=128)
memo = models.TextField(blank=True)
def __unicode__(self):
return self.last_name + ', ' + self.first_name
admin.py:
from directory.models import *
from django.contrib import admin
from sorl.thumbnail import get_thumbnail
class EmployeeAdmin(admin.ModelAdmin):
def profile_img(self, obj):
if obj.profile_image:
t = get_thumbnail(obj.profile_image,"50x50",crop='center', quality=99)
return u'<img src="/media%s"/>' % t.url
else:
return u'profile_image'
profile_img.short_description = 'Profile image'
profile_img.allow_tags = True
search_fields = ['last_name', 'first_name']
list_display = ['profile_img', 'last_name', 'first_name', 'department_name',
'job_title', 'office_number', 'fax_number',
'mobile_number', 'intercom_number', 'email']
list_filter = ['department_name']
admin.site.register(Department)
admin.site.register(Employee, EmployeeAdmin)
Any help is greatly appreciated.
I totally noobed out, I forgot to put sorl.thumbnail in my apps in the django settings.