Django: format DateField inherited by the model - django

I have a model with a DateField:
class Info(models.Model):
userprofile = models.OneToOneField(UserProfile, primary_key=True)
birth_date = models.DateField()
and i generate a form from it:
class SecondStepForm(ModelForm):
class Meta:
model = Info
exclude = ('userprofile',)
The problem is that i want to format the date input. I know it is possible with forms.DateField:
birth_date = forms.DateField(widget=forms.DateInput(format = '%d/%m/%Y'), input_formats=('%d/%m/%Y',))
but how to tell django that it should make a form from the model except for the date field where it should use forms.DateField?

You're there already. Just put that birth_date definition at the top level of the form, before the Meta class, and it will override the default field.

Related

How to use a serializer for different fields

I am working on a project of blog application in Django Rest Framework. But here I am facing some trouble. At first checkout my code then I will explain the question.
Here is the model.py
class Contact(models.Model):
id_no = models.AutoField(primary_key=True, unique=True)
email = models.EmailField()
name = models.CharField(max_length=1000)
subject = models.CharField(max_length=1000)
description = models.TextField()
And here is the serializer.py
class AddContactSerializer(serializers.ModelSerializer):
class Meta:
model = Contact
fields = '__all__'
Now in a view function I want to use only email and name field of the Contact model and in another view function I want to use name and description field of that model.
Can I use the same serializer class for different cases?
Please help me.
You can create multiple seralizers for a model. Example
class EmailContactSerializer(serializers.ModelSerializer):
class Meta:
model = Contact
fields = ['email','name'] # your desired fields here

How would I specify a data table that I have set up postgresql?

I am looking to set up the backend logic for a form where it shoots information to a data table that I set up in postgresql and was wondering, how I would specify the data table that I want to send the information to?
You can do this with a ModelForm. Assuming the 'data table' you mention is the database model class, you declare the Model you are sending information to in the Meta class, as shown here:
class Author(models.Model):
name = models.CharField(max_length=100)
title = models.CharField(max_length=3, choices=TITLE_CHOICES)
birth_date = models.DateField(blank=True, null=True)
def __str__(self):
return self.name
class Book(models.Model):
name = models.CharField(max_length=100)
authors = models.ManyToManyField(Author)
class AuthorForm(ModelForm):
class Meta:
model = Author
fields = ['name', 'title', 'birth_date']
class BookForm(ModelForm):
class Meta:
model = Book
fields = ['name', 'authors']
Notice where it says "model = Book" or "model = Author". This example is from the Django Documentation on ModelForms. You will need to instantiate your ModelForm class in your view.

Making form fields - read only or disabled in DJANGO updateView

I have a model which I will update using an updateView generic class based function. How can I make specific fields as read only ?
example :
Models.py:
class Employee(models.Model):
emp_no = models.IntegerField( primary_key=True)
birth_date = models.DateField()
first_name = models.CharField(max_length=14)
last_name = models.CharField(max_length=16)
gender = models.CharField(max_length=1)
hire_date = models.DateField()
class Meta:
verbose_name = ('employee')
verbose_name_plural = ('employees')
# db_table = 'employees'
def __str__(self):
return "{} {}".format(self.first_name, self.last_name)
views.py :
class EmployeeUpdate(UpdateView):
model = Employee
fields = '__all__'
How can I make the first_name readonly inside a UpdateView ?
Note: I want to have the model(charfield) the same, But it should be read only inide an UpdateView.
When one wants to customize their forms the easiest way is to make a form class. A generic view is not really meant to provide all features a form class does, even though it makes life a little easy by generating the form for you by itself.
You want to be using a ModelForm [Django docs] and set disabled=True [Django docs] on your field:
from django import forms
class EmployeeUpdateForm(forms.ModelForm):
first_name = forms.CharField(max_length=14, disabled=True)
class Meta:
model = Employee
fields = '__all__'
Note: The disabled boolean argument, when set to True, disables a form field using the disabled HTML attribute so that it won’t be
editable by users. Even if a user tampers with the field’s value
submitted to the server, it will be ignored in favor of the value from
the form’s initial data.
Now in your view you simply want to set the form_class attribute:
class EmployeeUpdate(UpdateView):
model = Employee
form_class = EmployeeUpdateForm

Can I add a checkbox in to Model Forms in Django even if there is no Field in DB for it

I have a model form and I need to add a checkbox to it. This checkbox is not mapped to any database field. Is this possible ? How !
You can specify which fields of model will be saved when form will be correct through fields variable of Meta class
So you can declare your checkbox and not include it in that property
#your model
class Author(models.Model):
name = models.CharField(max_length=100)
birth_date = models.DateField(blank=True, null=True)
#your model-form
class AuthorForm(ModelForm):
your_checkbox = forms.BooleanField(required = False,label = 'your_checkbox', ...)
class Meta:
model = Author
fields = ['name', 'birth_date'] #your checkbox is missing, so it's model independent
Define a Custom ModelForm by specifying model in Meta and declare the required additional field there. After that set form attribute of your Admin class with the name of YourForm.

Django REST-framework Serializer pk field?

What is the pk field in the Serializer class in Django-REST-framework?
I assume that it is the primary key, but is the name 'pk' a reserved term?
How does the Serializer class know that is to be the primary key of the Snippet model?
I see no field in the Snippet model named 'pk'.
class SnippetSerializer(serializers.Serializer):
pk = serializers.Field() # Note: `Field` is an untyped read-only field.
title = serializers.CharField(required=False,
max_length=100)
code = serializers.CharField(widget=widgets.Textarea,
max_length=100000)
linenos = serializers.BooleanField(required=False)
language = serializers.ChoiceField(choices=LANGUAGE_CHOICES,
default='python')
style = serializers.ChoiceField(choices=STYLE_CHOICES,
default='friendly')
....class SnippetSeralizer continues
class Snippet(models.Model):
created = models.DateTimeField(auto_now_add=True)
title = models.CharField(max_length=100, blank=True, default='')
code = models.TextField()
linenos = models.BooleanField(default=False)
language = models.CharField(choices=LANGUAGE_CHOICES,
default='python',
max_length=100)
style = models.CharField(choices=STYLE_CHOICES,
default='friendly',
max_length=100)
class Meta:
ordering = ('created',)
pk is a property that lives on the base Model class in django.db.models:
class Model(object):
...
pk = property(_get_pk_val, _set_pk_val)
...
which is used to identify the primary key for the model. I haven't used Django-REST, but they probably just map that to the field on the model.
And if you are using generic views in Django REST Framework, and you would like to use a different name for the pk field — say id, you can set lookup_field in your view to id.