how to add legend in django form - django

I am trying to add legend to the form field in my django project. But facing some issues unable to add the legend. Any kind of help will be appreciated.
Form.py
class MyForm3(ModelForm):
class Meta:
model = import
fields = ['date_of_request',
'Number_of_units',
'Date_of_shipment',
'Required_doc',-------------- This should be the legend
'doc1',
'doc2',
]
models.py
class import(models.Model):
date_of_request = models.DateField()
Number_of_units = models.IntegerField()
Date_of_shipment = models.IntegerField()
Required_doc = models.CharField(max_length=200)---------- This should be the legend
doc1 = models.BooleanField()
doc2 = models.BooleanField()

Related

Django ModelForm foreign key values are not displayed

Am new to Django, and I am trying to create a form using model form. The form has a foreign key value (connection_type below in forms.py) and it's not displaying the values it is referring to.
For the image below, the columns,
Connection name: displayed
Connection type: text box has not appeared
Endpoint: displayed
Image from the browser
forms.py
class ConnectionForm(forms.ModelForm):
connection_type = forms.ModelChoiceField(queryset=ConnectionTypes.objects.all(), to_field_name='connection_type_id')
class Meta:
model = ConnectionDetails
exclude = ['connection_id','last_update_date']
Models.py
class ConnectionDetails(models.Model):
connection_id = models.IntegerField(primary_key=True,default=re_sequence('connection_seq'))
connection_name = models.CharField(max_length=200)
connection_type = models.IntegerField()
endpoint = models.CharField(max_length=100)
port = models.IntegerField()
login_id = models.CharField(max_length=100)
login_password = fields.CharPGPPublicKeyField(max_length=100)
connection_string_1 = fields.CharPGPPublicKeyField(max_length=100)
connection_string_2 = fields.CharPGPPublicKeyField(max_length=100)
connection_string_3 = fields.CharPGPPublicKeyField(max_length=100)
aws_region = models.CharField(max_length=20)
owner_id = models.IntegerField()
last_update_date = models.DateTimeField(default=dbcurr_ts)
working_schema = models.CharField(max_length=100)
service = models.CharField(max_length=100)
def generate_enc(mystrenc):
return 'pass'
class Meta:
managed = False
db_table = 'connection_details'
verbose_name = 'connection_details'
verbose_name_plural = 'connection_details'
class ConnectionTypes(models.Model):
connection_type_id = models.IntegerField(primary_key=True,default=re_sequence('connection_type_seq'))
connection_type_name = models.CharField(max_length=100)
connection_type_desc = models.CharField(max_length=300)
connection_type_category = models.CharField(max_length=100)
last_update_date = models.DateTimeField(default=dbcurr_ts)
class Meta:
managed = False
db_table ='connection_types'
verbose_name = 'connection_types'
verbose_name_plural = 'connection_types'
Can you please let me know what is mistake am making?
One issue is that the model field for connecton_types takes an IntegerField. Yet, you are giving it a ModelChoiceField in the form. I think if you set connection_type as models.ForeignKey(ConnectionType, on_delete=models.CASCADE) or something similar in your models.py, it should work better. This way the ConnectionType is directly linked to whatever ConnectionDetails you have.

how to add category to blog project django

i developed a blog project by watching many open-source courses and create my own django custom admin dashboard where i want to add a category option to my blog project, i have watched some tutorial on as well but couldn't find them helpful
models.py
from django.db import models
from django.forms import ModelForm
from farmingwave.models import BaseHeader,Submenu
class Category(models.Model):
mainmenu=models.ForeignKey(BaseHeader,null=True,on_delete=models.SET_NULL)
submenu=models.ForeignKey(Submenu,on_delete=models.CASCADE)
class AdSideMenu(models.Model):
title_id = models.AutoField(primary_key=True)
title_name = models.TextField()
url = models.TextField()
priority = models.IntegerField()
submenu_status = models.TextField()
class Meta:
db_table = 'admin_side'
class CreateBlog(models.Model):
id = models.AutoField(primary_key=True)
blog_Title = models.TextField(max_length=100)
content = models.TextField(max_length=5000)
category = models.ForeignKey(Category,null=True,on_delete=models.SET_NULL)
class Meta:
db_table = 'create_blog'
they are inhereting data from another app
models.py
`class BaseHeader(models.Model):
main_id = models.AutoField(primary_key=True)
title_name = models.TextField()
url = models.TextField()
priority = models.IntegerField()
submenu_status = models.TextField("false")
class Meta:
db_table = 'base_header'
class Submenu(models.Model):
sub_id = models.AutoField(primary_key=True)
main_id = models.IntegerField()
sub_name = models.TextField()
url = models.TextField()
priority = models.IntegerField()
mainmenu=models.ForeignKey(BaseHeader,on_delete=models.CASCADE)
class meta:
db_table = 'base_subheader'`
and the view function:
def create_blog(request):
if request.method =='POST':
form = CreateBlogForm(request.POST)
if form.is_valid():
form.save()
form = CreateBlogForm()
else:
form = CreateBlogForm()
base = BaseHeader.objects.all()
sub = Submenu.objects.all()
create = CreateBlog.objects.all()
category = Category.objects.all()
context = {
'form' : form,
'createblog' : create,
'category' : category,
'menu' : base,
'sub_menu' : sub,
Why not make the category a select item?
CATEGORY_CHOICES = (
('sports', 'sports'),
('tech', 'tech'),
('politics', 'politics')
)
category = models.CharField(max_length=100, choices=CATEGORY_CHOICES, blank=False)
You'd be able to access it like any other field now, so let's say the user clicked on "Politics articles" you can add a .filter(category="politics") and access it in the templates through {{ article.category }}
I don't know why there are all of these lines in your code, nor do I know the scale of your project, but that's how I would go about doing it.

How to include rows of data in a single django model entry?

I am working on multiple django sites and have been limited in making my project look nice for clients.
For example in the same app I have two models images and image galleries. It would be so much nicer to just have an admin entry for galleries and in that a table of images.
That's exactly what InlineModelAdmin is for. Taken a models.py like this:
class Gallery(models.Model):
name = models.CharField(max_length=100)
class Image(models.Model):
image = models.ImageField()
gallery = models.ForeignKey(Gallery)
You create an admin.py like this and only register an admin class for the Gallery:
class ImageInline(admin.TabularInline):
model = Image
class GalleryAdmin(admin.ModelAdmin):
inlines = [ImageInline]
admin.site.register(Gallery, GalleryAdmin)
This is my solution thanks to Dirk's help.
from django.db import models
PHOTO_PATH = 'media_gallery'
class Gallerys(models.Model):
title = models.CharField(max_length=30, help_text='Title of the image maximum 30 characters.')
slug = models.SlugField(unique_for_date='date', help_text='This is automatic, used in the URL.')
date = models.DateTimeField()
class Meta:
verbose_name_plural = "Image Galleries"
ordering = ('-date',)
def __unicode__(self):
return self.title
class Images(models.Model):
title = models.CharField(max_length=30, help_text='Title of the image maximum 30 characters.')
content = models.FileField(upload_to=PHOTO_PATH,blank=False, help_text='Ensure the image size is small and it\'s aspect ratio is 16:9.')
gallery = models.ForeignKey(Gallerys)
date = models.DateTimeField()
class Meta:
verbose_name_plural = "Images"
ordering = ('-date',)
def __unicode__(self):
return self.title
import models
from django.contrib import admin
class ImageInline(admin.TabularInline):
model = Images
class GallerysAdmin(admin.ModelAdmin):
list_display = ('title', 'date', 'slug')
inlines = [ImageInline]
admin.site.register(models.Gallerys,GallerysAdmin)

django: how does manytomanyfield with through appear in admin?

As stated in the title how does manytomanyfield with through appear in the admin site?
class SchoolClass(models.Model):
id = models.AutoField(primary_key = True)
class_name = models.TextField()
level = models.IntegerField()
taught_by = models.ManyToManyField(User,related_name="teacher_teaching",through='TeachSubject')
attended_by = models.ManyToManyField(User,related_name='student_attending')
def __unicode__(self):
return self.class_name
class Meta:
db_table = 'classes'
class TeachSubject(models.Model):
teacher = models.ForeignKey(User)
class_id = models.ForeignKey(SchoolClass)
subject = models.ForeignKey(Subject)
In the admin site, for the model SchoolClass, I have a field for attending students, but not the teachers.
You should use InlineModelAdmin. Docs.
class TeachSubjectInline(admin.TabularInline):
model = TeachSubject
extra = 2 # how many rows to show
class SchoolClassAdmin(admin.ModelAdmin):
inlines = (TeachSubjectInline,)
admin.site.register(SchoolClass, SchoolClassAdmin)

Integrating Photologue

I want to integrate photologue with my Django app and use it to display photos in a vehicle inventory...kinda like what is offered by Boost Motor Group Inc. I've already integrated the app so the next step which I'm trying to figure out is how to hook it up into my vehicle model and also how to display the photos. My vehicle model looks like this BTW
class Vehicle(models.Model):
stock_number = models.CharField(max_length=6, blank=False)
vin = models.CharField(max_length=17, blank=False)
common_vehicle = models.ForeignKey(CommonVehicle)
exterior_colour = models.ForeignKey(ExteriorColour)
interior_colour = models.ForeignKey(InteriorColour)
interior_type = models.ForeignKey(InteriorType)
odometer_unit = models.ForeignKey(OdometerUnit)
status = models.ForeignKey(Status)
odometer_reading = models.PositiveIntegerField()
selling_price = models.PositiveIntegerField()
purchase_date = models.DateField()
sales_description = models.CharField(max_length=60, blank=False)
feature_sets = models.ManyToManyField(FeatureSet, blank=True)
features = models.ManyToManyField(Feature, blank=True)
def __unicode__(self):
return self.stock_number
For your purposes I would recommend you check out django-imagekit (I wrote both imagekit and photologue). It was designed to be integrated into other applications as opposed to being a stand-alone application itself. After that, as Dominic said, we'll need to know more about your requirements.
I use ImageKit (great!)
model.py
from imagekit.models import ImageModel
class Photo(ImageModel):
name = models.CharField(max_length=100)
original_image = models.ImageField(upload_to='photos')
num_views = models.PositiveIntegerField(editable=False, default=0)
content_type = models.ForeignKey(ContentType)
object_id = models.PositiveIntegerField()
content_object = generic.GenericForeignKey('content_type', 'object_id')
class IKOptions:
# This inner class is where we define the ImageKit options for the model
spec_module = 'cms.specs'
cache_dir = 'photos'
image_field = 'original_image'
save_count_as = 'num_views'
class Vehicle(models.Model):
images = generic.GenericRelation('Photo', blank = True, null = True)
specs.py
from imagekit.specs import ImageSpec
from imagekit import processors
from imagekit.lib import *
# first we define our thumbnail resize processor
class ResizeThumb(processors.Resize):
width = 100
height = 75
crop = True
# now lets create an adjustment processor to enhance the image at small sizes
class EnchanceThumb(processors.Adjustment):
contrast = 1.2
sharpness = 1.1
# now we can define our thumbnail spec
class Thumbnail(ImageSpec):
processors = [ResizeThumb, EnchanceThumb]
in your template you will access this thumbnails like this:
{% for p in vehicle.images.all %}
{{ p.get_thumbnail.url }}
{% endfor %}
admin.py could look like this:
class ImagesInline(generic.GenericTabularInline):
model = Photo
max_num =4
class VehicleAdmin(admin.ModelAdmin):
inlines = [ImagesInline]
All about ImageKit
add the file specs.py to your app and tell ImageKit of it like this
class IKOptions:
# This inner class is where we define the ImageKit options for the model
spec_module = 'cms.specs # ur_app.specs
add a field to your Photo-Model to save what kind of view/ content it shows. i.e. ChoiceField
In view/template you can filter for it