0

So as the title says, I am trying to shrink the widths of a couple of fields on my Django page. It is mainly CharField, DecimalField and IntegerField if that makes any difference.

Here is an example of one of the fields

title = models.CharField(max_length=200)

I have found others have used widgets but not able to get it work, both because I am uncertain how to use these, and maybe also because those examples all seemed to be using django.forms.CharField. Here is a link to such an example. I tried such an example like this:

title = models.CharField(max_length=200, widget=forms.Textarea(attrs={'cols': 10, 'rows': 20}))

but also:

title = models.CharField(max_length=200, widget=models.Textarea(attrs={'cols': 10, 'rows': 20}))

with import django.db.models and import django.forms

Here are my updated files:

models.py

class ChemRun(forms.Form):
    title           =       forms.CharField(max_length=50, widget=forms.TextInput(attrs={'style': 'width: 400px;' }))
    created_date    =       forms.DateTimeField(initial=timezone.now)
    status          =       forms.CharField(max_length=20, initial="In queue")

forms.py

class ChemRunForm(forms.Form):
    class Meta:
            model = ChemRun
            exclude = ('created_date', 'status')

views.py

@verified_email_required
def create(request):
    if request.POST:
            form = ChemRunForm()
            f = form.save(commit=False)
            f.owner = request.user
            f.save()
            data = form.cleaned_data
            initiate_run.delay(data)
            return HttpResponseRedirect('/accounts/profile')
    else:
            form = ChemRunForm()

    args = {}
    args.update(csrf(request))
    args['form'] = form

    return render_to_response('interface/newrun.html', args, context_instance=RequestContext(request))
Community
  • 1
  • 1
Frank
  • 619
  • 1
  • 6
  • 26
  • Does it really matter? it si going to be defined as "title" varchar(200) NOT NULL in the underlying SQL. Since it is a varchar, it is not going to affect much even if you shrink it. http://stackoverflow.com/questions/1962310/importance-of-varchar-length-in-mysql-table – Jose Cherian Sep 05 '15 at 21:34

1 Answers1

1

you can set it a few ways...

you can do it without having to define the widget and just set the html 'style' property on the element

Option 1

class MyForm(forms.ModelForm):
    def __init__(self, *args, **kwargs):
        super(MyFormForm, self).__init__(*args, **kwargs)
        self.fields['title'].widget.attrs['style'] = "width:200px"

Option 2

class MyForm(forms.ModelForm):
    class Meta:
        model = Foo
        'widgets' = {
            'title' = forms.CharField(attrs={'size':'80'}),
        }

Option 3

   class MyForm(forms.ModelForm):
        title = models.CharField(max_length=200, widget=forms.CharField(attrs={'size':'80'})
lukeaus
  • 11,465
  • 7
  • 50
  • 60
  • Thank you for the answer. This now uses forms.modelForm and forms.CharField, while I am using models.ModelForm and models.CharField. I haven't really understood the difference between models.ModelForms and forms.ModelForms, and I have been reluctant changing as it is likely to cause more problems. Is there a way to do this using models.ModelForm, or is it better I change to forms.ModelForm? – Frank Sep 06 '15 at 10:12
  • So forms can be either bound or unbound. You are trying to use bound forms cause you are using `models.CharField` - read a bit more about it here http://www.effectivedjango.com/forms.html . So you can think about it like this: `models.CharField` handles the data component whilst `forms.CharField` gives you the ability to handle unbound forms and also manipulate widgets, labels, help text etc..basically how the form renders. – lukeaus Sep 06 '15 at 21:18
  • Okay, I think I got the basics of it, thank you. Now I am getting new errors instead `TypeError: 'DeclarativeFieldsMetaclass' object is not iterable` – Frank Sep 07 '15 at 12:43
  • I also added examples from my models, forms and views files – Frank Sep 07 '15 at 12:49
  • first things first - `class ChemRun(forms.Form):` needs to inherit from models.Model - cause its a model! - same thing for your fields - you are describing the behaviour of your models in your models.py, so the fields also need to reference this `title = models.CharField(max_length=50)`. For `status = forms.CharField(max_length=20, initial="In queue")` this becomes `status = models.CharField(max_length=20)` - note that `initial` is a `forms.CharField` argument, not a `models.CharField` argument – lukeaus Sep 07 '15 at 18:06
  • next - in class ChemRunForm(forms.Form): - this should inherit from `forms.ModelForm` because you are using `class Meta: model = ChemRun` - so class ChemRunForm(forms.Form): becomes `class ChemRunForm(forms.ModelForm):` – lukeaus Sep 08 '15 at 03:45
  • next - you have to edit the form behaviour - consider using either my 'option 1' or 'option 2' as above - and don't forget to re-add the 'initial' - either in your view or in class ChemRunForm(forms.Form) (I should have mentioned in my first comment you can use initial in either of these 2 places) – lukeaus Sep 08 '15 at 03:45
  • Thanks, I have implemented the changes. Apparently I wasn't that well understood with how it works yet. I had forgotten to include the owner attribute, where I also save the active user that submits the form. Since ForeignKey doesn't exist for forms.Form, I try to supply that through the form instead to the ChemRun class. If I circumvene the need for the owner attribute, I still however have the problem that my form is never saved. In my updated files, is there a clear reason why it is not saved? – Frank Sep 08 '15 at 09:34
  • Tobias if my suggested answer solves the initial problem you had (i.e. the field width), then please accept my answer as solving that problem. Then I would recommend creating a new SO question with 'why does my form not save' - the reason is that you will need to post your view information and the forms as you currently have them, but to update your question with a working solution will make no sense, as anyone looking at your question will see a question with code that already works (cause you would have updated the forms code so it works!). Then link to your new question below. – lukeaus Sep 08 '15 at 10:05
  • That is a good point. I will do so and thank you very much for your help and your detailed answers. I will need to read up on models and forms more to prevent this. I have accepted your answer. Thank you again :) – Frank Sep 08 '15 at 10:37