Django ModelForm foreign key values are not displayed - django

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.

Related

How to create complex multi model join query set with Django ORM

I want to create a query set with multiple tables. I cannot find any resource that helps
Beside some small 2 table join examples, I cannot find any resource that is helpful for this, not in stackoverflow, the Django docs or even in the ORM Cookbook.
Below is firstly the SQL I want to recreate followed by the models classes, simplified for the purpose of this question. They have in fact a LOT more fields.
SELECT doc_uid,
docd_filename,
doct_name,
docd_media_url
FROM vugd_detail,
vug_virtual_user_group,
vugdoc_vug_docs,
doc_documents,
docd_detail,
doct_type
WHERE vugd_vug_uid = vug_uid
AND vugdoc_vug_uid = vug_uid
AND vugdoc_doc_uid = doc_uid
AND docd_doc_uid = doc_uid
AND doct_uid = doc_doct_uid
AND vugd_status = 1
AND docd_status = 1
AND NOW() BETWEEN vugd_start_date AND vugd_end_date
AND NOW() BETWEEN docd_start_date AND docd_end_date
AND vug_uid = {{Some ID}};
class VugVirtualUserGroup(models.Model):
objects = None
vug_uid = models.AutoField(primary_key=True)
vug_name = models.CharField(unique=True, max_length=30)
vug_short_code = models.CharField(max_length=6)
vug_created_on = models.DateTimeField()
vug_created_by = models.CharField(max_length=30)
class Meta:
managed = False
db_table = 'vug_virtual_user_group'
app_label = 'main'
class VugdDetail(models.Model):
objects = None
vugd_uid = models.AutoField(primary_key=True)
vugd_vug_uid = models.ForeignKey(VugVirtualUserGroup, models.DO_NOTHING, db_column='vugd_vug_uid')
vugd_long_name = models.CharField(max_length=50)
vugd_status = models.IntegerField()
vugd_start_date = models.DateTimeField()
vugd_end_date = models.DateTimeField()
class Meta:
managed = False
db_table = 'vugd_detail'
app_label = 'main'
class VugdocVugDocs(models.Model):
onjects = None
vugdoc_uid = models.AutoField(primary_key=True)
vugdoc_vug_uid = models.ForeignKey(VugVirtualUserGroup, models.DO_NOTHING, db_column='vugdoc_vug_uid')
vugdoc_doc_uid = models.ForeignKey(DocDocuments, models.DO_NOTHING, db_column='vugdoc_doc_uid')
class Meta:
managed = False
db_table = 'vugdoc_vug_docs'
app_label = 'main'
class DocdDetail(models.Model):
objects = None
docd_uid = models.AutoField(primary_key=True)
docd_doc_uid = models.ForeignKey(DocDocuments, models.DO_NOTHING, db_column='docd_doc_uid')
docd_filename = models.CharField(max_length=200)
docd_media_url = models.CharField(max_length=300)
docd_status = models.IntegerField()
docd_start_date = models.DateTimeField()
docd_end_date = models.DateTimeField()
class Meta:
managed = False
db_table = 'docd_detail'
app_label = 'main'
class DoctType(models.Model):
objects = None
doct_uid = models.AutoField(primary_key=True)
doct_vug_uid = models.ForeignKey('VugVirtualUserGroup', models.DO_NOTHING, db_column='doct_vug_uid')
doct_name = models.CharField(max_length=30)
doct_start_date = models.DateTimeField()
doct_end_date = models.DateTimeField()
class Meta:
managed = False
db_table = 'doct_type'
app_label = 'main'
class DocDocuments(models.Model):
object = None
doc_uid = models.AutoField(primary_key=True)
doc_doct_uid = models.ForeignKey('DoctType', models.DO_NOTHING, db_column='doc_doct_uid')
class Meta:
managed = False
db_table = 'doc_documents'
app_label = 'main'
As one can see the actual query is not so complicated.
The goal here is just to get the list of valid(active, not deleted) files avilable for a specific VUG(Simple user group), if the group has a valid status.
So if there is any Django ORM experts who can help with what is really a common SQL type that should be should be possible to be converted to a Django ORM script, your help will sincerely be appreciated.
The Django way to query multiple related tables is to chain them using dot notation.
A sudo code example might help point you in the right direction.
vug_virtual_user_group = VugVirtualUserGroup.objects.get(vug_uid="Some ID")
print(f'vug_virtual_user_group {vug_virtual_user_group}')
A lookup using the foreign key to get all related objects
vugdoc_vugdocs = vug_virtual_user_group.vugdocvugdocs_set.all()
print(f'vugdoc_vugdocs {vugdoc_vugdocs}')
This example assumes that the default modelmanger objects is not overridden by objects = None.

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 serialize nested model in Django-Rest

I have been trying to use with the a legacy database. I have created models file using inscpectdb but now I am not able to perform joins on the table.
I have two tables job_info and username_userid.
Here is my models.class file:
class UseridUsername(models.Model):
userid = models.IntegerField(blank=True, null=True)
username = models.CharField(max_length=100, blank=True, null=True)
class Meta:
managed = False
db_table = 'userid_username'
class LinuxJobTable(models.Model):
job_db_inx = models.AutoField(primary_key=True)
mod_time = models.IntegerField()
account = models.TextField(blank=True, null=True)
exit_code = models.IntegerField()
job_name = models.TextField()
id_job = models.IntegerField()
id_user = models.OneToOneField(UseridUsername , on_delete=models.CASCADE,db_column="id_user")
class Meta:
managed = False
db_table = 'linux_job_table'
Now how can I get all the values from LinuxJobTable and username from UseridUsername for the corresponding user.
Heren is my serializable class :
class UseridUsernameSerializer(serializers.ModelSerializer):
class Meta:
model = UseridUsername
fields = ('userid','username')
class UserSerializer(serializers.ModelSerializer):
class Meta:
username = UseridUsernameSerializer(many=False)
model = LinuxJobTable
fields = ('account','mod_time','username')
When I try to access it, it gives ' Field name username is not valid for model LinuxJobTable.' error.
The error is raising because UserSerializer search for a relates fields named username and it doesn't find a one. In your case the ralated field is named as id_user, So you have to mention it via source parameter.
So, Try this
class UserSerializer(serializers.ModelSerializer):
username = UseridUsernameSerializer(many=False, source='id_user')
class Meta:
model = LinuxJobTable
fields = ('account', 'mod_time', 'username')

select related in Django

I am trying to accomplish something very similar to:
How to join 3 tables in query with Django
Essentially, I have 3 tables. In the Django REST we are showing table 3. As you see below (models.py), table 3 has company_name which is a foreign key of table 2 and table 2 is a foreign key of table 1. Both table 2 and 3 are linked by the table 1 ID. Table 1 contains the actual text, which we want to display in the API output, not the ID number.
Table 1: Manufacturer of Car -- Table 2: What the Car is -- Table 3: list of all cars
Models.py
Table 1:
class ManufacturerName(models.Model):
name_id = models.AutoField(primary_key=True)
company_name = models.CharField(unique=True, max_length=50)
class Meta:
managed = False
db_table = 'manufacturer_name'
Table 2:
class CarBuild(models.Model):
car_id = models.AutoField(primary_key=True)
car_icon = models.CharField(max_length=150, blank=True, null=True)
company_name = models.ForeignKey('ManufacturerName', models.DO_NOTHING, db_column='ManufacturerName')
class Meta:
managed = False
db_table = 'car_build'
Table 3:
class CarList(models.Model):
list_id = models.AutoField(primary_key=True)
company_name = models.ForeignKey('CarBuild', models.DO_NOTHING, db_column='CarBuild')
title = models.CharField(unique=True, max_length=100)
description = models.TextField()
class Meta:
managed = False
db_table = 'cars'
Within my views:
This is what I am trying, based on the foreign key relationships:
queryset = CarList.objects.all().select_related('company_name__company_name')
I get no errors when I save and run this, however, the ID is still being returned, and not the text associated with the foreign key relationships:
[
{
"list_id": 1,
"company_name": "http://127.0.0.1:8000/api/1/",
"title": "Really fast car you're driving, and this is dummy text",
Again, I would like to achieve getting the text associated with the company_name foreign key relationships from table 1 to show in the JSON.
serializer and viewset
class manufacturer_name(serializers.HyperlinkedModelSerializer):
class Meta:
model = manufacturer_name
fields = ('name_id', 'company_name')
class manufacturer_name(viewsets.ModelViewSet):
queryset = manufacturer_namee.objects.all()
serializer_class = manufacturer_name
class CarBuildViewSet(viewsets.ModelViewSet):
queryset = CarBuild.objects.all()
serializer_class = CarBuildSerialiser
class CarBuildSerialiser(serializers.HyperlinkedModelSerializer):
class Meta:
model = CarBuild
fields = ('car_id', 'car_icon', 'company_name')
class CarListSerialiser(serializers.HyperlinkedModelSerializer):
class Meta:
model = News
fields = ('list_id', 'company_name', 'title')
class CarListViewSet(viewsets.ModelViewSet):
serializer_class = CarList
def get_queryset(self):
queryset = News.objects.all().select_related('company_name__company_name')
return queryset
Based on detailed conversation to clear few details. Here is the answer.
You need to make small changes to your models as it was quite confusing to understand what you want to achieve.
Models:
class ManufacturerName(models.Model):
name_id = models.AutoField(primary_key=True)
company_name = models.CharField(unique=True, max_length=50)
class Meta:
managed = False
db_table = 'manufacturer_name'
class CarBuild(models.Model):
car_id = models.AutoField(primary_key=True)
car_icon = models.CharField(max_length=150, blank=True, null=True)
manufacturer = models.ForeignKey(ManufacturerName,on_delete=models.SET_NULL)
class Meta:
managed = False
db_table = 'car_build'
class CarList(models.Model):
list_id = models.AutoField(primary_key=True)
car = models.ForeignKey(CarBuild, on_delete=models.DO_NOTHING)
title = models.CharField(unique=True, max_length=100)
description = models.TextField()
class Meta:
managed = False
db_table = 'cars'
And then You need to adjust your serializers.
class CarListSerialiser(serializers.HyperlinkedModelSerializer):
company_name= serializers.SerializerMethodField(read_only=True)
class Meta:
model = CarList
fields = ('list_id', 'company_name', 'title')
def get_company_name(self, obj):
return obj.car.manufacturer.company_name
And you use it in your view:
class CarListViewSet(viewsets.ModelViewSet):
queryset = CarList.object.all()
serializer_class = CarListSerialiser

DRF, update a single field in nested serializer

these are my models:
class ADS(models.Model):
advertiser = models.ForeignKey(User)
campaign = models.ForeignKey(Campaign, related_name="ads")
headline = models.CharField(max_length=50)
description_1 = models.TextField(blank=True)
description_2 = models.TextField(blank=True)
display_url = models.URLField(blank=True)
final_url = models.URLField(blank=True)
mobile_url = models.URLField(blank=True)
class Meta:
db_table = "ads"
and:
class AdsImages(models.Model):
ads = models.ForeignKey(ADS,blank=True, null=True)
image = models.ImageField(upload_to='images/',default='media/None/no-img.jpg')
class Meta:
db_table = "ads_images"
I have a nested serializer, as you can see the second model is a table with images, so I am uploading asynchronously the images via AngularJs. As you can see the ForeignKey(ADS, blank=True, null=True), so I am not filling it for the first time. My question is that how to update after that the ads field.
here are my serializers:
class AdsImagesSerializer(serializers.ModelSerializer):
image = serializers.ImageField(use_url=True,allow_empty_file=True)
class Meta:
model = AdsImages
fields = ('id','image','ads',)
class ADSerializer(serializers.ModelSerializer):
adsImages = AdsImagesSerializer(many=True)
class Meta:
model = ADS
fields = ('headline','description_1','description_2','display_url','final_url','mobile_url','advertiser','adsImages',)
Partial updates
By default, serializers must be passed values for all required fields or they will raise validation errors. You can use the partial argument in order to allow partial updates
# Update `comment` with partial data
serializer = CommentSerializer(comment, data={'content': u'foo bar'}, partial=True)