I connected my database to django. I want to enable user (teacher) insert the name of a student and get test results on certain subjects.
I run python3 manage.py inspectdb and inserted it into models.py
class Profilez(models.Model):
student = models.CharField(max_length=255)
schgroup = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'profilez'
class Schoolz(models.Model):
profilez_id = models.AutoField(primary_key=True)
lit = models.IntegerField(blank=True, null=True)
math = models.IntegerField(blank=True, null=True)
class Meta:
managed = False
db_table = 'schoolz'
in forms.py i put:
class StudentForm(forms.ModelForm):
SUB = (
('lit', 'lit'),
('math', 'math')
)
student = forms.CharField(max_length=150, label='', widget=forms.TextInput)
class Meta:
model = Schoolz
fields = ('student',)
in views.py:
def home(request):
if request.method == "POST":
form = StudentForm(request.POST)
if form.is_valid():
form1 = form.save(commit=True)
name = form1.student
ab=schoolz.objects.all()
context={
'name':name,
}
return render(request, 'book/analysis.html', context)
else:
form = StudentForm()
return render(request, 'book/search.html', {'form': form})
Can you please help me to understand what i am doing wrong and how to get value for certain subject for exmaple math subject.
I would appreciate help and guidance to undertand and execute it. I am struggling a month.
Notes
Add a field in Profile that should be unique for each student. Currently I am assuming name and surname combination will be unique.
If you use ajax, you can get score without refresh. Current way I have used is not very good.
You don't have to write models if you already have in DB. You can remove your models. add already present models in models.py and makemigrations and migrate.
Add a ForiegnKey field in Class10
class Class10(models.Model):
profile_id = models.IntegerField()
math = models.IntegerField()
literature = models.IntegerField()
biology = models.IntegerField()
student = models.ForeignKey(Profile, on_delete=models.CASCADE, related_name='stud_name') # add this in model
class Meta:
managed = False # make this True otherwise makemigrations won't get the changes.
db_table = 'class_10'
class Profile(models.Model):
student_name = models.CharField(max_length=255)
student_surname = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'profile'
views.py
def home(request):
if request.method == "POST":
form = StudentlForm(request.POST)
if form.is_valid():
form_1 = form.save(commit=False)
name = form_1.student_name
surname = form_1.student_surname
subject = form_1.subject
fil = Q(student__student_name=name) & Q(student__student_surname=surname)
student_1 = StudentScore.objects.filter(fil).values()
score = student_1[0][subject] # answer
context={
'score':score
}
return render(request, 'school/analysis.html', context)
else:
form = StudentlForm()
return render(request, 'school/search.html', {'form': form})
forms.py
class StudentForm(forms.ModelForm):
SUB = (
('math', 'math'),
('literature', 'literature'),
('biology', 'biology')
)
student_name = forms.CharField(max_length=150, label='', widget=forms.TextInput)
student_surname = forms.CharField(max_length=150, label='', widget=forms.TextInput)
subject = forms.CharField(widget=forms.Select(choices=SUB))
class Meta:
model = Profile
fields = ('student_name', 'student_surname', 'subject')
#Nina,
Please look on the relationship> it's general idea for the Student & Gradesheet model
class Student(models.Model):
std_name = models.CharField(max_length=100)
def __str__(self):
return self.std_name
class Gradesheet(models.Model):
student = models.ForeignKey(Student, on_delete=models.CASCADE)
sub = models.CharField(max_length=50)
grade = models.CharField(max_length=50)
def __str__(self):
return self.student.std_name
So if you need to search for a student grade for particular subject:
std_info = Student.objects.get(std_name='Nina')
Then you will get a Student Class instance for Nina.
Now fetch the data by relationship:
std_grade = std_info.gradesheet_set.filter(sub='math')
You will get QuerySet. Then just :
std_grade[0].grade
You will get your student's grade for particular subject. Look its a model relationship. So you may use other filtering options also to get your desired result.
According to your given model:
Instead of the profile_id you should use the Profile object which will help you to take the control through django ORM.
class Profile(models.Model):
student_name = models.CharField(max_length=255)
student_surname = models.CharField(max_length=255)
class Meta:
managed = False
db_table = 'profile'
class Class10(models.Model):
#profile_id = models.IntegerField()
profile = models.OneToOneField(Profile, on_delete=models.CASCADE,related_name='profile')
math = models.IntegerField()
literature = models.IntegerField()
biology = models.IntegerField()
class Meta:
managed = False
db_table = 'class_10'
So your query can be build by:
std_profile = Profile.objects.get(student_name='SomeoneName')
Now turn it for get the grade. Result would be:
math_grade = std_profile.profile.math
biology_grade = std_profile.profile.biology
literature_grade = std_profile.profile.literature
average_grade = ((math_grade + biology_grade + literature_grade)/3)
Here, your model relationship:Profile to Class10 is OneToOne
Related
models.py:
from django.db import models
class Course(models.Model):
course = models.TextField(blank=True)
class Student(models.Model):
first_name = models.TextField()
last_name = models.TextField()
course = models.ManyToManyField(Course)
forms.py:
from django import forms
from .models import Student, Course
class StudentForm(forms.ModelForm):
class Meta:
model = Student
fields = ['first_name', 'last_name', 'course']
class CourseForm(forms.ModelForm):
class Meta:
model = Course
fields = ['course']
views.py:
def students_view(request):
if request.method == 'POST':
students_form = StudentForm(request.POST)
if students_form.is_valid():
students_form.save()
print(Student.objects.all().values())
students_form = StudentForm()
context = {
'form':students_form
}
return render(request, 'courses/courses.html', context)
If I print print(Student.objects.all().values()) than I see student's ID, first_name and last_name. But I don't see in which groups they belong to. How to print that?
Like this for example:
students = Student.objects.prefetch_related("course")
print([(s, list(s.course.all()),) for s in students])
I have created a booking api where user have to login to book a package ( holiday package). Now how can a user after login check their booking history that means the bookings that they made? That means I want to create an api where if a user clicks my bookings, it will return the bookings that the user has made.
My booking model:
class Booking(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
package = models.ForeignKey(Package, on_delete=models.CASCADE, related_name='package')
name = models.CharField(max_length=255)
email = models.EmailField()
phone = models.CharField(max_length=255)
bookedfor = models.DateField()
created_at = models.DateTimeField(auto_now_add=True)
class Package(models.Model):
destination = models.ForeignKey(Destination, on_delete=models.CASCADE)
package_name = models.CharField(max_length=255)
featured = models.BooleanField(default=False)
price = models.IntegerField()
duration = models.IntegerField(default=5)
discount = models.CharField(max_length=255, default="15% OFF")
discounted_price = models.IntegerField(default=230)
savings = models.IntegerField(default=230)
special_discount = models.BooleanField(default=False)
My booking serializer:
class BookingSerializer(serializers.ModelSerializer):
# blog = serializers.StringRelatedField()
class Meta:
model = Booking
fields = ['name', 'email', 'phone', 'bookedfor']
# fields = '__all__'
My booking view:
class BookingCreateAPIView(CreateAPIView):
permission_classes= [IsAuthenticated]
queryset = Booking.objects.all()
serializer_class = BookingSerializer
def perform_create(self, serializer):
# user = self.request.user
package = get_object_or_404(Package, pk= self.kwargs['pk'])
serializer.save(user=self.request.user,package=package)
First of all you have to add a new url at your urls.py file.
After that in the classs BookingCreateAPIView you should create a new method to display all the Bookings made by the user.
The method could be:
def perform_query(self):
bookings = Booking.objects.get(user=request.user)
return HttpResponse(bookings)
You can use for get the user in views.py orders like :-
from .models import Booking
def BookingCreateAPIView(CreateAPIView):
orders = Booking.objects.get(user=request.user)
Then Try this :-
def BookingCreateAPIView(CreateAPIView):
bookings = Booking.objects.order_by('created_at')
bookings = Booking.objects.filter(owner=request.user).order_by('created_at')
I'm trying to save a ModelForm with foreignkey field from another model. But somehow the data is not being saved.
The primary key of the foreignkey field in the Problem models is from Biodata models
index.html form is loaded with session['patient'] value that should be the value of the foreignkey in the Problem models upon creation of new item.
Upon submitting the form, it says the new item is successfully added, but at the backend, it wasn't saved at all.
Here's the code :
models.py
class Biodata(models.Model):
lastname = models.CharField(max_length=50)
firstname = models.CharField(max_length=50)
dob = models.DateField()
sex = models.CharField(max_length=10)
address = models.CharField(max_length=100,blank=True)
suburb = models.CharField(max_length=40,blank=True)
state = models.CharField(max_length=50,blank=True)
postcode = models.CharField(max_length=6,blank=True)
def __str__(self):
return self.firstname + " " + self.lastname
class Problems(models.Model):
biodata = models.ForeignKey(Biodata, on_delete = models.CASCADE, default=None)
problem = models.CharField(max_length=200)
notes = models.CharField(max_length=300)
status = models.CharField(max_length=30)
date = models.CharField(max_length=10)
def __str__(self):
return self.problem
views.py
def problem_add(request):
patient_id = request.session['patient']
form = ProblemForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.Biodata = Biodata.objects.get(id=patient_id)
instance.save
messages.success(request,('Problem added'))
return redirect('/crud/index/')
else :
messages.success(request,('There is error in the form'))
return redirect('/crud/index/')
forms.py
class ProblemForm(forms.ModelForm):
STATUS = [('S','Stable'),('U','Unstable'),('I','Inactive'),('O','Ongoing Dx.')]
problem = forms.CharField(label='',max_length=50, widget=forms.TextInput(attrs={'placeholder':'Problem'}))
notes = forms.CharField(label='', widget=forms.Textarea(attrs={'rows':4,'placeholder':'Notes'}))
status = forms.ChoiceField(label='', widget=forms.Select(attrs={'placeholder':'Status'}), choices=STATUS)
date = forms.DateField(label='', widget=forms.DateInput(format='%m/%d/%Y', attrs={'class':'datepicker','placeholder':'Date'}),
input_formats=('%m/%d/%Y', ))
class Meta :
model = Problems
fields = ('problem','notes','status','date')
In your views.py correct it
instance.biodata=Biodata.objects.get(id=patient_id)
You are trying
instance.Biodata = .......
Since Biodata field does not exist in Problems table
You have just written instance.save and this doesn't result in any error because it is valid to write it like that. The execution moves to new line and you get the success message.
Because save is a method on instance you should call it like instance.save().
I've a registration form, where user must chose one of 2 options.
Django renders all correctly, django admin also have it ok, but db records all possible choices as value.
forms.py
class UserRegisterForm(UserCreationForm):
email = forms.EmailField()
class Meta:
model = User
fields = ['username', 'email','password1','password2']
class UserProfileForm(forms.ModelForm):
terms_compliance = forms.BooleanField(label=mark_safe('I agree with terms and conditions '))
class Meta:
model = UserProfile
widgets = {'role': forms.RadioSelect}
fields = ('role','terms_compliance')
def __init__(self):
self.fields['terms_compliance'].initial = True
models.py
class UserProfile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
role_choices = [('publisher','Publisher'), ('advertiser','Advertiser')]
role = models.CharField(max_length=15, choices=role_choices, default=None)
terms_compliance = models.BooleanField()
def __str__(self):
return self.user.username
In new instance (which is user.userprofile.role_choices) I need advertiser or publisher, but all I have is: [('publisher','Publisher'), ('advertiser','Advertiser')]
If you want to provide choices in a Database Field. Do like this:
class UserProfile(models.Model):
class RoleChoice(ChoiceEnum):
PUBLISHER = 'Издатель'
ADVERTISER = 'Рекламодатель'
user = models.OneToOneField(User, on_delete=models.CASCADE)
role = models.CharField(max_length=15, choices=RoleChoice.choices(), default=None)
terms_compliance = models.BooleanField()
def __str__(self):
return self.user
In Views.py, populate the DB like this.
For example:
...
choice = request.query_params.get('choice') or UserProfile.RoleChoice.PUBLISHER.value
...
For more details read from here: https://django-mysql.readthedocs.io/en/latest/model_fields/enum_field.html
when I try to feel department field is show me this error.
I don't understand this error.. please help me out
Cannot assign "'HR'": "Employee.department" must be a "Department" instance.
here is my model.py
class Department(models.Model):
name = models.CharField(max_length= 20,null=True)
def __str__(self):
return self.name
class Employee(models.Model):
employee_name = models.CharField(max_length= 20, null=True)
surname = models.CharField(max_length= 20, null=True)
address = models.CharField(max_length = 50, null=True)
qualification = models.CharField(max_length = 30,null=True)
contact_num = models.IntegerField(null=True)
department = models.ForeignKey(Department, on_delete=models.CASCADE)
def __str__(self):
return self.employee_name
here is my form.py
class AdForm(forms.ModelForm):
employee_name = forms.CharField()
surname = forms.CharField ()
address = forms.CharField ()
qualification = forms.CharField ()
contact_num = forms.IntegerField ()
department = forms.CharField()
class Meta:
model = Employee
fields = ('employee_name',
'surname',
'address',
'qualification',
'contact_num',
'department')
here is my view.py
def create(request):
if request.method == 'POST':
form = AdForm(request.POST)
if form.is_valid(): #getting error on this
form.save()
return HttpResponseRedirect(reverse('employee-list'))
else:
form = AdForm()
return render(request, 'employee/create.html', {'form': form})
The department field on your Employee model is a ForeignKey field, but in your AdForm you define it as CharField.
You could fix the field definition in your form. Alternatively, you could also simply remove the explicit field definition. When using a model form, Django will select the correct field type for you.
class AdForm(forms.ModelForm):
class Meta:
model = Employee
fields = ('employee_name',
'surname',
'address',
'qualification',
'contact_num',
'department')
This will render the department field as a <select> widget, allowing you to select from your (pre-existing) departments.