i'm having trouble displaying images on my Djnago admin page.
i read https://stackoverflow.com/questions/2443752/how-to-display-uploaded-images-in-change-list-page-in-django-admin/51181825#51181825 this article but still didn't get what i want :(
this is my codes
models.py
from django.contrib.auth.models import (
BaseUserManager, AbstractBaseUser, PermissionsMixin
)
from django.db import models
from django.utils.html import mark_safe
class User(AbstractBaseUser, PermissionsMixin):
image = models.ImageField(
upload_to='media/profile_image/',
null=True
)
admin.py
class UserAdmin(BaseUserAdmin):
# The forms to add and change user instances
form = UserChangeForm
add_form = UserCreationForm
def image_tag(self, obj): # Here
return format_html(
f'''<a href="{obj.image.url}" target="_blank">
<img
src="{obj.image.url}" alt="{obj.image}"
width="50" height="50"
style="object-fit: cover;"
/>
</a>''')
list_display = ('uid','get_full_name', 'email', 'nickname', 'introduce','image', 'birth','is_active', 'is_superuser', 'date_joined', 'image_tag')
...
this is what i got
the image is in my PROJECTNAME/media/profile_image but i cant' display it on my admin page :(
I solved the problem by adding
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
this on my urls.py
sorry for asking what i could solve it my self, but I will left this for someone who might have same problem...
thanks
Related
I am having two models projects and User in projects the User is related like shown below
models.py:
class project(models.Model):
user=models.OneToOneField(User,on_delete=models.CASCADE)
room = models.ForeignKey(room,on_delete=models.CASCADE)
goal = models.ManyToManyField(goal)
design = models.ManyToManyField(design)
furniture = models.ForeignKey(furniture,on_delete=models.CASCADE)
created_at = models.DateTimeField(default=datetime.now)
updated_at = models.DateTimeField(default=datetime.now)
Now here I want to display the extra column as projects in user page in django admin for every user when I click on that it should take to particular project detail page of that user
Screenshots:
This is the user list page
This is the project list page
This is the project detail page
admin.py:
from django.contrib import admin
from .models import project
class ProjectAdmin(admin.ModelAdmin):
readonly_fields = ('user','room','goal','design','furniture','created_at','updated_at')
admin.site.register(project,ProjectAdmin)
Please help me out Thanks in advance
You would need to write a custom admin for your User:
from django.contrib import admin
from django.contrib.auth import get_user_model
from django.contrib.auth.admin import UserAdmin
from django.utils.safestring import mark_safe
UserModel = get_user_model()
admin.site.unregister(UserModel)
#admin.register(UserModel)
class CustomUserAdmin(UserAdmin):
list_display = (
'username', 'email', 'first_name', 'last_name', 'user_project'
)
def user_project(self, obj):
url = '/admin/modsy/project/{}/change/'.format(obj.project.pk)
return mark_safe('view project'.format(url))
I would like to have on my Django 2.1.1 site django-filebrowser-no-grappelli. I've followed this indications but at the end of the procedure, when I restart my server, I've this error:
header_image = models.FileBrowseField("Image", max_length=200,
directory="images/", extensions=[".jpg"], blank=True) AttributeError:
module 'django.db.models' has no attribute 'FileBrowseField'
This are the files of my project:
MODELS.PY
from django.db import models
from django.urls import reverse
from tinymce import HTMLField
from filebrowser.fields import FileBrowseField
class Post(models.Model):
"""definizione delle caratteristiche di un post"""
title = models.CharField(max_length=70, help_text="Write post title here. The title must be have max 70 characters", verbose_name="Titolo", unique=True)
short_description = models.TextField(max_length=200, help_text="Write a post short description here. The description must be have max 200 characters", verbose_name="Breve descrizione dell'articolo")
contents = HTMLField(help_text="Write your post here", verbose_name="Contenuti")
publishing_date = models.DateTimeField(verbose_name="Data di pubblicazione")
updating_date = models.DateTimeField(auto_now=True, verbose_name="Data di aggiornamento")
header_image = models.FileBrowseField("Image", max_length=200, directory="images/", extensions=[".jpg"], blank=True)
slug = models.SlugField(verbose_name="Slug", unique="True", help_text="Slug is a field in autocomplete mode, but if you want you can modify its contents")
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse("singlearticleView", kwargs={"slug": self.slug})
class Meta:
verbose_name = "Articolo"
verbose_name_plural = "Articoli"
VIEWS.PY
from django.shortcuts import render
from .models import Post
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
class SingleArticle(DetailView):
model = Post
template_name = "single_article.html"
class ListArticles(ListView):
model = Post
template_name = "list_articles.html"
def get_queryset(self):
return Post.objects.order_by('-publishing_date')
URLS.PY
from django.urls import path
from .views import ListArticles, SingleArticle
urlpatterns = [
path("", ListArticles.as_view(), name="listarticlesView"),
path("<slug:slug>/", SingleArticle.as_view(), name="singlearticleView"),
]
ADMIN.PY
from django.contrib import admin
from .models import Post
class PostAdmin(admin.ModelAdmin):
"""creazione delle caratteristiche dei post leggibili nel pannello di amministrazione"""
list_display = ["title", "publishing_date", "updating_date", "id"]
list_filter = ["publishing_date"]
search_fields = ["title", "short_description", "contents"]
prepopulated_fields = {"slug": ("title",)}
fieldsets = [
(None, {"fields": ["title", "slug"]}),
("Contenuti", {"fields": ["short_description", "contents"]}),
("Riferimenti", {"fields": ["publishing_date"]}),
]
class Meta:
model = Post
admin.site.register(Post, PostAdmin)
URLS.PY PROJECT
from django.contrib import admin
from django.urls import path, include
from filebrowser.sites import site
urlpatterns = [
path('admin/filebrowser/', site.urls),
path('grappelli/', include('grappelli.urls')),
path('admin/', admin.site.urls),
path('', include('app4test.urls')),
path('tinymce/', include('tinymce.urls')),
]
I've started all of this because I will use TinyMCE and a file browser application is necessary. When I deactive the string header_image in models.py the project running well but, obviously, when I try to upload an image I've an error.
Where I made a mistake?
your import is done like this:
from filebrowser.fields import FileBrowseField
but you're trying to use the field following way:
header_image = models.FileBrowseField(...)
It's not part of the models package, just do it without the models. part:
header_image = FileBrowseField(...)
I want to use the {{ post.title }} and {{ for post in object_list }}
into my home template to show the latest 4 posts, I tried to import from blog.models import Post, but it doesn't work. I guess I'm putting it in the wrong place.
blog.models
from django.db import models
from ckeditor.fields import RichTextField
class Post(models.Model):
title = models.CharField(max_length = 140)
image = models.ImageField(upload_to="media", blank=True)
body = RichTextField(config_name='default')
date = models.DateField()
def __str__(self):
return self.title
home.urls
from django.urls import path
from . import views
urlpatterns = [
path('', views.HomePageView.as_view(), name='home'),
]
home.views
from django.views.generic import TemplateView
from allauth.account.forms import LoginForm
class HomePageView(TemplateView):
template_name = 'home/index.html'
mysite tree look like this
mysite
home
admin
app
models
tests
urls
views
blog
admin
app
models
tests
urls
views
You can override get_context_data and add the latest blog posts to the template context.
from blog.models import Post
class HomePageView(TemplateView):
template_name = 'home/index.html'
def get_context_data(self, **kwargs):
context = super(HomePageView, self).get_context_data(**kwargs)
context['object_list'] = Post.objects.order_by('-date')[:4]
return context
I am a beginner to Django.
I want to create a form that allow user to store their data to the database, but I face to an issue.
If I add data through Django admin, the data will shown correctly. But if I add data through my form. Data will store into database successfully but they don't shown in my Django admin.
Note: The Django version I used is 1.11.2
The is my Django admin page. There are 8 data in the database but just show the one I added by the Django admin.
views.py
from django.shortcuts import render
from django.views.generic import CreateView
from .forms import ApplyFormCreateForm
from .models import ApplyForm
class ApplyFormCreateView(CreateView):
form_class = ApplyFormCreateForm
template_name = 'form.html'
success_url = "/"
models.py
from django.db import models
from course.models import Semester
DEFAULT_SEMESTER_ID = 1
class ApplyForm(models.Model):
name = models.CharField(max_length=15)
school = models.CharField(max_length=20)
department = models.CharField(max_length=20)
email = models.EmailField(max_length=100)
is_beginner = models.BooleanField(default=False)
introduction = models.TextField(max_length=2000)
motivation = models.TextField(max_length=2000)
comments = models.TextField(max_length=2000, blank=True)
semester = models.ForeignKey(Semester, default=DEFAULT_SEMESTER_ID)
created_at = models.DateTimeField(auto_now_add=True)
update_at = models.DateTimeField(auto_now=True)
def __unicode__(self):
return self.school + self.department + self.name
def __str__(self):
return self.school + self.department + self.name
form.html
{% extends "base.html" %}
{% block content %}
<form method='POST'> {% csrf_token %}
{{form.as_p}}
<button type='submit'>Save</button>
</form>
{% endblock content %}
form.py
from django import forms
from .models import ApplyForm
class ApplyFormCreateForm(forms.ModelForm):
class Meta:
model = ApplyForm
fields = [
'name',
'school',
'department',
'email',
'is_beginner',
'introduction',
'motivation',
'comments',
]
url.py
from django.conf.urls import url
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from myweb.views import HomeView
from course.views import CourseListView
from applyform.views import ApplyFormCreateView
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^$', HomeView.as_view(), name='home'),
url(r'^course/$', CourseListView.as_view(), name='course'),
url(r'^apply/$', ApplyFormCreateView.as_view(), name='applyform'),
]
I am new to Django Rest Framework and am struggling to get my serialisations to work correctly for a foreignkey relationship between two models. I have tried to reduce my setup down to be as simple as possible but I still can't understand how it is supposed to work. I am trying to use HyperlinkedModelSerializer so (from the docs) 'that it uses hyperlinks to represent relationships'. When I try to visit the url for either the list or detail view for {model X} on the test server I get:
'Could not resolve URL for hyperlinked relationship using view name
"{model Y}-detail". You may have failed to include the related model
in your API, or incorrectly configured the lookup_field attribute on
this field.'
What am I doing wrong?
My models:
from django.db import models
class Project(models.Model):
name = models.CharField(max_length=50)
description = models.TextField()
class ProjectPhoto(models.Model):
project = models.ForeignKey(
Project, related_name='photos', on_delete=models.CASCADE
)
image = models.ImageField()
caption = models.CharField(max_length=100)
date_added = models.DateTimeField(auto_now_add=True)
My serializers
class ProjectSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Project
fields = ('name', 'description', 'photos')
class ProjectPhotoSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ProjectPhoto
fields = ('image', 'caption', 'date_added', 'project'))
My views:
from rest_framework import viewsets
from projects.models import Project, ProjectPhoto
from projects.serializers import ProjectSerializer, ProjectPhotoSerializer
class ProjectViewSet(viewsets.ModelViewSet):
queryset = Project.objects.all().order_by('name')
serializer_class = ProjectSerializer
class ProjectPhotoViewSet(viewsets.ModelViewSet):
queryset = ProjectPhoto.objects.all().order_by('date_added')
serializer_class = ProjectPhotoSerializer
EDIT:
My urls:
from django.conf.urls import url, include
from rest_framework import routers
from projects import views
router = routers.DefaultRouter()
router.register(r'^projects', views.ProjectViewSet)
router.register(r'^project-photos', views.ProjectPhotoViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
these are then added in my main app urls.py file. I don't think this is problem as if I change the serializer to ModelSerializer then everything works fine.
I think your problem is in your urls.py file, see the code and picture
rest/urls.py file
from django.conf.urls import url, include
from rest_framework import routers
from .views import ProjectViewSet, ProjectPhotoViewSet
router = routers.SimpleRouter()
router.register(r'project', ProjectViewSet)
router.register(r'project-photo', ProjectPhotoViewSet)
urlpatterns = [
url(r'^', include(router.urls)),
]
Principal urls.py file:
from django.conf.urls import url, include
from django.contrib import admin
from rest import urls as urls_rest
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^rest/', include(urls_rest)),
]
and other option, try to use this code in your serializers.py file:
from rest_framework import serializers
from .models import Project, ProjectPhoto
class ProjectPhotoSerializer(serializers.ModelSerializer):
class Meta:
model = ProjectPhoto
fields = ('image', 'caption', 'date_added', 'project')
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = ('name', 'description', 'photos')
depth = 2
You have 3 options to use serializers (see picture below)