i tried to make search field to search by author in the admin panel but i got an error
Related Field got invalid lookup: icontains
i follow the documentation and other stackoverflow question but it doesn't work
#model.py
from django.contrib.auth import get_user_model
User = get_user_model()
class Author(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
def __str__(self):
return str(self.user)
# Create your models here.
class Post(models.Model):
title = models.CharField(max_length=256)
content = models.TextField(verbose_name='content')
date_published = models.DateTimeField(auto_now_add=True)
date_edited = models.DateTimeField(auto_now=True)
author = models.ForeignKey(Author, on_delete=models.CASCADE)
thumbnail = models.ImageField(blank=True)
def __str__(self):
return self.title
#admin.py
from django.contrib import admin
from .models import Post, Author,
class PostAdmin(admin.ModelAdmin):
list_display = ['title',
'date_published',
'date_edited',
'author', ]
search_fields = ['title',
'author__user',]
admin.site.register(Post, PostAdmin)
admin.site.register(Author)
it works when i changed the search_field[1] to author__id, but since it only accept id, it can't get the username. any idea how to solve it? should i make custom user model?
Related
I have 2 many to many fields in models and i want to connect them to each other i mean if i connect user in Admin Model with Counter Party i cant see that in Counter Party admin
How can i do that?
When im trying to do that it shows only in 1 model
models.py
class CustomUser(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, verbose_name='Пользователь')
user_counter = models.ManyToManyField('CounterParty', blank=True, verbose_name='Контрагенты пользователя')
def __str__(self):
return f'{self.user}'
class CounterParty(models.Model):
GUID = models.UUIDField(default=uuid.uuid4, editable=True, unique=True)
name = models.CharField(max_length=150, verbose_name='Наименование')
customer = models.BooleanField(default=False, verbose_name='Заказчик')
contractor = models.BooleanField(default=False, verbose_name='Подрядчик')
counter_user = models.ManyToManyField(User, blank=True, related_name='counter_user',
verbose_name='Пользователи контрагента')
class Meta:
verbose_name = 'Контрагент'
verbose_name_plural = 'Контрагенты'
def __str__(self):
return
admin.py
from django.contrib import admin
from .models import CustomUser, CounterParty, ObjectList, SectionList
from authentication.models import User
from authentication.admin import UserAdmin
class CustomUserInLine(admin.StackedInline):
model = CustomUser
can_delete = False
verbose_name_plural = 'Пользователи'
class CustomUserAdmin(UserAdmin):
inlines = (CustomUserInLine,)
#admin.register(CounterParty)
class CounterPartyAdmin(admin.ModelAdmin):
pass
admin.site.unregister(User)
admin.site.register(User, CustomUserAdmin)
user admin
counter party admin
You would not want to have these kinds of references with ManyToMany. Ideally you would have a one sided reference.
You can do an inline in your admin like this:
class CustomUserInLine(admin.StackedInline):
model = "CustomUser.user_counter.through"
Here are the docs for inline M2M in the admin: Django docs
models.py
from django.db import models
from django.contrib.auth.models import User
STATUS = (
(0,"Draft"),
(1,"Publish")
)
class BlogModel(models.Model):
id = models.AutoField(primary_key=True)
blog_title = models.CharField(max_length=200)
blog = models.TextField()
status = models.IntegerField(choices=STATUS, default=0)
created_at = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now=True)
class Meta:
ordering = ['-created_at']
def __str__(self):
return f"Blog: {self.blog_title}"
class CommentModel(models.Model):
your_name = models.CharField(max_length=20)
comment_text = models.TextField()
created_at = models.DateTimeField(auto_now_add=True)
blog = models.ForeignKey('BlogModel', on_delete=models.CASCADE)
class Meta:
ordering = ['-created_at']
def __str__(self):
return f"Comment by Name: {self.your_name}"
admin.py
from django.contrib import admin
from blog.models import BlogModel,CommentModel
class PostAdmin(admin.ModelAdmin):
list_display = ('blog_title', 'status','created_at','updated_at')
list_filter = ('status',)
search_fields = ('blog_title', 'content',)
admin.site.register(BlogModel, PostAdmin)
admin.site.register(CommentModel)
I created a simple blog post website with comments and I want to create reports and on the admin panel I have to see how to achieve this.
Like how many posts are created and how many have comments and how many post are draft and published
I checked this module but I don't understand how to implement it https://pypi.org/project/django-reports-admin/
You already have most of this, by using PostAdmin. The list_display already shows you how many posts are published/draft, and the change list has filters for that as well.
To show the comment count, simply add that to list_display:
class PostAdmin(admin.ModelAdmin):
list_display = ('blog_title', 'status', 'comment_count', 'created_at', 'updated_at')
def comment_count(self, obj):
return obj.commentmodel_set.count()
comment_count.short_description = 'Comment count'
This thus defines a custom method on the PostAdmin, that displays the comment count as a column, and gives it a user-friendly name as column header.
You can expand this with more statistics if you like. The Django admin is highly customizable.
Note: model names should be in CamelCase, so BlogModel and CommentModel should be Blog and Comment respectively.
I've created Comment section. The main goal is that only registered users can post comments and only from their usernames.
For now, I have a problem from who (username) the post is posting. On screenshot, you can see, that I can choose to post comment from user:JOHUA, but I'm currently logged in from user:JOHN
I need to set permission for user to post comment only from his username (maybe I should remove username variable in models.py, forms.py and admin.py and to set it by default like user:username, or maybe you know how to remove other usernames from Username column, so register user can only choose his username.
I have been puzzling over this problem for a long time, so definitely need community help!
HERE IS SOME CODE:
models.py
class Comment(models.Model):
post = models.ForeignKey(Post, on_delete=models.CASCADE, related_name='comments')
username = models.ForeignKey(User, on_delete=models.CASCADE)
email = models.EmailField()
body = models.TextField()
created_on = models.DateTimeField(auto_now_add=True)
active = models.BooleanField(default=False)
class Meta:
ordering = ['created_on']
def __str__(self):
return 'Comment {} by {}'.format(self.body, self.username)
forms.py
from .models import Comment
from django import forms
class CommentForm(forms.ModelForm):
class Meta:
model = Comment
fields = ['username', 'email', 'body']
admin.py
from django.contrib import admin
from .models import Post, Category, Comment
class CategoryAdmin(admin.ModelAdmin):
pass
#admin.register(Comment)
class CommentAdmin(admin.ModelAdmin):
list_display = ('username', 'body', 'post', 'created_on', 'active')
list_filter = ('active', 'created_on')
search_fields = ('username', 'email', 'body')
actions = ['approve_comments']
def approve_comments(self, request, queryset):
queryset.update(active=True)
admin.site.register(Post)
admin.site.register(Category, CategoryAdmin)
I am trying to set up a basic blog with a custom auth model. I am trying to get a simple form to work but somehow I am not able to make it work. I am not sure what is causing the error. This is a fresh app and a fresh project I am working on.
I tried to reference from the docs but I am not sure what I am doing incorrect. How can i fix this error? Thanks in advance
Docs: https://docs.djangoproject.com/en/1.11/topics/auth/customizing/#changing-to-a-custom-user-model-mid-project
Similar questions: Cannot create form field for 'created_by' yet, because its related model 'users.User' has not been loaded yet
My Current Code
models.py
class User(AbstractUser):
pass
class Post(models.Model):
author = models.ForeignKey('settings.AUTH_USER_MODEL')
title = models.CharField(max_length=200)
text = models.TextField()
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
forms.py:
from blog.models import User
class PostForm(forms.ModelForm):
image = forms.CharField(
widget=forms.FileInput(attrs={'class': 'form-control'}),required=False)
class Meta():
model = Post
fields = ('author','title', 'text','image')
widgets = {
'title': forms.TextInput(attrs={'class': 'textinputclass'}),
}
views.py
from blog.forms import PostForm, CommentForm
class CreatePostView(LoginRequiredMixin,CreateView):
...
form_class = PostForm
model = Post
def form_valid(self,form):
if self.request.POST:
post = form.save()
return HttpResponseRedirect('/')
settings.py:
AUTH_USER_MODEL = 'blog.User'
admin.py:
from .models import User
from django.contrib.auth.admin import UserAdmin
admin.site.register(User,UserAdmin)
You should use settings.AUTH_USER_MODEL, not the string 'settings.AUTH_USER_MODEL':
class Post(models.Model):
author = models.ForeignKey(settings.AUTH_USER_MODEL)
I'm getting an error:
AlreadyRegistered at / The model Post is already registered
Why is this happening, and how do I fix it? Here's my models.py :
from django.db import models from
django.contrib import admin
class Post(models.Model):
title = models.CharField(max_length=60)
body = models.TextField()
created = models.DateTimeField(auto_now_add = True)
def __unicode__(self):
return self.title
class PostAdmin(admin.ModelAdmin):
search_fields = ["title"]
admin.site.register(Post,PostAdmin)
This generally happens when you register you models in models.py file which might be imported into some other modules. The recommended way is to create a separate admin.py file for registering your models.
models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=60)
body = models.TextField()
created = models.DateTimeField(auto_now_add = True)
def __unicode__(self):
return self.title
admin.py
from django.contrib import admin
class PostAdmin(admin.ModelAdmin):
search_fields = ["title"]
admin.site.register(Post,PostAdmin)