Author:- Tushar Sonu Lambole
This post includes the basics of Model creation in Django
1. AutoIncrement and primary field
class ProjectMaster(models.Model):
p_id = models.AutoField(primary_key=True)
2. Display text for model fields
class ProjectMaster(models.Model):
p_name = models.CharField(verbose_name='Project Name', max_length=150)
3. Ordering the data in admin view
class ProjectMaster(models.Model):
class Meta:
ordering = ('-p_date',)
4. Display model in admin site
class ProjectMasterAdmin(admin.ModelAdmin):
list_display = ('p_id','p_name','p_description','p_date')
admin.site.register(ProjectMaster, ProjectMasterAdmin)
5. Foreign Key
class ClientMaster(models.Model):
c_id = models.AutoField(primary_key=True)
p_fk = models.ForeignKey(ProjectMaster,verbose_name='Project')
6. ImageUploader with validation for ".png" extension and Dynamic ImagePath
class ClientMaster(models.Model):
c_name = models.CharField(max_length=150,verbose_name='Name')
def image_path(instance, filename):
return os.path.join('ImagesFiles', str(instance.c_name), str(instance.c_name)+'.png')
def validate_file_extension(value):
if not value.name.endswith('.png'):
raise ValidationError(u'Error: Only .Png files')
7. View uploaded images
A) in settings.py
MEDIA_ROOT = '/Users/tusharlambole/Documents/Development/Projects/DjangoProjects/PycharmProjects/TusharWebApp/'
MEDIA_URL = 'http://127.0.0.1:8000/'
B) in Url.py
urlpatterns = patterns('',
url(r'^(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)
This post includes the basics of Model creation in Django
1. AutoIncrement and primary field
class ProjectMaster(models.Model):
p_id = models.AutoField(primary_key=True)
2. Display text for model fields
class ProjectMaster(models.Model):
p_name = models.CharField(verbose_name='Project Name', max_length=150)
class ProjectMaster(models.Model):
class Meta:
ordering = ('-p_date',)
4. Display model in admin site
class ProjectMasterAdmin(admin.ModelAdmin):
list_display = ('p_id','p_name','p_description','p_date')
admin.site.register(ProjectMaster, ProjectMasterAdmin)
5. Foreign Key
class ClientMaster(models.Model):
c_id = models.AutoField(primary_key=True)
p_fk = models.ForeignKey(ProjectMaster,verbose_name='Project')
class ClientMaster(models.Model):
c_name = models.CharField(max_length=150,verbose_name='Name')
return os.path.join('ImagesFiles', str(instance.c_name), str(instance.c_name)+'.png')
def validate_file_extension(value):
if not value.name.endswith('.png'):
raise ValidationError(u'Error: Only .Png files')
c_logo = models.ImageField(upload_to=image_path, validators=[validate_file_extension],verbose_name='Logo Image')
A) in settings.py
MEDIA_ROOT = '/Users/tusharlambole/Documents/Development/Projects/DjangoProjects/PycharmProjects/TusharWebApp/'
MEDIA_URL = 'http://127.0.0.1:8000/'
B) in Url.py
urlpatterns = patterns('',
url(r'^(?P<path>.*)$', 'django.views.static.serve',
{'document_root': settings.MEDIA_ROOT}),
)