I am trying to create a ModelForm for my Model Class "Asset" in Django 3
from django.db import models
from django.contrib.auth.models import User
from django.forms import ModelForm
class Manufacturer(models.Model):
name = models.CharField(max_length=100)
class Asset(models.Model):
serial = models.CharField(max_length=200)
manufacturer = models.ManyToManyField(Manufacturer)
author = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
name = models.CharField(max_length=200)
I managed to create a Form via the following code
from django import forms
from .models import Manufacturer
class AssetForm(forms.Form):
serial = forms.CharField(max_length=150)
manufacturer = forms.ModelChoiceField(queryset=Manufacturer.objects.all().values('name'))
name = forms.CharField(max_length=200)
description = forms.TextInput()
status = forms.CharField(max_length=200)
category = forms.CharField(max_length=200)
The querySet results in a dropdown being filled out with either "{'name':'Apple'}" or "('Apple',)" depending on using values or values_list respectively. How can I just display the name itself?
Adding the following method to the model fixes the problem:
def __str__(self):
return self.name
This will return the name and only the name to the queryset.
Related
I am trying to create nested relationship from more than two models in Django Rest Framework.
Thank you in advance for helping me.
I succeed with two models but when I'm trying with three models unable to create nested serialization.
from django.db import models
class Project(models.Model):
project_id = models.AutoField(primary_key=True)
project_name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Site(models.Model):
site_id = models.AutoField(primary_key=True)
site_name = models.CharField(max_length=255)
project_id= models.ForeignKey(Project, related_name="projectid", on_delete=models.CASCADE)
def __str__(self):
return self.site_name
class Aggin(models.Model):
assign_id = models.AutoField(primary_key=True)
site_id = Models.ForeginKey(Site, relate_name="siteid", on_delete=models.CASCADE)
from rest_framework import serializers
from .models import Song, Artist
class ProjectSerializer(serializers.ModelSerializer):
class Meta:
model = Project
fields = ('__all__')
class SiteSerializer(serializers.ModelSerializer):
class Meta:
model = Site
fields = ('__all__')
class AggignSerializer(serializers.ModelSerializer)
class Meta:
model = Aggin
fields = ('__all__')
I think you don't need to primary id field if you wanna use the Django's default foreign key setting. And related_name should be defined from the view of the counterpart model.
from django.db import models
class Project(models.Model):
project_name = models.CharField(max_length=255)
def __str__(self):
return self.name
class Site(models.Model):
site_name = models.CharField(max_length=255)
project = models.ForeignKey(Project, related_name="sites", on_delete=models.CASCADE)
def __str__(self):
return self.site_name
class Aggin(models.Model):
site = Models.ForeginKey(Site, relate_name="assigns", on_delete=models.CASCADE)
And then, in serializer, you can set like the following.
from rest_framework import serializers
from .models import Song, Artist
class ProjectSerializer(serializers.ModelSerializer):
sites = SiteSerializer(read_only = True, many = True)
class Meta:
model = Project
fields = ('id', 'project_name', 'sites')
class SiteSerializer(serializers.ModelSerializer):
assigns = AggignSerializer(read_only = True, many = True)
class Meta:
model = Site
fields = ('id', 'site_name', 'assigns')
class AggignSerializer(serializers.ModelSerializer):
class Meta:
model = Aggin
fields = ('id')
I'm trying to add a data using "Array Model Field"(djongo) as shown Djongo Documentation(Array Model Field) or
from djongo import models
class Blog(models.Model):
name = models.CharField(max_length=100)
tagline = models.TextField()
class Meta:
abstract = True
class MetaData(models.Model):
pub_date = models.DateField()
mod_date = models.DateField()
n_pingbacks = models.IntegerField()
rating = models.IntegerField()
class Meta:
abstract = True
class Author(models.Model):
name = models.CharField(max_length=200)
email = models.EmailField()
class Meta:
abstract = True
def __str__(self):
return self.name
class Entry(models.Model):
blog = models.EmbeddedModelField(
model_container=Blog,
)
meta_data = models.EmbeddedModelField(
model_container=MetaData,
)
headline = models.CharField(max_length=255)
body_text = models.TextField()
authors = models.ArrayModelField(
model_container=Author,
)
n_comments = models.IntegerField()
def __str__(self):
return self.headline
Into admin.py I added for registration of model in admin panel
from django.contrib import admin
from .models import Entry
admin.site.register(Entry)
And when I try to add a data via http://localhost:8000/admin/ I have a MigrationError...
Where is my mistake? And what am I not understanding?
You should use models.ObjectIdField() on all models to avoid calling django migrations.
Example:
class Author(models.Model):
_id = models.ObjectIdField()
name = models.CharField(max_length=200)
email = models.EmailField()
class Meta:
abstract = True
def __str__(self):
return self.name
See more in Djongo Docs
I'm a stupid. Sry. I didn't 'makemigration' after update a model.
And so here's what I did to make it work:
1. After update a model I did 'python manage.py makemigrations' and that power on.
I am still not satisfied with django foreignkey relationship.
below are two classess .
from django.db import models
from django.utils.text import slugify
from django_countries.fields import CountryField
from django.conf import settings
# Create your models here.
class PhotoGallery(models.Model):
title = models.CharField(max_length=255,unique=True)
picture_choices =
models.CharField(max_length=255,choices=PICTURE_CHOICES,default=NTR)
description = models.TextField(default='')
user = models.ForeignKey(settings.AUTH_USER_MODEL,
on_delete=models.CASCADE,related_name='image_uploader')
date_posted = models.DateTimeField(auto_now=True)
views = models.PositiveIntegerField()
likes = models.PositiveIntegerField()
country = CountryField(blank_label='(select country)')
slug = models.SlugField(allow_unicode=True,unique=True)
def __str__(self):
return self.title
from django.contrib import admin
from gallery.models import PhotoGallery
class PhotoGalleryAdmin(admin.ModelAdmin):
prepopulated_fields = {'slug': ('title',)}
And below is class Imagesmodel that has a foreignkey .Calling the PhotoGallery class from class Imagesmodel is not a problem .MY big problem is doing the reverse
class ImagesModel(models.Model):
gala_obj =
models.ForeignKey(PhotoGallery,
related_name='picture_gallery',on_delete=models.CASCADE)
post_image = models.ImageField(upload_to='gallery_pics',
verbose_name='Image')
def __str__(self):
return self.gala_obj.title
and below is my views.py file
`def detailViewPage(request,slug):
#here i wanted to get one image with the given slug
from `ImagesModel`
a = get_object_or_404(PhotoGallery, slug=slug)
selected_pic = a.picture_gallery.all()
#here i wanted to get all images excluding one
with the given slug
object_2 = ImagesModel.objects.exclude(id=selected_pic.id)
.order_by('-id')[:15]
return render(request,'gallery/photogallery_detail.html',{
'selected_pic':selected_pic,
'object_2':object_2,
})`
below is the error i get
The question is not very clear, but I assume you want to get all pictures associated with an object A. In your B model, give your foreignkey a related name:
class B(models.Model):
a = models.ForeignKey(A,related_name='post_title', related_name='pictures')
image = models.ImageField(upload_to='gallery_pics',
verbose_name='Image')
In your views.py:
a = get_object_or_404(A, slug=slug)
b = a.pictures.all()
I don't know why you named your foreignkey 'title', but the above code will get all the pictures associated with the object A.
The following will work also:
a = get_object_or_404(A, slug=slug)
pictures = a.b_set.all()
If you want to get the slug from an object B, then you can do the following:
b = get_object_or_404(B, id=1)
slug = b.a.slug
I have just started learning Django Rest Framework and trying to make a simple API using Django rest Framework.
This is my models.py
from __future__ import unicode_literals
from django.db import models
class Student(models.Model):
created = models.DateTimeField(auto_now_add=True)
name = models.CharField(max_length=150, blank=False)
student_id = models.CharField(max_length=20, primary_key=True)
father_name = models.CharField(max_length=150)
mother_name = models.CharField(max_length=150)
class Meta:
ordering = ('student_id',)
class Subject(models.Model):
created = models.DateTimeField(auto_now_add=True)
subject_id = models.CharField(max_length=20, primary_key=True)
name = models.CharField(max_length=150)
class Meta:
ordering = ('subject_id',)
class Result(models.Model):
created = models.DateTimeField(auto_now_add=True)
grade = models.DecimalField(max_digits=5, decimal_places=3, blank=False)
student_id = models.ForeignKey(Student, on_delete=models.CASCADE)
subject_id = models.ForeignKey(Subject, on_delete=models.CASCADE)
class Meta:
ordering = ('created',)
And this is my serializers.py
from rest_framework import serializers
from models import *
class StudentSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Student
fields = ('student_id', 'name', 'father_name', 'mother_name')
class SubjectSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Subject
fields = ('subject_id', 'name')
class ResultSerializer(serializers.HyperlinkedModelSerializer):
class Meta:
model = Result
fields = ('grade', 'student_id', 'subject_id')
In my "Result" model, I have two foreign keys; student_id and subject_id. This is how it looks like:
My questions is, how can I show the "name" field in the drop down menu in stead of showing "Student Object" and "Subject Object"?
I have tried with
STUDENT_CHOICES = [(each.student_id, each.name) for each in Student.objects.all()]
SUBJECT_CHOICES = [(each.subject_id, each.name) for each in Subject.objects.all()]
in the model's "choices=" field but it didn't work out.
Thanks in advance.
I think you're looking for this part of the DRF documentation.
Basically, your Django model's own representation is used. So for example, in your Student model you can add __str__ method:
# this is for Python 3, use __unicode__ on Python 2
def __str__(self):
return self.name
Meta options documentation for Django is here, look for model methods.
I created a single web page that works for a data entry operator which enter the data to database. I used modelForm to take the data. When I use it django raise an error that "ModelForm has no model class specified". What should I do?
model.py
class Person(models.Model):
NIC = models.CharField(unique=True,max_length=12)
FName = models.CharField(max_length=30)
LName = models.CharField(max_length=30)
FullName = models.CharField(max_length=100)
DOB = models.DateField()
Nationality = models.CharField(max_length=20)
AddressLine1 = models.CharField(max_length=100)
AddressLine2 = models.CharField(max_length=100)
AddressLine3 = models.CharField(max_length=100)
AddressLine4 = models.CharField(max_length=100, null=True,blank=True)
ContactNum = models.CharField(max_length=12)
Email = models.EmailField()
FacebookProf = models.CharField(max_length=100,null=True,blank=True)
LinkedInProf = models.CharField(max_length=100,null=True,blank=True)
PImage = models.ImageField(upload_to= Person_directory_path,null=True)
Objective = models.TextField()
CVPDF = models.ImageField(upload_to=Person_directory_path)
SpecialNotes = models.TextField(blank=True,null=True)
Department = models.ManyToManyField("Department")
Post = models.ManyToManyField("Post")
Degree = models.ManyToManyField("Degree",through="Person_Degree",null=True)
Interview = models.ManyToManyField("Interview",through='Person_Interview',null=True)
def __str__(self):
return self.NIC, self.FName, self.LName, self.FullName, self.Email
forms.py
from django.forms import ModelForm
from django import forms
from .models import Person
class Interview_Form(forms.ModelForm):
class meta:
model = Person
fields = ['NIC', 'FName', 'LName','FullName','Email']
views.py
from .forms import *
def deo(request):
deoForm = Interview_Form()
context = {
'deoForm':deoForm,
}
return render(request, 'deo.html', context)
To me it looks like you're importing ModelForm from django.forms, but when you create Interview_form you are using forms.ModelForm.
You should just be using ModelForm.