How to set a default time in Django ModelForm - django

I created a Django ModelForm.
Here is the models.py file
class Room(models. Model):
available_from = models.TimeField()
available_till = models.TimeField()
Here is the forms.py file
class RoomForm(forms.ModelForm):
class TimeInput(forms.TimeInput):
input_type = 'time'
available_from = forms.TimeField(
widget=TimeInput(),
)
available_till = forms.TimeField(
widget=TimeInput(),
)
class Meta:
model = Room
fields = ['available_from','available_till']
I want to know how to set a default time to the form.

You can specify a default in the model if you want to do this for all forms/admins/… that are derived from this model:
from datetime import time
class Room(models. Model):
available_from = models.TimeField(default=time(2))
available_till = models.TimeField()
or if this is specific to this form, you can use the initial=… parameter [Django-doc]:
from datetime import time
class TimeInput(forms.TimeInput):
input_type = 'time'
class RoomForm(forms.ModelForm):
available_from = forms.TimeField(
widget=TimeInput(),
initial=time(2)
)
class Meta:
model = Room
fields = ['available_from','available_till']
widgets = {'available_till': TimeInput}

Related

Adding Foreign Key to Django Import Export

I am trying to import data from a csv using Django_Import Export. I saw other SO posts but they are not helping. Below are the models
Models.py
class TblSubject(amdl.AagamBaseModel):
subject_id = models.AutoField(primary_key=True)
subject_name = models.CharField(max_length=20)
standard = models.ForeignKey('TblStandard', models.DO_NOTHING)
remembrance_credit = models.IntegerField(default=40)
applied_knowledge_credit = models.IntegerField(default=30)
understanding_credit = models.IntegerField(default=30)
subject_credit = models.IntegerField(default=100)
class Meta:
db_table = 'tblsubject'
def __str__(self):
return f'{self.subject_name}'
class SubjectChapter(amdl.AagamBaseModel):
subject_chapter_id = models.AutoField(primary_key=True)
subject = models.ForeignKey('TblSubject', on_delete=models.CASCADE)
chapter_id = models.IntegerField()
chapter_name = models.CharField(max_length=150)
remembrance_credit = models.IntegerField()
applied_knowledge_credit = models.IntegerField()
understanding_credit = models.IntegerField()
chapter_credit = models.IntegerField()
class Meta:
db_table = 'subject_chapter'
def __str__(self):
return f'{self.chapter_id} {self.chapter_name} : {self.subject}'
Here is the admin.py
from django.contrib import admin
from import_export import resources, fields
from import_export.widgets import ForeignKeyWidget
from .models import SubjectChapter, TblSubject
from import_export.admin import ImportExportModelAdmin
class SubjectChapterResource(resources.ModelResource):
class Meta:
model = SubjectChapter
import_id_fields = ('subject_chapter_id',)
subject = fields.Field(
column_name='subject_name',
attribute='subject_name',
widget=ForeignKeyWidget(TblSubject, 'subject_id'))
class SubjectChapterAdmin(ImportExportModelAdmin):
resource_class = SubjectChapterResource
admin.site.register(SubjectChapter, SubjectChapterAdmin)
And i am getting this below error
I am inserting data for SUBJECTCHAPTER from csv where the SUBJECT column is a foreign key from TBLSUBJECT and it contains the name of the TBLSUBJECT.
Change this
class SubjectChapterResource(resources.ModelResource):
class Meta:
model = SubjectChapter
import_id_fields = ('subject_chapter_id',)
subject = fields.Field(
column_name='subject_name',
attribute='subject_name',
widget=ForeignKeyWidget(TblSubject, 'subject_name'))
From subject_id to subject_name

Django. How to create django_easyselect_form with custom fieldset?

There is my model:
class MoneyTransfer(models.Model):
sender = models.ForeignKey(BankAccount, related_name='outcome_transfers')
receiver = models.ForeignKey(BankAccount, related_name='income_transfers')
when = models.DateTimeField()
total = models.FloatField()
comment = models.CharField(max_length=255)
objects = TransferQuerySet.as_manager()
form:
SendTransferForm = select2_modelform(MoneyTransfer)
I have two usages of form:
1. fields = 'receiver', 'comment', 'total'
2. fields = 'sender', 'receiver', 'comment', 'total'
How to implement it in code?
You can create two forms class
class FirstForm(ModelForm):
class META:
model = models.MoneyTransfer
fields = ['receiver', 'comment', 'total']
and then:
class SecondForm(ModelForm):
class META:
model = models.MoneyTransfer
fields = ['sender', 'receiver', 'comment', 'total']
I've decided not to use model form and created simple form with necessary widgets:
class SendTransferForm(forms.Form):
sender = forms.ModelChoiceField(queryset=BankAccount.objects.all(), widget=Select2(), label="Счёт отправителя")
receiver = forms.ModelChoiceField(queryset=BankAccount.objects.all(), widget=Select2(), label="Счёт получателя")
total = forms.CharField(widget=forms.TextInput(attrs={'class': 'select2fake'}), label="Сумма")
comment = forms.CharField(widget=forms.TextInput(attrs={'class': 'select2fake'}), label="Комментарий")

eav-django models serialization with django rest framework

I'm using eav-django for a project and I need to serialize it's models with DjangoRestFramework, but I got some issues.
My models (models.py) are the standard models needed by eav-django:
class ServiceSchema(BaseSchema):
pass
class ServiceChoice(BaseSchema):
schema = models.ForeignKey(ServiceSchema, related_name='choices')
class ServiceAttr(BaseAttribute):
schema = models.ForeignKey(ServiceSchema, related_name='attrs')
choice = models.ForeignKey(ServiceChoice, related_name='attrs', null=True)
class ServiceEntity(BaseEntity):
title = models.CharField(max_length=100)
attrs = generic.GenericRelation(ServiceAttr, object_id_field='entity_id', content_type_field='entity_type')
#classmethod
def get_schemata_for_model(cls):
return ServiceSchema.objects.all()
def __unicode__(self):
return self.title
class ServiceFacetSet(BaseFacetSet):
def get_queryset(self, **kwargs):
return ServiceEntity.objects.filter(**kwargs)
class HostSchema(BaseSchema):
pass
class HostChoice(BaseChoice):
schema = models.ForeignKey(HostSchema, related_name='choices')
class HostAttr(BaseAttribute):
schema = models.ForeignKey(HostSchema, related_name='attrs')
choice = models.ForeignKey(HostChoice, related_name='attrs', null=True)
class HostEntity(BaseEntity):
title = models.CharField(max_length=100)
attrs = generic.GenericRelation(HostAttr, object_id_field='entity_id', content_type_field='entity_type')
services = models.ManyToManyField(ServiceEntity, null=True, blank=True, default=None, related_name='hosts')
#classmethod
def get_schemata_for_model(cls):
return HostSchema.objects.all()
def __unicode__(self):
return self.title
class HostFacetSet(BaseFacetSet):
def get_queryset(self, **kwargs):
return HostEntity.objects.filter(**kwargs)
And I'm trying to serialize them with this piece of code in serializers.py:
class ServiceSchemaSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = ServiceSchema
class ServiceChoiceSerializer(serializers.HyperlinkedModelSerializer):
schema = ServiceSchemaSerializer(many=False)
class Meta:
model = ServiceChoice
fields = ('schema', )
class ServiceAttrSerializer(serializers.HyperlinkedModelSerializer):
schema = ServiceSchemaSerializer(many=False)
choice = ServiceChoiceSerializer(many=False)
class Meta:
model = ServiceAttr
fields = ('schema', 'choice')
class ServiceEntitySerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = HostEntity
fields = ('title', 'attrs')
class HostSchemaSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = HostSchema
class HostChoiceSerializer(serializers.HyperlinkedModelSerializer):
schema = HostSchemaSerializer(many=False)
class Meta:
model = HostChoice
fields = ('schema', )
class HostAttrSerializer(serializers.HyperlinkedModelSerializer):
schema = HostSchemaSerializer(many=False)
choice = HostChoiceSerializer(many=False)
class Meta:
model = HostAttr
fields = ('schema', 'choice')
class HostEntitySerializer(serializers.HyperlinkedModelSerializer):
services = ServiceEntitySerializer(many=True)
class Meta:
model = HostEntity
fields = ('title', 'attrs', 'services')
Django rest framework error is [...] GenericRelatedObjectManager is not JSON serializable. Ok, got it. But there is some way to accomplish the serialization?

Serialize related objects in django rest framework

How can I serialize related objects in DRF. Am having three models auth_user (User), ModelA, ModelB.
My models:
class ModelA(models.Model):
user = models.OneToOneField(auth_user, related_name = 'modelA')
name = models.CharField(max_length = 30)
class ModelB(models.Model):
owner = models.OneToOneField(auth_user)
user = models.OneToOneField(auth_user, related_name = 'modelB')
type = models.ForeignKey(ModelD)
cost = models.IntegerField()
class ModelD(models.Model):
type_desc = models.CharField(max_length = 40)
My serialilzers:
class A(serializers.ModelSerializer):
class Meta:
model = ModelA
fields = ('name', )
class B(serializers.ModelSerializer):
class Meta:
model = ModelB
fields = ('type', 'cost', )
class AuthUserSerilaizer(serializers.ModelSerializer):
userA = serializers.RelatedField(source = 'modelA')
userB = serializers.RelatedField(source = 'modelB')
class Meta:
model = User
fields = ('email', 'password', 'userA', 'userB', )
write_only_fields = ('password',)
#transaction.commit_manually
def restore_object(self, attrs, instance = None):
try:
user = User.objects.create_user(email = attrs.get('email'), password = attrs.get('password'))
modela = ModelA(user =user, name = attrs.get('name'))
modela.save()
transaction.commit()
return User(email = attrs.get('email'))
except Exception ,e:
transaction.rollback()
print repr(e)
JSON I'm passing
data = {'email':'123#gmail.com,
'password' : 'dummy',
'userA' : {'name' :'123'},
'userB':{'type':1,'cost':'100'}
Whenever am making a POST request the 'attrs' gets only email and password not userA and userB, why? How can I deserialize and create data serially in the respective tables.
try this in your view
from django.core.serializers.json import DjangoJSONEncoder
import json
response = json.dumps(data,cls=DjangoJSONEncoder)
return HttpResponse(response, mimetype="application/json")
and in success function you can access using
usera_name = response.userA.name
userb_type = response.userB.type
userb_cost = response.userB.cost

Relation in Django REST Framework?

I am using serializers.GeoFeatureModelSerializer to serialize Model. I have a queryset
that is creating Left Outer Join. I want to serialize related Model fields
Here is my Model
class LookupTiming(models.Model):
day = models.CharField(max_length=7)
time_1 = models.TimeField()
time_2 = models.TimeField()
class Meta:
db_table = u'lookup_timing'
class Streets(models.Model):
name = models.CharField(max_length=50)
geometry = models.GeometryField(null=True, blank=True)
objects = models.GeoManager()
class Meta:
db_table = u'streets'
def __unicode__(self):
return '%s' % self.name
class StreetTimings(models.Model):
street= models.ForeignKey(Streets)
lookuptiming = models.ForeignKey(LookupTiming)
class Meta:
db_table = u'street_timings'
queryset =
Streets.objects.filter(streettimings_lookuptiming_isnull=True)
Serializer Class
class StreetSerializer(gis_serializer.GeoFeatureModelSerializer):
class Meta:
model = Streets
geo_field = "geometry"
id_field = False
fields = ('id', 'streettimings__lookuptiming__day', other fields)
Updated
I want to show following fields on response
Streets (id)
LookupTiming (day)
I want output like this query simple is that
SELECT "streets"."id", "lookuptiming"."day" FROM "streets"
LEFT OUTER JOIN "streettimings" ON ( "streets"."id" = "streettimings"."street_id" )
LEFT OUTER JOIN "lookuptiming" ON ( "streettimings"."lookuptiming_id" = "lookuptiming"."id" )
How can i do this?
Thank you