ModelForm has no model class specified when use model forms - python

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.

Related

Django Forms created from Model with overfull Queryset Output

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.

How to make Django select box option not selectable?

I have made a Django Form using Django Crispy Forms. I used the Foreign Key concept to display dropdowns in my page. I would like the first option of the dropdown ('Choose..') to be shown to the user but he/she must not be able to select it.
It is very easy to do with JavaScript but I'm not sure how to do it with Django.
My page with the dropdowns
I am also attaching the code for my forms.py and models.py.
models.py
from django.db import models
from django import forms
class Organization(models.Model):
orgname = models.CharField(max_length = 100, blank=True)
def __str__(self):
return str(self.orgname)
class Team(models.Model):
teamID = models.AutoField(primary_key=True)
teamName = models.CharField(max_length = 100, blank=True)
org = models.ForeignKey(Organization, on_delete=models.CASCADE)
def __str__(self):
return str(self.teamName)
class AgileTeam(models.Model):
agileTeamID = models.AutoField(primary_key=True)
agileTeamName = models.CharField(max_length = 100, blank=True)
org = models.ForeignKey(Organization, on_delete=models.CASCADE)
team = models.ForeignKey(Team, on_delete=models.CASCADE)
def __str__(self):
return str(self.agileTeamName)
class Employee(models.Model):
name = models.CharField(max_length=100)
assoc_id = models.CharField(max_length=10)
username = models.CharField(max_length=50, blank=True)
password = models.CharField(max_length=50, blank=True)
organization = models.ForeignKey(Organization, on_delete=models.CASCADE)
team = models.ForeignKey(Team, on_delete=models.CASCADE)
agile_team = models.ForeignKey(AgileTeam, on_delete=models.CASCADE)
forms.py
from django import forms
from django.forms import ModelForm
from .models import Organization, Team, AgileTeam, Employee
class EmployeeForm(forms.ModelForm):
password = forms.CharField(widget=forms.PasswordInput(render_value = True))
class Meta:
model = Employee
fields = ('name', 'assoc_id', 'username', 'password', 'organization', 'team', 'agile_team',)
labels = {
'name':'Name',
'assoc_id':'Associate ID',
'username': 'Username',
'password': 'Password',
'organization':'Organization Name',
'team': 'Team Name',
'agile_team': 'Agile Team'
}
def __init__(self, *args, **kwargs):
super(EmployeeForm,self).__init__(*args, **kwargs)
# Code to make fields optional and to set the first option of dropdown as "Choose.."
self.fields['organization'].required = False
self.fields['organization'].empty_label = "Choose.."
self.fields['team'].required = False
self.fields['team'].empty_label = "Choose.."
self.fields['agile_team'].required = False
self.fields['agile_team'].empty_label = "Choose.."
This is my first question on StackOverflow. I hope I have been able to explain my problem properly.
Thanks in advance!
May the force be with you.

error NOT NULL constraint failed: customize form django-all-auth with 3 models (foreign key)

I'm learning django and in one of my challenges I want to add 3 foreign keys to the sign up form django-all-auth, but I have the error: NOT NULL constraint failed: advertising_profile.user_id
please can you help me and explain what Im failing.
I am trying to save this information for the registration form
==========views.py==================
def register(request):
form = CustomSignUpProfileModelForm()
if request.method == "POST":
form = CustomSignUpProfileModelForm(data=request.POST)
if form.is_valid():
#user = form['customSignUp'].save(commit=False)
profile = form.save(commit=False)
profile.user = request.user
profile.save()
#user = form.save()
if profile is not None:
do_login(request, user)
return redirect('welcome')
#form.fields['username'].help_text = None
#form.fields['password1'].help_text = None
#form.fields['password2'].help_text = None
return render(request,"account/signup.html",{'form':form})
==========end views.py======================
=========forms.py======================
from django import forms
from django.forms import ModelForm
from betterforms.multiform import MultiModelForm
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from .models import Profile, Region, Commune, Nation
class CustomSignUp(UserCreationForm):
username = forms.EmailField(label="Correo electrónico")
class Meta:
model = User
fields = ["username","password1","password2"]
class CustomSignIn(AuthenticationForm):
username = forms.EmailField(label="Correo Electrónico")
class Meta:
model = User
fields = ["username","password"]
class Profile(forms.ModelForm):
class Meta:
model = Profile
fields = ["name","last_name","mother_last_name","phone","region","commune","nation"]
class Region(forms.ModelForm):
class Meta:
model = Region
fields = ["name"]
class Commune(forms.ModelForm):
class Meta:
model = Commune
fields = ["name"]
class Nation(forms.ModelForm):
class Meta:
model = Nation
fields = ["name"]
class CustomSignUpProfileModelForm(MultiModelForm):
form_classes = {
'customSignUp': CustomSignUp,
'profile':Profile,
}
=============end forms.py =====================
============== models.py =====================
from django.db import models
from django.contrib.auth.models import User
from phone_field import PhoneField
# Create your models here.
class Region(models.Model):
cprovin = models.CharField(max_length=4)
name = models.CharField(max_length=50,verbose_name="Región")
def __str__(self):
return self.name
class Commune(models.Model):
cpoblac = models.CharField(max_length=4)
name = models.CharField(max_length=50, verbose_name="Comuna")
region = models.ForeignKey(Region,on_delete=models.CASCADE, verbose_name="Elija una región",null=False, blank=False)
def __str__(self):
return self.name
class Nation(models.Model):
name = models.CharField(max_length=50, verbose_name="Nacionalidad", null=False, blank=False)
def __str__(self):
return self.name
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE,null=False, blank=False)
name = models.CharField(max_length=30, verbose_name="Nombre", null=False, blank=False)
last_name = models.CharField(max_length=30, verbose_name="Apellido Paterno", null=False, blank=False)
mother_last_name = models.CharField(max_length=30, verbose_name="Apellido Materno", null=False, blank=False)
nation = models.ForeignKey(Nation,on_delete=models.CASCADE, verbose_name="Elija su nacionalidad", null=False, blank=False)
region = models.ForeignKey(Region,on_delete=models.CASCADE,verbose_name="Elija una región", null=False, blank=False)
commune = models.ForeignKey(Commune,on_delete=models.CASCADE,verbose_name="Elija una comuna", null=False, blank=False)
phone = PhoneField(null=False, blank=False, unique=True, help_text="Número de contacto")
def __str__(self):
return self.name
============== end models.py =====================
in this line profile.user = request.user but you should confirm that your model should have user

Can't to add a data into MongoDB using djongo "Array Model Field"

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.

how to filter data in model forms according to fields in form in Django

I am trying to filter data according to selected fields in forms. I have created a model and imported it to forms.py
from django import forms
from django.forms import ModelForm
from .models import Student_Detail, Student_Education
class StudentDetailForm(forms.ModelForm):
class Meta:
model = Student_Detail
fields = ['name', 'surname' , 'sex', 'birth_date', 'area',
'state' ,
'city' , 'pincode']
def to_python(self, value):
if not value:
return []
return value.split(',')
and my models are
`
from __future__ import unicode_literals
from django.db import models
# Create your models here.
class State(models.Model):
state = models.CharField(max_length=50)
slug = models.SlugField(unique=True, null=True, blank=True)
def __str__(self):
return self.state
class City(models.Model):
state = models.ForeignKey('State', on_delete=models.CASCADE)
city = models.CharField(max_length=70)
slug = models.SlugField(unique=True, null=True, blank=True)
def __str__(self):
return self.city
class Student_Detail(models.Model):
name = models.CharField(max_length=50)
surname = models.CharField(max_length=50, blank=True, null=True)
sex = models.CharField(max_length=4)
birth_date = models.DateTimeField()
area = models.CharField(max_length=100, blank=True, null=True)
state = models.ForeignKey('State', on_delete=models.CASCADE)
city = models.ForeignKey('City', on_delete=models.CASCADE)
pincode = models.IntegerField()
slug = models.SlugField(unique=True, null=True, blank=True)
def __str__(self):
return self.name + " " + self.surname`
Now I want to filter cities in form according to a state selected in the same form.
My View is
from django.shortcuts import render
from .models import City, Student_Detail, State, Student_Education
from django.http import HttpResponseRedirect
from .forms import StudentDetailForm, StudentEducationForm
def get_student_data(request):
if request.method == 'POST':
form_detail = StudentDetailForm(request.POST)
if form_detail.is_valid():
form_detail.save()
return HttpResponseRedirect('/home/')
else:
form_detail = StudentDetailForm()
return render(request,'home/form.html/',
{'form_detail':form_detail, })
def thanks(request):
template_name = 'home/thanks.html/'
return render(request, template_name, {})
I am also trying to enter data in two different models using forms but some thing getting wrong while saving data in two different models at view layer.
Kindly help.
Access your form fields like this myForm.fields['name'] and filter Student_Detail
from django.shortcuts import render
from django.http import HttpResponse
def student_view(request):
# your business logic or whatever goes here
if form.is_valid():
students = Student_Detail.objects.filter(name=myForm.fields['name'],
surname=myForm.fields['surname'])
return render(request, 'student_view.html', {data=students})

Categories