How can I get a textarea from model+ModelForm? - python

models.py=>
from django.db import models
from django.forms import ModelForm
from datetime import date
import datetime
from django import forms
from django.forms import Textarea
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
created = models.DateField(auto_now_add=True)
modified = models.DateField(auto_now_add=True)
def __unicode__(self):
return self.title
class PostModelForm(ModelForm):
class Meta:
model = Post
But I get a text input not textarea for models.TextField(). Is that a reason of css?

I think this section in the documentation should be useful to solve the problem.
from django.forms import ModelForm, Textarea
class PostModelForm(ModelForm):
class Meta:
model = Post
widgets = {
'content': Textarea(attrs={'cols': 80, 'rows': 20}),
}

Alternative to jcollardo's solution (same result, different syntax):
from django import forms
class PostModelForm(forms.ModelForm):
content = forms.CharField(widget=forms.Textarea)
class Meta:
model = Post

You are using models not forms, which means you can't use textarea properly. Instead you can try TextField:
field_name = models.TextField( **options)

Related

How to autofocus a Charfield in a Django ModelForm

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']

ValueError at /studentform/ ModelForm has no model class specified

I am getting an error while running the following form. please help me to fix the error.
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class student(models.Model):
name = models.CharField(max_length=50)
emailid = models.EmailField(max_length=60)
marks = models.CharField(max_length=11)
date = models.DateTimeField()
def __str__(self):
return self.name
forms.py
from django import forms
from .models import *
class student_form(forms.ModelForm):
name = forms.CharField(widget=forms.TextInput(), required=True, max_length=100)
emailid = forms.EmailField(widget=forms.EmailField(), required=True)
class Meta():
model = student
fields = ['name','emailiid']
I have tried many things but no solution. please look at in this code and help to sort this out. so confusing for me as i am new to Django.
In forms.py, you must indent the Meta class so it is part of the student_form class.
This gives:
from django import forms
from .models import *
class student_form(forms.ModelForm):
name = forms.CharField(widget=forms.TextInput(), required=True, max_length=100)
emailid = forms.EmailField(widget=forms.EmailField(), required=True)
class Meta:
model = student
fields = ['name','emailiid']

How to fix, limit_choices_to cannot be a ForeignKey in Django?

I've a snip of code like following:
models.py
class Notebook(models.Model):
owner = models.ForeignKey(User, on_delete = models.CASCADE)
name= models.CharField(max_length=50)
class Note(models.Model):
create_user = models.ForeignKey(User, on_delete = models.CASCADE)
text=models.CharField(max_length=500)
notebook=models.ForeignKey(Notebook, on_delete = models.CASCADE, limit_choices_to = {'owner' : create_user})
But I'm getting an error that limit_users_to cannot be a Foreign Key.
I want to users to select only notebooks they have created while writing a note, but now users can select other's notebook while limit_choices_to is not set.
And notebook must be ForeignKey.
What can i do?
You have to do that in the View when creating a Note
form.py
from .models import Note
from django.forms import ModelForm
class NoteForm(ModelForm):
class Meta:
model = Note
view.py
from django.views.generic.edit import CreateView
from .form import NoteForm
from .models import Note, Notebook
class NoteCreateView(CreateView):
model=Note
form_class=NoteForm
def get_form(self, form_class=None):
form = super(NoteCreateView, self).get_form(form_class)
# Thats the solution:
form.fields['notebook'].queryset = Notebook.objects.filter(owner=self.request.user)
return form

Django render is very slow

This is my training django project. I am using GeoIP, django-modeltranslation, i18n. Showing video gallery page is very slow. The database contains about 20 entries.
Model
from __future__ import unicode_literals
from django.db import models
from ckeditor_uploader.fields import RichTextUploadingField
from datetime import datetime
import urllib, json, re
from django.utils.translation import ugettext_lazy as _
class Video(models.Model):
class Meta:
abstract = True
title = models.CharField(max_length=80, unique=True)
text = RichTextUploadingField()
link = models.CharField(max_length=80)
slug = models.CharField(db_index=True,max_length=40,blank=True,null=True)
created_date = models.DateTimeField(auto_now_add=True)
pub_date = models.DateTimeField(default=datetime.now())
is_active = models.BooleanField(default=True)
position = models.IntegerField(default=0)
meta = models.TextField(blank=True,null=True)
def __unicode__(self):
return self.title
class VideoMessage(Video):
class Meta:
verbose_name = _('VideoMessage')
verbose_name_plural = _('VideoMessages')
Translation
from modeltranslation.translator import translator, TranslationOptions
from models import VideoMessage
class VideoMessageTranslationOptions(TranslationOptions):
fields = ('text', 'link', 'meta',)
translator.register(VideoMessage, VideoMessageTranslationOptions)
Views
from django.shortcuts import render
from django.views.generic import View
from models import VideoMessage
class Index(View):
def get(self, request):
params={}
messages=VideoMessage.objects.exclude(is_active=False).exclude(link='').order_by('-position')
params['videos']={}
params['videos']['message']=messages
return render(request, 'index.html', params)
gprof2dot tree. 100% = ~2000ms
I parsed the image at each rendering. It was bad idea.
Try to find out what takes the longest time.
You can use something like Opbeat where you can get a free account. You can see a breakdown on what takes time on different requests so you can focus on whatever is slow.
Also, is this happening only during development or also in production? Having DEBUG=True in a production setup is not only a bad idea but also it can have a big impact on performance.

Define CSS style in Django model field

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)

Categories