Add descriptive text to the right of field in Django admin - django

I have a DecimalField in my model that I'd like to show up in the admin interface with a unit to the right of the field, like so:
I think if I add help_text to the field, that will show up below the field. Is there a way to specify it to show up to the right?

You can handle it with help_text from the forms, overwrite your field in the form, such as the css.
from django.db import models
from django.contrib import admin
from django import forms
from your.models import Post
class PostForm(forms.ModelForm):
ethanol = forms.FloatField(
label='This is Ethanol',
max_value=10,
min_value=0,
widget=forms.NumberInput(
attrs={
'class': 'whatever',
'style': 'position:relative'
}
),
help_text='<span style="position:absolute;right:0">g/mL</span>'
)
class Meta:
model = Post
fields = '__all__'
class PostAdmin(admin.ModelAdmin):
form = PostForm
list_display = ['ethanol', 'id']
admin.site.register(Post, PostAdmin)

Related

How to remove arrows from Django integerField without maintaining the only number input feature?

forms.py
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
registration = forms.IntegerField(label='Registration Number')
class Meta:
model = User
fields = ['username', 'email','registration','password1', 'password2']
How can I remove the up and down arrows from the registration field?
P.S. I want to only allow the user to input numbers in this field.
This can be done in CSS:
Like so:
input::-webkit-outer-spin-button,
input::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
You should be able to make it specific to that field by using:
#id_registration::-webkit-outer-spin-button,
#id_registration::-webkit-inner-spin-button {
-webkit-appearance: none;
margin: 0;
You can do this by overriding widgets in Meta class.
Like this:
from django import forms
from django.contrib.auth.models import User
from django.contrib.auth.forms import UserCreationForm
from .models import Profile
# Import widget that you want
from django.forms import TextInput
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
registration = forms.IntegerField(label='Registration Number')
class Meta:
model = User
fields = ['username', 'email','registration','password1', 'password2']
widgets = {
'registration': TextInput()
}
Also I'm not sure but you can just try this:
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
# Add widget to your field
registration = forms.IntegerField(label='Registration Number', widget=forms.TextInput())
class Meta:
model = User
fields = ['username', 'email','registration','password1', 'password2']
For more info:
Overriding the default fields

How to add Widgets to UpdateView in Django

I need to add this widget to the django UpdateView,
class tlistUpdate(LoginRequiredMixin,UpdateView):
fields = ('title', 'thumbnail', 'content', 'tags')
model = htmlpage
template_name = 'blog/create_form.html'
Tried adding
widgets = {
'content': SummernoteWidget(),
}
and
content = forms.CharField(widget=SummernoteWidget())
But it did't work.
The UpdateView is not constructed to handle advanced form construction. The idea is that you use fields if you aim to construct a simple (standard) Form.
You can simply construct a ModelForm and use that form in your CreateView/UpdateView:
# app/forms.py
from django import forms
class HtmlPageForm(forms.ModelForm):
class Meta:
model = HtmlPage
fields = ('title', 'thumbnail', 'content', 'tags')
widgets = {
'content': SummernoteWidget
}
In your views.py you can then use the form by setting the form_class attribute [Django-doc]:
# app/views.py
from app.forms import HtmlPageForm
class TlistUpdate(LoginRequiredMixin,UpdateView):
model = htmlpage
form_class = HtmlPageForm
template_name = 'blog/create_form.html'
Note: normally a Django models, just like all classes in Python are given a name in PerlCase, not snake_case, so it should be: HtmlPage instead of htmlpage.

Django DateInput() widget not working in ModelForm

I'm making a user login form with a CustomUser model derived from AbstractUser, with one extra field: date_of_birth. I use CreateView to generate the form. All fields show up, the password field uses the password widget as expected (showing dots instead of characters), but the date field does not (plain character field with no formatting or calendar). What am I overlooking?
models.py:
from django.urls import reverse
from django.contrib.auth.models import AbstractUser
# Create your models here.
class CustomUser(AbstractUser):
date_of_birth = models.DateField(verbose_name="Date of Birth", blank=True, null=True)
def get_absolute_url(self):
return reverse('index')
def __str__(self):
return self.username
forms.py:
from .models import CustomUser
class CustomUserForm(forms.ModelForm):
class Meta:
model = CustomUser
fields = ["username", "password", "first_name", "last_name", "email", "date_of_birth"]
widgets = {
"password": forms.PasswordInput(),
"date_of_birth": forms.DateInput()
}
views.py:
from django.views.generic.edit import CreateView
from .models import CustomUser
from .forms import CustomUserForm
# Create your views here.
def index(request):
return HttpResponse("Hello, world")
class CustomUserCreate(CreateView):
model = CustomUser
form_class = CustomUserForm
If you come here in 2020 and beyond, just overide the default type=text undelying input by using 'type':'date'
So something like the below would work. Tested on Mozilla Dev Edition 73.+
'date_of_birth': forms.DateInput(attrs={'class':'form-control', 'type':'date'}),
Django has no built-in fancy datepicker. DateField uses the DateInput widget which is just a text input.
Thanks voodoo-burger for pointing me in the right direction. I found a video with a very simple solution to use the HTML5 datepicker: https://www.youtube.com/watch?v=I2-JYxnSiB0.
It only requires to add the following to forms.py:
class DateInput(forms.DateInput):
input_type = 'date'
and then use this as the widget (so replace forms.DateInput() with DateInput()).

Cannot define model in django

I am trying to build my first django app using the most common posts as a test. Unfortunately the server keeps returning errors such as Postmodel admin not defined. I have tried migrating the new changes but this doesnt work, as well as modifying the views, but it seems i need to explicitly define this model. Could someone point me in the right direction
Heres how my admin.py looks like
from django.contrib import admin
# Register your models here.
from .models import posts
import views
admin.autodiscover()
class PostsModelAdmin(admin.ModelAdmin):
list_display = ('title', 'updated', 'timestamp')
list_display_links = ('updated')
list_editable = ('title')
list_filter = ('updated', 'timestamp')
search_fields = ("title", 'content')
class Meta:
model = posts
admin.site.register(posts)
admin.site.register(PostModelAdmin)
Try this...
from .models import posts
from django.contrib import admin
class PostsModelAdmin(admin.ModelAdmin):
list_display = ('title', 'updated', 'timestamp')
list_display_links = ('updated')
list_editable = ('title')
list_filter = ('updated', 'timestamp')
search_fields = ("title", 'content')
class Meta:
model = posts
admin.site.register(posts, PostsModelAdmin)
The register method takes a model and a class. Your error is because you're just passing the class, which is never allowed unless it's passed after the model.
Also you had a typo in your code. You're missing an s when registering it at the bottom.

Django - Admin: list_display TextField

I'm trying to display the first 10 characters of a TextField on a list_display.
Is it possible in the admin interface ?
You can define a callable that returns the first 10 characters of the field, and add that to list_display.
More information see the Django docs for list_display.
myapp/admin.py
from django.contrib import admin
from django.utils.text import Truncator
from django.db import models
from .models import Product
def truncated_name(obj):
name = "%s" % obj.name
return Truncator(name).chars(70)
class ProductAdmin(admin.ModelAdmin):
list_display = ['id', truncated_name, 'category', 'timestamp',]
list_display_links = [truncated_name]
list_filter = ['category']
class Meta:
model = Product
You can also override the fields like so:
formfield_overrides = {
models.CharField: {'widget': TextInput(attrs={'size': '20'})},
models.TextField: {'widget': Textarea(attrs={'rows': 1, 'cols': 40, 'style': 'height: 1.5em;'})},
}