In my django app I want to set focus to the first CharField (task) when the page loads.
my models.py is
from django.db import models
class ListModel(models.Model):
task = models.CharField(max_length=255)
status = models.BooleanField(default=False)
def __str__(self):
return f"{self.task} : {str(self.status)}"
and forms.py is
from django.forms import ModelForm
from .models import ListModel
class ListForm(ModelForm):
class Meta:
model = ListModel
fields = ["task", "status"]
I have tried adding the following widget in my CharField (in models.py):
task = models.CharField(max_length=255, widget=models.TextInput(attrs={'autofocus': True})
but it gives an AttributeError: module 'django.db.models' has no attribute 'TextInput'
I have also tried adding the following to the ListForm class (in forms.py):
def __init__(self):
self.fields['task'].widget.attrs.update(autofocus = 'autofocus')
though I am not getting any error for this, but when I load my page the focus is not set to the task CharField either. What can I do add auto-focus to my CharField?
You are confusing model fields (which are used to store data in the database), and form fields, which are used to obtain, validate and clean data the user has entered.
You thus work with:
from django.forms import ModelForm
from django import forms
from .models import ListModel
class ListForm(ModelForm):
# forms ↓
task = forms.CharField(
max_length=255,
# forms ↓
widget=forms.TextInput(attrs={'autofocus': True})
)
class Meta:
model = ListModel
fields = ['task', 'status']
Related
I have created a new model for my app Consumptions but it doesn't show up.
I know that I have to put it on the admin.py page but still not working.
I don't know what could be happening
This is my models.py page:
from logs.mixins import LogsMixin
# Other models
class MF(LogsMixin, models.Model):
"""Definición del modelo de Proveedor."""
name = models.CharField("Nombre", null=False, default="MF", max_length=50)
class Meta:
verbose_name = 'Módulo formativo'
verbose_name_plural = 'Módulos formativos'
def __str__(self):
return self.name
# Other models
And this is my admin.py page:
from django.contrib import admin
from .models import Provider, Consumption, Message, Course, Call, Platform, MF
admin.site.register(Provider)
admin.site.register(Consumption)
admin.site.register(Message)
admin.site.register(Course)
admin.site.register(Call)
admin.site.register(Platform)
admin.site.register(MF)
As you can see is not my only model, I do the same with all of them but the MF one is not showing up on the admin page.
What am I doing wrong?
Try following approach:
class ProviderAdmin(admin.ModelAdmin):
model = Provider
admin.site.register(Provider, ProviderAdmin)
In ProviderAdmin class you may specify filters, search fields or empty value handling:
search_fields = ('',)
list_filter = ('',)
empty_value_display = 'empty'
This is my forms.py file!!!
from django import forms
from . models import URLModel
class URLForm(forms.ModelForm):
class Meta:
model = 'URLModel'
fields = ['url']
This is my models.py file
from django.db import models
# Create your models here.
class URLModel(models.Model):
url=models.URLField(unique=True)
short=models.CharField(max_length=200,unique=True)
def __str__(self):
return self.url
Now i just wanted to ask that why this error is coming and i have revieved and i cant observe any error for real...please help
# Remove single quote from your model specification in forms.py
from django import forms
from .models import URLModel
class URLForm(forms.ModelForm):
class Meta:
model = URLModel
fields = ('url',)
This is my first time using Django and I am completely stuck at how to use ModelForms in my project. I have been able to follow the online tutorials this far but without ModelForms(to add data into a Postgresql database), I can't proceed onward. I am trying to simply make a form page that lets the users add a few inputs (2 datefields and 1 textfield) and by submitting that form, the data will be added to the database.
The error I have been getting is:
AttributeError: 'Hyuga_Requests' object has no attribute 'name' [where Hyuga_Request is a class set in the models.py]
models.py
from __future__ import unicode_literals
from django.db import models
from django.forms import ModelForm
class Hyuga_Requests(models.Model):
name = models.CharField(max_length=50)
s_date = models.DateField(auto_now=True)
e_date = models.DateField(auto_now=True)
reason = models.TextField(max_length=500)
def __unicode__(self):
return self.name
views.py
from django.shortcuts import render
from django import forms
from .forms import Hyuga_RequestForm
def create_req(request):
form = Hyuga_RequestForm()
context = {"form":form,}
return render(request,"request_form/requestform.html", context)
forms.py
from django import forms
from .models import Hyuga_Requests
from django.forms import ModelForm
class Hyuga_RequestForm(forms.ModelForm):
class Meta:
model = Hyuga_Requests()
fields = ['name','s_date','e_date','reason']
Please help this noobie...
Don't instantiate the model in the class Meta inside the Hyuga_RequestForm class.
model = Hyuga_Requests() should be model = Hyuga_Requests
model = Hyuga_Requests() -> model = Hyuga_Requests
The error come because you are calling the model on the form.
from django import forms
from .models import Hyuga_Requests
from django.forms import ModelForm
class Hyuga_RequestForm(forms.ModelForm):
class Meta:
model = Hyuga_Requests
fields = ['name','s_date','e_date','reason']
Note: i suggest to you use on the any class you define on python not use "_", you can check more about PEP8 and code styles here: https://www.python.org/dev/peps/pep-0008/
So here is the code that I am working with right now
models.py
from django.db import models
class Building(models.Model):
name = models.TextField(max_length=60)
def __str__(self):
return self.name
class Charge(models.Model):
item = models.CharField(max_length=60)
cost = models.CharField(max_length=15)
last_updated = models.DateField(default='',auto_now=True)
buildings = models.ManyToManyField(Building)
def __str__(self):
return self.item
admin.py
from django.contrib import admin
from rlscharges.models import Charge, Building
from django.db import models
from django.forms import CheckboxSelectMultiple
class MyModelAdmin(admin.ModelAdmin):
formfield_overrides = {
models.ManyToManyField: {'widget': CheckboxSelectMultiple},
}
class BuildingInline(admin.TabularInline):
model = Charges.building.through
class BuildingAdmin(MyModelAdmin):
fields = ['name']
inlines = [BuildingInline]
admin.site.register(Charge, MyModelAdmin)
admin.site.register(Building, BuildingAdmin)
I basically just want the checkboxselectmultiple to show up on the Charge and Building models admin pages. Right now the checkbox only shows up on the Charge model and the TabularInline shows up on the Building model. Is there a way to get formfield_overrides to apply to the BuildingInline so it shows the checkboxes and not the TabularInline? Or do I need to do something to the relationship of the models? I apologize ahead of time if this is a stupid question, I am just getting started with django.
Suppose I have a following code:
File models.py:
from django.db import models
from django.contrib.auth.models import User
class MyClass(models.Model):
username = models.ForeignKey(User, blank=True, null=True)
my_field = models.CharField(max_length=200, default="sample_field")
File views.py
from django.forms.models import inlineformset_factory
from django.contrib.auth.models import User
from myapp.models import MyClass
#login_required
def index(request):
username = User.objects.get(username=request.user.username)
MyClassFormSet = inlineformset_factory(User, MyClass, can_delete=False, extra=5)
formset = MyClassFormSet(instance=username)
...
What is the easiest way to add CSS class to the field my_field here?
(I saw some answers on SO for forms, but not for models).
Create a form from the model and define UI attributes there, that is the correct place to do it e.g.
class MyForm(ModelForm):
class Meta:
model = MyClass
fields = ('my_field')
widgets = {
'my_field': TextInput(attrs={'class': 'mycssclass'}),
}
That should set correct class for your field, then in HTML file set the needed css attributes e.g.
.mycssclass {
color: red;
}
If you are using inlineformset_factory you can still pass a widgets dict to it, where widgets is a dictionary of model field names mapped to a widget, or you can pass a custom form to it, so you can do something like this
MyClassFormSet = inlineformset_factory(User, MyClass, form=MyForm, can_delete=False, extra=5)