After import the Tinymce, the entry of the models.post in the admin's site not show up(red draw). When i restart the page, it's show in a momment then off completely
Here is screenshot
main.admin.py
from django.contrib import admin
from .models import Author, Category, Post
admin.site.register(Author)
admin.site.register(Category)
admin.site.register(Post)
main.models.py
from django.db import models
from tinymce.models import HTMLField
from django.contrib.auth import get_user_model
from django.urls import reverse
User = get_user_model()
class Author(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
profile_picture = models.ImageField()
def __str__(self):
return self.user.username
class Category(models.Model):
title = models.CharField(max_length=40)
def __str__(self):
return self.title
class Post(models.Model):
title = models.CharField(max_length=100)
overview = models.TextField()
detail = models.TextField()
timestamp = models.DateTimeField(auto_now_add=True)
content = HTMLField(default='')
comment_count = models.IntegerField(default=0)
view_count = models.IntegerField(default=0)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
thumbnail = models.ImageField()
categories = models.ManyToManyField(Category)
featured = models.BooleanField()
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail', kwargs={
'id': self.id
})
The problem is due to the installation of TinyMCE through pip install django-tinymce. Try installing as:
pip install django-tinymce4-lite
then,
from tinymce import HTMLField (instead of 'tinymce.models import HTMLField')
class Post(models.Model):
...
content = HTMLField('Content')
Related
I am trying to create an announcement website (All) that can be visible to others (the Users, for which I added an Account). For this I wanted to modify a little the user profile to add fields like telephone, email address...
So I modified admin.py:
from django.contrib import admin
from .models import Todo, Account
from django.contrib.auth.models import User
class AccountInline(admin.StackedInline):
model = Account
can_delete = False
verbose_name_plural = 'Accounts'
class TodoAdmin(admin.ModelAdmin):
readonly_fields = ('created',)
inlines = (AccountInline, )
admin.site.unregister(User)
admin.site.register(Todo, TodoAdmin)
But got back:
<class 'todo.admin.AccountInline'>: (admin.E202) 'todo.Account' has no ForeignKey to 'todo.Todo'.
So I added a ForeignKey to Todo with account = models.ForeignKey(Account, on_delete=models.CASCADE):
from django.db import models
from django.contrib.auth.models import User
class Account(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
email = models.CharField(max_length=100)
firstname = models.CharField(max_length=30)
lastname = models.CharField(max_length=50)
company = models.CharField(max_length=5)
def __str__(self):
return self.user.username
class Todo(models.Model):
title = models.CharField(max_length=100)
datetime = models.DateTimeField()
memo = models.TextField(blank=True)
created = models.DateTimeField(auto_now_add=True)
datecompleted = models.DateTimeField(null=True, blank=True)
important = models.BooleanField(default=False)
user = models.ForeignKey(User, on_delete=models.CASCADE)
account = models.ForeignKey(Account, on_delete=models.CASCADE)
def __str__(self):
return self.title
But I still have the error, and I don't have any Users in the admin panel anymore
You accidentally wrote unregister for Users in your admin.py file. It should be admin.site.register(User)
You misinterpretted the error: the error states that you don't have a foreign key in your Account model to Todo.
This means your inline admin code isn't correct as it's expecting the other way around.
I have made a feature in Django where every user can change his platform's logo. The image selected by the user will be saved in static/{user.customer.public_id}/platformLogo/image.jpg. When i save the changes, i can see the uploaded image's path which also contain unique public ID which i don't want user to see for security purpose. Can anyone help me to hide this image path in Django for user? Attaching my code part here below.
Here we can see the image path which has unique ID in path, which we need to hide
Here is the uploaded image path directory
Here is my models.py
from sre_constants import CATEGORY
from unicodedata import category
from attr import fields
from django.db import models
from datetime import date
from django.contrib.auth.models import User
import uuid
def upload_path(instance, filename):
filename = str(date.today())
name = instance.user.customer.public_id.hex
return f'{name}/platformLogo/{filename}.jpg'
class Customer(models.Model):
user = models.OneToOneField(User, null=True, blank =True, on_delete=models.CASCADE)
public_id = models.UUIDField(primary_key=True, default = uuid.uuid4, editable=False)
date_created = models.DateTimeField(auto_now_add=True, null=True)
name = models.CharField(max_length=200, null=True)
otp_code = models.CharField(max_length=6, null=True)
first_name = models.CharField(max_length=200, null=True)
last_name = models.CharField(max_length=200, null=True)
email = models.CharField(max_length=200, unique=True)
phone = models.CharField(max_length=200, null=True)
profile_pic= models.ImageField(upload_to=upload_path, default='logo.png', null=True, blank=False,)
def __str__(self):
return self.name
Here is my views.py
#login_required(login_url='login')
def accountSetting(request):
customer = request.user.customer
form = CustomerForm(instance= customer)
if request.method == 'POST':
form = CustomerForm(data=request.POST, files=request.FILES, instance=customer)
if form.is_valid():
form.save()
context = {'form': form}
if request.user.is_anonymous:
return redirect("/")
return render(request, 'account-settings.html', context)
Here is my forms.py
from django.forms import ModelForm
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
from .models import Customer
from django import forms
class CustomerForm(ModelForm):
class Meta:
model = Customer
fields = '__all__'
exclude = ['user', 'email','name','otp_code']
class CreateUserForm(UserCreationForm):
class Meta:
model = User
fields = ['username','first_name','last_name', 'email', 'password1', 'password2']
Here is settings.py
STATIC_URL = '/static/'
STATICFILES_DIRS = [os.path.join(BASE_DIR, 'static')]
MEDIA_URL = '/platformLogo/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'static/platformLogo')
Since you already made public_id UUID, why not hash the logo and image name?
In Django environments I’ve used xsendfile with Apache or nginx. You end up placing the images in a folder that is accessible by Apache and served by apache, but can only be served after a request to the Django backend. It prevents all of the logos being visible to prying eyes.
I am currently working on a little django app, the app is like a social media app.
User can post, like and comment.
I recently created the User Profiles. Which I can now see the user for that user profile in my view, but I cant seem to dig into the Posts that may be related to the UserProfile.
what I am trying to do is in my view of HTML, I want to be able to get the post from the userprofile and the comment, and likes.
But I have tried everything and nothing works.
Currently in my HTML view I have rendered {{ profile.user }} and it displays the users name, but If I try profile.user.post or profile.user.comments I get nothing.
Here is some code to show where I am at.
Any help would be much appreciated.
Profile View.
def profile(request):
profile = get_object_or_404(UserProfile, user=request.user)
template = 'profiles/profile.html'
context = {
'profile': profile,
# 'posts': posts
}
return render(request, template, context)
Profile Model
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class UserProfile(models.Model):
"""
A user profile model to link posts and likes
"""
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="profile")
def __str__(self):
return self.user.username
Post Model
from django.db import models
from django.contrib.auth.models import User
from cloudinary.models import CloudinaryField
from profiles.models import UserProfile
class Post(models.Model):
user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, blank=True, related_name='user_posts')
title = models.CharField(max_length=220, unique=True)
location = models.CharField(max_length=220)
rating = models.DecimalField(
max_digits=6, decimal_places=2)
#slug = models.SlugField(max_length=220, unique=True)
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="activity_post")
updated_on = models.DateTimeField(auto_now=True)
description = models.TextField()
featured_image = CloudinaryField('image', blank=False)
created_on = models.DateTimeField(auto_now_add=True)
likes = models.ManyToManyField(User, related_name='activity_likes', blank=True)
like_count = models.BigIntegerField(default='0')
class Meta:
ordering = ['-created_on']
def __str__(self):
return self.title
def number_of_likes(self):
return self.likes.count()
def liked_by_user(self):
return self.likes.values_list('id', flat=True)
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
name = models.CharField(max_length=80)
email = models.EmailField()
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['created_on']
def __str__(self):
return f"Comment {self.body} by {self.name}"
enter code here
My Signal to create / save the profile, also have it registered in apps.py
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
from .models import UserProfile
#receiver(post_save, sender=User)
def create_profile(sender, instance, created, **kwargs):
if created:
UserProfile.objects.create(user=instance)
#receiver(post_save, sender=User)
def save_profile(sender, instance, **kwargs):
instance.profile.save()
I'm working on a simple blog project and have been following Corey Schafer on YouTube. In the tutorials, he creates new blog posts with integers (e.g. /blog/1, /blog/2, and so on), but I would like to create my post path with strings (like blog/my-blog-post, /blog/new-blog-post). I'm pretty new to python and django and I've tried some things with little luck. Any tips on how to do this?
Models:
class BloggPost(models.Model):
tittel = models.CharField(max_length=100)
innhold = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='blogg_foto')
def __str__(self):
return self.tittel
def get_absolute_url(self):
return reverse('post-detail', kwargs={'pk': self.pk})
Urls:
from django.urls import path
from .views import BloggPostListViewHome, BloggPostListView, BloggPostDetailView
from . import views
path('blogg/<int:pk>/', BloggPostDetailView.as_view(), name='bloggpost-detail'),
You can define a slug field, for example with an AutoSlugField from the django-autoslug package [readthedocs].
You can install that in the virtual environment with:
pip install django-autoslug
then you can add an AutoSlugField to your model with:
from autoslug import AutoSlugField
class BloggPost(models.Model):
tittel = models.CharField(max_length=100)
slug = AutoSlugField(populate_from='tittel')
innhold = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
image = models.ImageField(default='default.jpg', upload_to='blogg_foto')
def __str__(self):
return self.tittel
def get_absolute_url(self):
return reverse('post-detail', kwargs={'slug': self.slug})
In your urls.py you then define a pattern with:
path('blogg/<slug:slug>/', BloggPostDetailView.as_view(), name='bloggpost-detail'),
Class-based views with a SingleObjectMixin, such as a DetailView and an UpdateView, will perform filtering automatically on a slug if a slug field exists in the URL patterns.
I made one project called mysite and I created using startapp called books.I made the admin site and it worked successfully. But when I tried to add models to my admin site the error occurred mentioning these things.
ImportError at /admin/
No module named books.models
Actually I created admin.py in books folder and then I wrote the following code.
from django.contrib import admin
from mysite.books.models import Publisher, Author, Book
admin.site.register(Publisher)
admin.site.register(Author)
admin.site.register(Book)
models.py:
from django.db import models
class Publisher(models.Model):
name = models.CharField(max_length=30)
address = models.CharField(max_length=50)
city = models.CharField(max_length=60)
state_province = models.CharField(max_length=30)
country = models.CharField(max_length=50)
website = models.URLField()
def __unicode__(self):
return self.name
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
class Book(models.Model):
title = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
publisher = models.ForeignKey(Publisher)
publication_date = models.DateField()
def __unicode__(self):
return self.title
So, how to solve this problem?
try this instead..
from django.contrib import admin
from models import Publisher, Author, Book
admin.site.register(Publisher)
admin.site.register(Author)
admin.site.register(Book)
I'd try
from books.models import Publisher, Author, Book
...
if books is the name of your app