I want to create a blog site. I already created the homepage of the site and there is 4 articles on my blog site. I want to open an article by clicking on it and it will redirect me to the unique article page. Every article page has few images and headlines and line breakers. How will I upload these to my blog model using django?
Example article page...See the article page's picture
There's a few ways to do this, but I would recommend CKEditor for Django
For the Blog home page and Detail pages, look at django's class based views:
https://docs.djangoproject.com/en/3.2/ref/class-based-views/generic-display/
urls.py:
urlpatterns = [
path('', views.BlogListView.as_view(), name='blog_list'),
path('detail/<int:pk>', views.BlogDetailView.as_view(), name='blog_detail'),
]
# You can also use <slug:slug> instead of <int:pk>
views.py:
from blog.models import Blog
from django.views.generic import ListView, DetailView
class BlogListView(ListView):
model = Blog
class BlogDetailView(DetailView):
model = Blog
For the blog formatting page:
https://github.com/django-ckeditor/django-ckeditor
https://medium.com/djangotube/django-ckeditor-install-with-youtube-and-code-spinet-plugins-b873c643f649
Change up your message/body to a RichTextUploadingField and then you/users can format images with text as you see fit.
models.py
from ckeditor_uploader.fields import RichTextUploadingField
class Blog(models.Model):
title = models.CharField(max_length=100)
message = RichTextUploadingField()
In your settings follow the GitHub guide to setup CKEditor and you're also going to have to add MEDIA_URL and MEDIA_ROOT to your settings.py and project urls.py files.
https://docs.djangoproject.com/en/3.2/howto/static-files/
project/settings.py
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
project/urls.py
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URLconf goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Related
I'm working on a bookstore using Django. I'm trying to save each book's cover in each book created by the user using imagefield. I implemented every step in Django documentation about using imagefield but it doesn't work.
settings.py(in main project):
MEDIA_DIR = os.path.join(BASE_DIR,'media')
MEDIA_ROOT = MEDIA_DIR
MEDIA_URL = '/media/'
in urls.py (main project):
from django.contrib import admin
from django.urls import include, path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path("admin/", admin.site.urls),
path("", include("book.urls")),
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
in models.py(the book app):
class books(models.Model):
cover = models.ImageField(upload_to='cover/co', blank=True)
When I want go admin I find that the photo is submitted (when I click on the photo url in database nothing is shown to me) but I don't find any created media folders and when I try to request the image in any template It isn't showed to me.
when I try to click on the photo in the database in admin this is shown to me:
enter image description here
These are the paths of the app, project and static:
enter image description here
I don't know where is the problem and how to solve it as this is my first time to use imagefiled in django model,,, it might be from the paths, the model or the urls so if there is any help.
Remove / at the beginning of your MEDIA_URL.
Simply you can try this way:
settings.py file:
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR,'media')
In models.py file:
class books(models.Model):
cover = models.ImageField(upload_to='cover/', blank=True) #I have removed co from here
After adding above code don't forget to migrate
Try this and see if this is solves your problem
I'm trying to accomplish something I believed would be simple: upload an image (via admin), then use the complete URL in a template to display the image.
The problem is I can only print the relative URL: /pics/filename.jpg. I believe the sequence is settings.py (MEDIA_ROOT, MEDIA_URL), urls.py, views.py and then mytemplate.html.I hope someone can find what's missing.
Settings:
STATIC_URL = '/static/'
MEDIA_ROOT = '/Users/ed/code/projects/djcms/pics/'
MEDIA_URL = '/pics/'
Urls.py:
from django.conf import settings
from django.conf.urls.static import url, static
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^news/(?P<pk>[0-9]+)/$', views.detail, name='detail'),
] + static(r'^$/pics/', document_root = settings.MEDIA_URL)
Views.py
def detail(request, pk):
story = Article.objects.get(pk=pk)
my_pic = Photo.objects.get(pk=pk)
print(story.image.url)
print(my_pic)
print(story.body)
print(request)
context = {'story': story}
return render(request, 'articles/detail.html', context)
The Error with story.image.url:
AttributeError: 'Photo' object has no attribute 'url'
When I remove the .url, I get this partial URL:
pics/intro-bg.jpg
What am I missing? Thanks.
This setup is working for me, maybe it will help you. It is for latest version of Django. Many answers in OS are for older Django versions.
URLS:
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
#url
]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Settings:
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
Template:
<img src="{{ foo.image.url }}"><br>
Model:
image = models.ImageField(upload_to = 'img/', default = 'img/None/no-img.jpg')
My foo model has an imagefield, when it is stored, I can retrieve the full url through item.image.url based on the above setup.
In urls.py, try: static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The URLS seem to be causing the problem.
from django.conf import settings
from django.conf.urls.static import url, static
from . import views
urlpatterns = [
url(r'^$', views.index, name='index'),
url(r'^news/(?P<pk>[0-9]+)/$', views.detail, name='detail'),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
The logic behind those URL patterns displays my homepage and individual news articles. Each news article has a url of /news/, followed by the article number, i.e. /news/1.
Each article uses my Photo model via a ForeignKey in the Article model. This allows a photo to be tied to a specific article.
However, in my template, the URL is a jumble of news and images:
http://localhost:8000/news/2/img/phones.png.
The news URL correctly finds the news item but not the image associated with the news item. The correct result would display the individual article along with its associated image. Do I need another URL?
The Request object in Django has a method, build_absolute_uri() Using this method you can get absolute url of the image field.
So to get the absolute url, you can use two methods
First method: Getting absolute url in view while doing GET request.
from settings import MEDIA_URL
class ClassName(APIView):
def get(self, *args, **kwargs):
model = models.ModelName.objects.get(name='pran')
absolute_url = self.request.build_absolute_uri('/').strip("/") + MEDIA_URL + str(model.image_field_name)
return Response({'url': absolute_url}, 200)
Method 2: If you are doing POST request and you are using serializer then pass request as context object to it.
ser = serializers.MySerializerName(data=request.data}, context={'request': request})
I am working on this project on django,i have this model which have few char fields and a text field. What i want to know is is there anyway i can edit the appearance of the text field in django admin panel so that i can edit what i write in that text field like the one in word press where you get options to make a text bold or insert links and images.
I tried this module called grappelli but it just changes the appearance of my admin panel adding colors and decorative stuffs.
class Heading(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=5000)
content = models.TextField()
date = models.DateField(default=datetime.now())
def __str__(self):
return self.title
use ckeditor
https://github.com/django-ckeditor/django-ckeditor
on shell:
pip install django-ckeditor
on settings.py:
add 'ckeditor' on INSTALLED_APPS
on models.py:
from ckeditor.fields import RichTextField
class Heading(models.Model):
content = RichTextField()
You can use django-summernote
https://github.com/summernote/django-summernote
step 1: Install django-summernote
pip install django-summernote
step 2: Add django_summernote to INSTALLED_APP in settings.py.
INSTALLED_APPS = [
'django_summernote',
'...',
]
step 3: Add django_summernote.urls to project urls.py.
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
# ...
urlpatterns = [
...
path('summernote/', include('django_summernote.urls')),
...
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
step 4: Give MEDIA_URL in your settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
step 5: on admin.py
from django.contrib import admin
from django_summernote.admin import SummernoteModelAdmin
from .models import Heading
class HeadingAdmin(SummernoteModelAdmin):
summernote_fields = ('content',)
admin.site.register(Heading, HeadingAdmin)
step 6: Run database migration
python manage.py migrate
I have created a page where a user can add a new item (notes in this case) and I am making use of CBV which I have recently started learning.
This is my model form
class NoteForm(forms.ModelForm):
class Meta:
model = Note
fields = ('title', 'note', 'tags')
This is the view in views.py
class NoteCreate(CreateView):
model = Note
form_class = NoteForm
template_name = "add_note.html"
Then this is the url as I used in the urls.py of the app
from django.conf.urls import patterns, url
from . import views
from madNotes.views import NoteCreate, NoteIndex,
urlpatterns = patterns(
'',
url(r'^notes/add/$', NoteCreate.as_view(), name="new_note"),
url(r'^$', NoteIndex.as_view()),
url(r'^(?P<slug>\S+)/$', views.NoteDetail.as_view(), name="entry_detail"),
)
NB: I used the same url as the main page at 127.0.0.1:8000 in the projects urls.py file and it worked.
I have seen several tutorials and even the docs and can't seem to find what I am doing wrong. Will I also need to add a function in order for it to be saved in the db or the CBV will do it all?
EDit: The error I get is this
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/notes/add/
Here is the project's urls.py
from django.conf.urls import patterns, include, url
from django.contrib import admin
from MadNotez import settings
from registration.backends.default.views import RegistrationView
from madNotes.forms import ExRegistrationForm
if settings.DEBUG:
import debug_toolbar
urlpatterns = patterns('',
url(r'^__debug__/', include(debug_toolbar.urls)),
url(r'accounts/register/$', RegistrationView.as_view(form_class = ExRegistrationForm), name='registration_register'),
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^admin/', include(admin.site.urls)),
url('^markdown/', include('django_markdown.urls')),
url('^notes/', include('madNotes.urls')),
#url(r'^$', views.NoteCreate.as_view(), name="new note"), when I used it here it worked
)
you say that is the urls.py of the app, which means it is included by the project's urls.py.
As you show now, all the app's URIs go under the notes prefix:
url('^notes/', include('madNotes.urls')),
so as things stand at present the correct URI for the page is
http://127.0.0.1:8000/notes/notes/add/
In order to clean things up a bit, I'd suggest to modify the app's urls.py to
url(r'^add/$', NoteCreate.as_view(), name="new_note"),
so that the page can be reached at
http://127.0.0.1:8000/notes/add/
This way all the app's pages/services are available under the notes prefix and with a simple name that is consistent with their action (i.e. add, delete, etc)
I have a simple Django admin page that uploads images to a product description. Everything works until I try to view the image by clicking on its path in the products information. I get this error:
Page not found (404)
Request URL: http://0.0.0.0:6666/the_image.jpg
I'm guessing I need to declare something in urls.py, but I have no idea where to start. I also tried changing my media paths in settings.py but I always get errors if I change to anything other than '/'
model.py
class Image(models.Model):
product_image = models.ForeignKey(Product)
image = models.ImageField(upload_to='/')
settings.py
MEDIA_ROOT = '/'
MEDIA_URL = '/'
admin.py
class InlineImage(admin.TabularInline):
model = Image
class ProductAdmin(admin.ModelAdmin):
inlines = [InlineImage]
Docs are here https://docs.djangoproject.com/en/dev/ref/settings/#media-root
You need to set MEDIA_ROOT and MEDIA_URL in your settings file like this
MEDIA_ROOT = /var/www/example.com/media/
MEDIA_URL = /media
and your upload_to should probably be the model name or something to identify it.
image = models.ImageField(upload_to='image')
Then the link should point the /media/image/NAME_OF_IMAGE.png
You will also need to have urls.py setup to server media files. For production you would want to do this in nginx with an alias. See https://docs.djangoproject.com/en/dev/howto/static-files/#serving-files-uploaded-by-a-user-during-development
Which says:
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = patterns('',
# ... the rest of your URLconf goes here ...
) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)