When I create new sesid in session I need all the courses to add to the sesid in Registration model.
I am creating a result management system using django.
What I want to do is to
create a session (it is done)
then automatically, all the courses from course model will be in the
session model ( I don't need to add individually) and then show a
page that enables to add batch to the added courses.
After submission all the students of the corresponding batch will be
added to the course and thus session and redirect to somewhere to enable user to assign each course to a specific teacher
each of the students have several marks fields to cover by the assigned teacher
the result will be calculated and saved in the database after input from a table (better as an imported excel file)
so far, I have made this:
from django.db import models
from django.contrib.auth.models import User
from django.urls import reverse
class Course(models.Model):
cid = models.AutoField(primary_key=True)
cnam = models.CharField(max_length=200)
cidn = models.IntegerField()
cred = models.IntegerField()
def __str__(self):
return 'IT-' + str(self.cidn) + ' - ' + self.cnam
class Student(models.Model):
snam = models.CharField(max_length=200)
sid = models.AutoField(primary_key=True)
sroll = models.IntegerField()
sreg = models.IntegerField()
sbtc = models.IntegerField()
sses = models.CharField(max_length=10)
def __str__(self):
return self.snam
class Teacher(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
full_name = models.CharField(max_length=200, null=True)
umob = models.CharField(max_length=20, blank=True, default='')
ulogo = models.ImageField(upload_to='media', blank=True)
def __str__(self):
return self.user.username
def createprofile(selfsender, **kwargs):
if kwargs['created']:
user_profile = Teacher.objects.creeate(user=kwargs['instance'])
class Session(models.Model):
sesid = models.IntegerField(primary_key=True,verbose_name= ('Session'))
def __str__(self):
return str(self.sesid)
def get_absolute_url(selfself):
return reverse('Dashboard:session')
class Registration(models.Model):
session = models.ForeignKey(Session, on_delete=models.CASCADE)
teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE)
course = models.ForeignKey(Course, on_delete=models.CASCADE)
# def __str__(self):
# return str(self.session.sesid) + ' - ' + 'IT-' + self.str(course.cidn) + ' - ' + self.course.cnam + ' - ' + self.str(Teacher.user)
class Result(models.Model):
reg = models.ForeignKey(Registration, on_delete=models.CASCADE)
student = models.ForeignKey(Student, on_delete=models.CASCADE)
ct1 = models.FloatField(null=True, blank=True)
ct2 = models.FloatField(null=True, blank=True)
ct3 = models.FloatField(null=True, blank=True)
asn = models.FloatField(null=True, blank=True)
# avg
atd = models.IntegerField(null=True, blank=True)
#total
def __str__(self):
return str(self.reg.session) + ' - ' + 'IT-' + str(self.reg.course.cidn) + ' - ' + self.student.snam
views.py:
from django.urls import reverse_lazy
from django.views import generic
from django.views.generic.detail import DetailView
from django.views.generic.list import ListView
from django.views.generic.edit import CreateView
from django.shortcuts import render, redirect
from django_tables2 import RequestConfig
from .tables import *
from .models import *
from .forms import CustomUserChangeForm
class Login(generic.CreateView):
form_class = CustomUserChangeForm
success_url = reverse_lazy('index')
template_name = 'Dashboard/login.html'
class IndexView(ListView):
template_name = 'Dashboard/index.html'
def get_queryset(self):
return Course.objects.all()
def course(request):
table = CourseTable(Course.objects.all())
RequestConfig(request).configure(table)
return render(request, 'Dashboard/course.html', {'table': table})
def teacher(request):
table = TeacherTable(Teacher.objects.all())
RequestConfig(request).configure(table)
return render(request, 'Dashboard/teacher.html', {'table' : table})
def student(request):
table = StudentTable(Student.objects.all())
RequestConfig(request).configure(table)
return render(request, 'Dashboard/student.html', {'table' : table})
def result(request):
table = ResultTable(Result.objects.all())
RequestConfig(request).configure(table)
return render(request, 'Dashboard/result.html', {'table' : table})
class SessionView(CreateView,ListView):
template_name = 'Dashboard/createSession.html'
model = Session
fields = ['sesid']
def get_queryset(self):
return Session.objects.all()
How can I approach to the dynamic update of database?
Based on the explanation in the comment, something like this should do the trick.
For reusability, you could also move the for course... bit to a method on Session, such as add_courses(self, teacher): ...
class SessionView(CreateView, ListView):
template_name = 'Dashboard/createSession.html'
model = Session
queryset = Session.objects.all()
fields = ['sesid']
def form_valid(self, form): # this will be the creation form
instance = form.save() # save the empty session
for course in Course.objects.all():
Registration.objects.create(
session=instance,
course=course,
teacher=self.request.user.teacher, # (Is this correct?)
)
return HttpResponseRedirect(self.get_success_url())
Related
I need to get id from logged user to filter query in models.how to get users id in django model?
Thanks
in models.py:
class Portfo(models.Model):
product = models.ForeignKey(Product, on_delete=models.CASCADE, null=True)
sell = models.ForeignKey(Sell, on_delete=models.CASCADE, null=True)
customer = models.ForeignKey(Customer, on_delete=models.CASCADE, null=True)
profit = models.PositiveIntegerField(null=True)
final_amount = models.IntegerField(null=True)
def __str__(self):
return self.product.name
def final_amount(self):
final_amount = 0
buy = Buy.objects.filter(product_id=self.product.id, owner__exact=...)
sell = Sell.objects.filter(product_id=self.product.id)
I need to get id from logged user to filter query in models.
Models are designed to be request-unaware. If you want to retrieve the user id, you will need to pass it through a parameter, so:
class Portfo(models.Model):
# …
def final_amount(self, user_id):
final_amount = 0
buy = Buy.objects.filter(product_id=self.product_id, owner_id=user_id)
sell = Sell.objects.filter(product_id=self.product_id, owner_id=user_id)
# …
In the view, you can then use the .final_amount(…) method, for example with:
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
#login_required
def some_view(request, pk):
my_porfolio = get_object_or_404(Portfolio, pk=pk)
final_amount = my_portfolio.final_amount(request.user.id)
# …
I have the following models:
class Student(models.Model):
first_name = models.CharField(verbose_name='student first name', max_length=64)
last_name = models.CharField(verbose_name='student last name', max_length=64)
email = models.EmailField()
class Meta:
db_table = 'student'
def __str__(self):
return self.first_name + ' ' + self.last_name
class Course(models.Model):
name = models.CharField(max_length=255)
description = models.TextField()
start_date = models.DateField(null=True, blank=True, default=None)
end_date = models.DateField(null=True, blank=True, default=None)
class Meta:
db_table = 'course'
def __str__(self):
return self.name
class CourseParticipant(models.Model):
course = models.ForeignKey(Course, related_name='courses', on_delete=models.CASCADE)
student = models.ForeignKey(Student, related_name='student_name', on_delete=models.CASCADE)
completed = models.BooleanField(null=False, default=False)
class Meta:
db_table = 'course_participant'
def __str__(self):
return self.course, self.student
And urs:
urlpatterns = [
path('course', CourseAPIView.as_view()),
path('course/<int:pk>/', CourseAPIDetailView.as_view()),
path('student', StudentAPIView.as_view()),
path('student/<int:pk>/', StudentAPIDetailView.as_view()),
path('student/assigned_to_course', StudentAssignedToTheCourseAPIView.as_view()),
path('student/assign_student_to_course', StudentAssignToCourse.as_view()),
path('student/assigned_to_course/<int:pk>/', StudentAssignedToTheCourseDetailView.as_view()),
path('student/report/<int:pk>/', StudentReportView.as_view()),
]
I need made export some data in csv, in next format:
student full name
number of assigned courses to the student
number of completed courses by student
For example:
Test Student,10, 3
Test Student1,12, 1
Test Student2,5, 3
Test Student3,5, 4
So, what view should be for it. I mean, how i can get data like student full name and etc. I will be grateful for the help
You can use Python's csv module.
At first, I would suggest defining full_name as a property in your Student model since it will make it clearer:
class Student(models.Model):
...
#property
def full_name(self):
return self.first_name + ' ' + self.last_name
Then you can define a simple APIView for the job:
import csv
from django.http import HttpResponse
from rest_framework.views import APIView
class ExportCSVStudents(APIView):
def get(self, request, *args, **kwargs):
response = HttpResponse(content_type='text/csv')
response['Content-Disposition'] = 'attachment; filename="export.csv"'
writer = csv.writer(response)
for student in Student.objects.all():
assigned_courses = CourseParticipant.objects.filter(student=student)
completed_courses = assigned_courses.filter(completed=True)
row = ','.join([
student.full_name,
assigned_courses.count(),
completed_courses.count()
])
writer.writerow(row)
return response
This should automatically download a file called export.csv with your desired data, after you register it in your urlconf and access it via simple HTTP GET.
I tried to search a local manager from zipcode A to zipcode B.
For example:
"Manager west" as the regions
zipform | zipto
17000 to 17259
17300 to 19309
19360 to 19419
23920 to 23999
models.py
class Region(models.Model):
zipfrom = models.CharField(u'PLZ von', max_length=50, blank=True)
zipto = models.CharField(u'PLZ bis', max_length=50, blank=True)
class Meta:
verbose_name = u'Region'
verbose_name_plural = u'Regionen'
def __unicode__(self):
return "{0} - {1}".format(self.zipfrom, self.zipto)
class AddPartner(models.Model):
name = models.CharField(u'Name', max_length=50)
regionen = models.ManyToManyField(Region, verbose_name=u'regionen', blank=True)
class Meta:
verbose_name = u'AddPartner'
verbose_name_plural = u'AddPartners'
def __unicode__(self):
return self.name
views.py
from django.shortcuts import redirect, render, render_to_response
from django.template import Template, RequestContext
from partner.models import AddPartner, Region
from django.db.models import Q
def partnerview(request):
partner = AddPartner.objects.all()
region = Region.objects.all()
if 'q' in request.GET and request.GET['q']:
q = request.GET['q']
suche = region.filter(Q(zipto=q) | Q(zipform=q)) # despair
else:
return render_to_response('partner.html',{
'partner': partner, 'region': region, },context_instance=RequestContext(request))
return render_to_response('partner.html',{
'partner': partner, 'region': region,'suches': suche, 'query': q
},context_instance=RequestContext(request))
I am a beginner and I have no idea to handle this. The next big question is to get the rigt result "the local manager" in the template.
You can use the pair of __lte/__gte lookups. The next query will find the regions where zipfrom <= q <= zipto:
suche = region.filter(zipfrom__lte=q, zipto__gte=q)
To get the list of managers for found regions use the following query:
managers = AddPartner.objects.distinct().filter(regionen__in=suche)
I am following a tutorial online for Django. The presenter loads in random data as follows:
for i in xrange(100): Vote(link = Link.objects.order_by('?')[0],voter=a).save()
From what I could understand, it goes from 0 to 100 and creates a new vote. The vote object has a link object. I don't understand what the order_by('?') means.
Here is the model.py file:
from django.db import models
from django.contrib.auth.models import User
from django.db.models import Count
class LinkVoteCountManager(models.Manager):
def get_query_set(self):
return super(LinkVoteCountManager, self).get_query_set().annotate(
votes=Count('vote')).order_by("-votes")
class Link(models.Model):
title = models.CharField("Headline", max_length=100)
submitter = models.ForeignKey(User)
submitted_on = models.DateTimeField(auto_now=True)
rank_score = models.FloatField(default=0.0)
url = models.URLField("URL", max_length=250, blank=True)
description = models.TextField(blank=True)
with_votes = LinkVoteCountManager()
objects = models.Manager()
def __unicode__(self):
return self.title
class Vote(models.Model):
voter = models.ForeignKey(User)
link = models.ForeignKey(Link)
def __unicode__(self):
return "%s voted %s" %(self.voter.username, self.link.title)
I have the following models: http://slexy.org/view/s20T8yOiKZ
from mxutils.cms_services import generate_secid
from django.db import models
from django.contrib import admin
from django import forms
class World(models.Model):
title = models.CharField(max_length=150)
secid = models.SlugField(max_length=1000, editable=False)
elements = models.ManyToManyField("Element", related_name='elements', blank=True, null=True)
metadata = models.OneToOneField("Category_metadata", blank=True, null=True)
def save(self):
if not self.pk:
super(World, self).save()
self.secid = generate_secid(self.title, self.pk, World.objects.all())
return super(World, self).save()
def __unicode__(self):
return "%s" % self.title
class Element(models.Model):
parent = models.ForeignKey(World, related_name='element_parent')
world = models.ForeignKey(World, related_name='world', blank=True, null=True)
item = models.ForeignKey("Item", blank=True, null=True)
value = models.DecimalField(default=0, max_digits=5, decimal_places=3)
def save(self):
if self.world and self.item:
return None
elif not self.world and not self.item:
return None
else:
return super(Element, self).save()
def __unicode__(self):
if self.world:
return "%s" % self.world.title
else:
return "%s" % self.item.title
class ElementInline(admin.TabularInline):
model = Element
extra=1
class WorldAdmin(admin.ModelAdmin):
inlines = [ElementInline,]
list_display = ('title',)
ordering = ['title']
search_fields = ('title',)
When I try to click add button for worlds in admin page it shows me the following error:
class 'cms_sample.world_models.Element' has more than 1 ForeignKey to class 'cms_sample.world_models.World'.
I think it's something to do with inline.
What can it be?
Django doesn't know which of the two foreign keys (parent and world) is to be inlined using the ElementInline.
class ElementInline(admin.TabularInline):
model = Element
fk_name = 'parent' #or 'world', as applicable.
extra=1