I'm struggling getting the right query for my project. How can i get the last lesson in a specific module . I intended to show a message to a user when he completes the last lesson of a module i.e "Congrats use you have completed module blah blah blah" this message needs only to be flashed once the last lesson of a module has been completed.
class Module(models.Model):
DRAFT = 1
SUSPENDED = 2
PUBLISHED = 3
MODULE_STATUSES = (
(DRAFT, _("Draft")),
(SUSPENDED, _("Suspended")),
(PUBLISHED, _("Published"))
)
course = models.ForeignKey(Course)
name = models.CharField(verbose_name=_("Module Name"), max_length=200, help_text=_('The module title'))
description = models.TextField(verbose_name="Module Description", help_text=_("Module description"))
prerequisite = models.ForeignKey('self', verbose_name=_("Prerequisite Module"), null=True, blank=True, default=None)
slug = models.SlugField(editable=False, help_text=_('Unique identifier'))
status = models.IntegerField(verbose_name="Module Status", choices=MODULE_STATUSES, default=PUBLISHED)
position = PositionField(collection='course', default=0)
end_of_module = models.TextField(verbose_name=_("Module Summary"), default=None, null=True, help_text=_("Wrap and summarize this module"))
last_module = models.ForeignKey('self', verbose_name=_("Previous Module"), null=True, blank=True, default=None, related_name="previous_module")
next_module = models.ForeignKey('self', verbose_name=_("Next Module"), null=True, blank=True, default=None, related_name="the_next_module")
class Meta:
verbose_name_plural = "Modules"
def __unicode__(self):
return self.name
def get_absolute_url(self):
return reverse('module_detail', args=[self.slug])
class Lesson(models.Model):
module = models.ForeignKey(Module)
name = models.CharField(verbose_name=_("Lesson Title"), max_length=200, help_text=_('The lesson title'))
prerequisite = models.ForeignKey('self', verbose_name=_("Prerequisite Lesson"), null=True, blank=True, default=None)
content = models.TextField()
instructions_before = models.TextField(verbose_name=_("Instructions before exercise"), null=True, blank=True, default=None)
instructions_after = models.TextField(verbose_name=_("Instructions after exercise"), null=True, blank=True, default=None)
quizzes = models.ManyToManyField(Quiz, verbose_name=_("Quiz"), blank=True, related_name='lessons')
slug = models.SlugField(editable=False, help_text=_('Unique identifier'))
exercises = models.ManyToManyField(Exercise, verbose_name=_("Exercise"), blank=True, related_name='lesson_exercises')
position = PositionField(collection='module', default=0)
class Meta:
verbose_name = _("Lesson")
verbose_name_plural = _("Lessons")
def __unicode__(self):
return self.name
You should filter all the Lessons by Lesson.module. Then, order by Lesson.position (reverse).
Related
I can't open my Review table, here's the models of code:
This is the `Project` model:
class Project(models.Model):
title = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
demo_link = models.CharField(max_length=2000, null=True, blank=True)
source_link = models.CharField(max_length=2000, null=True, blank=True)
tags = models.ManyToManyField('Tag', blank=True)
vote_total = models.IntegerField(default=0, null=True, blank=True)
vote_ratio = models.IntegerField(default=0, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True,
primary_key=True, editable=False)
def __str__(self):
return self.title
And this is the Review model:
class Review(models.Model):
VOTE_TYPE = (
('up', 'Up Vote'),
('down', 'Down Vote'),
)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
body = models.TextField(null=True, blank=True)
value = models.CharField(max_length=200, choices=VOTE_TYPE)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True, editable=False)
def __str__(self):
return self.title
but I can't open my Review table on admin panel (OperationalError at /admin/projects/review/)
Here's the error details:
I make migrations and do migrate:
I am new in web development with Django and MySQL database, I got to develop a web application with Django framework, after deployment of my project in the server.
after 2 months, I noticed that data from my order table was deleted as well as the data of one user is displayed in the profile of another,
I want to know what I must do as a test to know the PR eventual error and to stop the deletion of data in my database.
data often deleted in the order and customer table.
the ORDER model bind with a foreign key to other Model:
class Order(models.Model):
user = models.ForeignKey(User, null=True, blank=True, on_delete=models.CASCADE)
created = models.DateTimeField( auto_now_add=True, verbose_name=_('Creation Date'))
payed = models.DateTimeField( verbose_name=_('Payment Date'), default=datetime.now, null=True, blank=True)
reference = models.IntegerField( verbose_name=_('Order Reference'), default=0, null=True, blank=True )
customer = models.ForeignKey( Customers, verbose_name=_('Customer'), null=True, blank=True, on_delete=models.CASCADE )
company = models.ForeignKey( Compagnie, verbose_name=_('Company'), null=True, blank=True, on_delete=models.CASCADE )
class Customers(models.Model):
company = models.ForeignKey(
Compagnie,
verbose_name=_('Company'),
null=True,
blank=True,
on_delete=models.CASCADE
)
forename = models.CharField(
verbose_name=_('First Name'),
max_length=255,
null=True,
blank=True)
GENDER = [('M', _('Male')),
('F', _('Female'))]
gender = models.CharField(
verbose_name=_('Gender'),
max_length=1,
choices=GENDER,
null=True,
blank=True)
city = models.ForeignKey(
City,
verbose_name=_('City'),
null=True,
blank=True,
on_delete=models.CASCADE
)
additionalNum = models.CharField(
verbose_name=_('Additional Number:'),
max_length=60,
null=True,
blank=True,
)
adressCustomer = models.TextField(
verbose_name=_('Address Customer:'),
max_length=500,
null=True,
blank=True,
)
telCustomer = models.CharField(
verbose_name=_('Phone Customer:'),
max_length=30,
null=True,
blank=True,
)
emailCustomer = models.EmailField(
verbose_name=_('Email Customer:'),
null=True,
blank=True,
)
otherBuyerId = models.CharField(
verbose_name=_('Other Buyer ID:'),
max_length=50,
null=True,
blank=True
)
vatNumber = models.CharField(
max_length=120,
null=True,
verbose_name=_('Vat Number:'),
blank=True
)
needs_attention = models.BooleanField(
verbose_name=_('Needs attention'),
default=False)
biography = models.TextField(
verbose_name=_('Biography'),
null=True,
blank=True)
_is_updating_cache_fields = False
def get_name(self):
first = self.forename or ''
name = "%s" % (first)
return name.strip()
class Meta:
verbose_name = _('Customer')
verbose_name_plural = _('Customers')
def __unicode__(self):
return u'%s %s: %s' % (
type(self).__name__,
self.pk,
self.forename)
def __str__(self):
if self.forename:
return self.forename
else:
return "Unnamed"
Can someone give me an explanation for this problem?
i want to add in only one user from Available classic to Chosen classic but not from admin page from view when user click on button
I tried this
pro = Profile(user=request.user)
pro.classic.add(name='Frank Sinatra-i love you baby')
but i get tthis error
Before adding any objects to a many-to-many relation, the both side of many-to-many objects must obtain their id, so they should be saved first.
Another problem in this code is you need to construct a Classic object before you add it to chosen ones. The add method receives objects, not parameters of model constructor.
May following code example helps you:
pro, _ = Profile.objects.get_or_create(user=request.user)
your_classic = Classic.objects.create(name='Frank Sinatra-i love you baby')
pro.classic.add(your_classic)
give me this error
mu model code
from django.db import models
# Create your models here.
from django.utils import timezone
from django.contrib.auth.models import User
from django.db.models.signals import post_save
from django.dispatch import receiver
class RequestSong(models.Model):
music = models.CharField(max_length=150, blank=False, null=False)
stampDate = models.DateTimeField(default=timezone.now, blank=False, null=False)
def __str__(self):
return self.music
class HelpUser(models.Model):
email = models.EmailField(blank=False, null=False)
helpMessege = models.TextField(blank=False, null=False)
stampDate = models.DateTimeField(default=timezone.now)
def __str__(self):
return str(self.email)
class Language(models.Model):
language = models.CharField(
max_length=2,
choices=[
('AR', 'Arabic'),
('EN', 'English'),
],
default='AR'
)
def __str__(self):
return self.language
class ChillOut(models.Model):
name = models.CharField(max_length=50, blank=False, null=False)
music = models.FileField(upload_to='', max_length=100, blank=True, null=True)
lang = models.ForeignKey(Language, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Sad(models.Model):
name = models.CharField(max_length=50, blank=False, null=False)
music = models.FileField(upload_to='', max_length=100, blank=True, null=True)
lang = models.ForeignKey(Language, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Happy(models.Model):
name = models.CharField(max_length=50, blank=False, null=False)
music = models.FileField(upload_to='', max_length=100, blank=True, null=True)
lang = models.ForeignKey(Language, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Romantic(models.Model):
name = models.CharField(max_length=50, blank=False, null=False)
music = models.FileField(upload_to='', max_length=100, blank=True, null=True)
lang = models.ForeignKey(Language, on_delete=models.CASCADE)
def __str__(self):
return self.name
class WorkOut(models.Model):
name = models.CharField(max_length=50, blank=False, null=False)
music = models.FileField(upload_to='', max_length=100, blank=True, null=True)
lang = models.ForeignKey(Language, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Classic(models.Model):
name = models.CharField(max_length=50, blank=False, null=False)
music = models.FileField(upload_to='', max_length=100, blank=True, null=True)
lang = models.ForeignKey(Language, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
classic = models.ManyToManyField(Classic, blank=True, null=True)
workOut = models.ManyToManyField(WorkOut, blank=True, null=True)
chillOut = models.ManyToManyField(ChillOut, blank=True, null=True)
romantic = models.ManyToManyField(Romantic, blank=True, null=True)
happy = models.ManyToManyField(Happy, blank=True, null=True)
sad = models.ManyToManyField(Sad, blank=True, null=True)
def __str__(self):
return str(self.user)
# class Favorite(models.Model):
# name = models.CharField(max_length=50, blank=False, null=False)
# fav = models.ForeignKey(ChillOut, on_delete=models.CASCADE)
# pro = models.ForeignKey(Profile, on_delete=models.CASCADE)
# def __str__(self):
# return self.name
def update_user_profile(sender, **kwargs):
if kwargs['created']:
user = Profile.objects.create(user=kwargs['instance'])
post_save.connect(update_user_profile,sender=User)
I am currently attempting to create a DnD 5e Character creator using Django and SRD materials provided by WoTC. This is the first time I have ever used Django, and I am learning it as I go. I have come up against a bit of a challenge that has stone-walled me for a few days now. I have researched the issue, and after applying multiple techniques I thought may help, I've had limited luck. My question is this:
I have a number of models representing Heroes, Races, Subraces, Classes, Backgrounds and so forth. I wish to be able to restrict a users ability to choose a Subrace, based on their selection of a race beforehand.
So far I have this:
models.py
class Race(models.Model):
race_name = models.CharField(max_length=200)
race_size = models.CharField(
max_length=2, choices=SIZE_CHOICE, default='M')
race_speed = models.IntegerField(
default=30)
race_lang = models.CharField(max_length=200, null=True, blank=True)
race_str = models.IntegerField(default=0, null=True, blank=True)
race_dex = models.IntegerField(default=0, null=True, blank=True)
race_con = models.IntegerField(default=0, null=True, blank=True)
race_int = models.IntegerField(default=0, null=True, blank=True)
race_wis = models.IntegerField(default=0, null=True, blank=True)
race_cha = models.IntegerField(default=0, null=True, blank=True)
skill_spend = models.IntegerField(default=0, null=True, blank=True)
race_extra = models.TextField(max_length=2000, blank=True, null=True)
race_source = models.CharField(max_length=200, blank=True)
def __str__(self):
return self.race_name
class Meta:
verbose_name = 'Race'
verbose_name_plural = 'Races'
class Subrace(models.Model):
sub_name = models.CharField(max_length=200)
sub_size = models.CharField(
max_length=2, choices=SIZE_CHOICE, default='M', null=True)
sub_speed = models.IntegerField(
default=30, null=True)
sub_lang = models.CharField(max_length=200, null=True, blank=True)
sub_str = models.IntegerField(default=0, null=True, blank=True)
sub_dex = models.IntegerField(default=0, null=True, blank=True)
sub_con = models.IntegerField(default=0, null=True, blank=True)
sub_int = models.IntegerField(default=0, null=True, blank=True)
sub_wis = models.IntegerField(default=0, null=True, blank=True)
sub_cha = models.IntegerField(default=0, null=True, blank=True)
sub_extra = models.TextField(max_length=2000, null=True, blank=True)
sub_parent = models.ForeignKey(Race, on_delete=models.CASCADE, null=True)
def __str__(self):
return self.sub_name
class Meta:
verbose_name = 'Subrace'
verbose_name_plural = 'Subraces'
class Hero(models.Model):
def roll_stats():
d6 = die.Dice(6)
list_stats = d6.roll(4)
list_stats.sort()
add = sum(list_stats[1:4])
return add
hero_name = models.CharField(max_length=200)
author = models.ForeignKey(User, null=True)
hero_subrace = models.ForeignKey(
Subrace, on_delete=models.CASCADE, null=True, blank=True)
pub_date = models.DateTimeField('date published', blank=True, null=True)
hero_klass = models.ForeignKey(Klass, on_delete=models.CASCADE, null=True)
hero_race = models.ForeignKey(Race, on_delete=models.CASCADE)
background = models.ForeignKey(
Background, on_delete=models.CASCADE, null=True)
health = models.IntegerField(blank=True, null=True)
hero_exp = models.IntegerField(default=0, null=True)
hero_alignment = models.ForeignKey(Alignment, blank=True, null=True)
hero_str = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_dex = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_con = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_int = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_wis = models.IntegerField(default=roll_stats, null=True, blank=True)
hero_cha = models.IntegerField(default=roll_stats, null=True, blank=True)
def save(self, *args, **kwargs):
"Returns a hero's hp"
die_str = str(self.hero_klass.hit_dice)
die_nums = die_str.split("d")
die_val = int(die_nums[1])
die_roll = int(die_nums[0])
hp_die = die.Dice(die_val)
results = hp_die.roll(die_roll)
self.health = sum(results)
super(Hero, self).save(*args, **kwargs)
def __str__(self):
return self.hero_name
def get_absolute_url(self):
return reverse('hero.views.detail', args=[str(self.id)])
class Meta:
verbose_name = 'Hero'
verbose_name_plural = 'Heroes'
views.py
def new_hero(request):
user = request.user
if request.method == "POST":
form = HeroForm(request.POST)
if form.is_valid():
hero = form.save(commit=False)
hero.author = request.user
hero.save()
return redirect('detail', hero.pk)
else:
form = HeroForm()
return render(request, 'new_hero.html', {'form': form, 'user': user})
forms.py
class HeroForm(forms.ModelForm):
class Meta:
model = Hero
fields = ['hero_name', 'hero_race', 'hero_subrace',
'hero_klass', 'hero_exp', 'health', 'background',
'hero_str', 'hero_dex', 'hero_con', 'hero_int',
'hero_wis', 'hero_cha', 'hero_alignment']
def __init__(self, *args, **kwargs):
super(HeroForm, self).__init__(*args, **kwargs)
for fieldname in ['hero_str', 'hero_dex', 'hero_con', 'hero_int', 'hero_wis', 'hero_cha']:
self.fields[fieldname].disabled = True
race = Race.objects.all()
for name in race:
self.fields['hero_subrace'].queryset = Subrace.objects.filter(sub_parent=name)
I have trialled a few different techniques, but this is where I am now. This:
for name in race:
self.fields['hero_subrace'].queryset = Subrace.objects.filter(sub_parent=name)
is my most recent addition to my app. At the hero creation screen I am hit with a blank box of choices, as opposed to the full unrestricted list without the loop or queryset.
Basically I'm hoping that someone has some advice for me on a method I may be overlooking, or something that I've missed, or simply not found yet. Also please feel free to critique the rest of the code, like I said this is my first Django App :). Also my first Stack Overflow question, so thanks :)
For anyone that is wondering, I used django-smart-selects to solve my problem.
base.html
<script type="text/javascript" src="{% static 'smart-selects/admin/js/chainedfk.js' %}"></script>
<script type="text/javascript" src="{% static 'smart-selects/admin/js/bindfields.js' %}"></script>
I added the above html to my {% load staticfiles %} call.
and changed models.py:
models.py
from smart_selects.db_fields import ChainedForeignKey
class Hero(models.Model):
....
race = models.ForeignKey(Race, on_delete=models.CASCADE)
subrace = ChainedForeignKey(Subrace,
chained_field="race",
chained_model_field="race",
show_all=False,
auto_choose=True,
blank=True,
null=True)
Now I have a subrace field that is dynamically update when the user chooses a Race.
I have this chunk of code which adds up all the players hurt on one team.
teams = Team.objects.annotate(team_count=Count('Team played for')).order_by('city')
I am having an issue however. It is currently adding all injuries, but I would like to count just the players that are currently injured, or more specifically... where returned=False
Here are my models for a bit more context.
Team models.py
class Team(models.Model):
city = models.CharField(verbose_name='City', max_length=30, null=True, blank=True)
team_name = models.CharField(verbose_name='Team Name', max_length=30, null=True, blank=True)
team_logo = models.ImageField(upload_to='images/', null=True, blank=True)
team_affiliation = models.ForeignKey('self', null=True, blank=True)
def __unicode__(self):
return u'%s %s' % (self.city, self.team_name)
EDIT added player models.py
class Player(models.Model):
first_name = models.CharField(verbose_name='First Name', max_length=30, null=True, blank=True)
last_name = models.CharField(verbose_name='Last Name', max_length=30, null=True, blank=True)
team = models.ForeignKey(Team, related_name='Team played for')
position = models.ForeignKey(Position, related_name="Position")
pob = models.CharField(verbose_name='Place of Birth', max_length=100, null=True, blank=True)
dob = models.DateField()
age = models.IntegerField(null=True, blank=True)
height = models.CharField(verbose_name='Height', max_length=10, null=True, blank=True)
weight = models.CharField(verbose_name='Weight', max_length=10, null=True, blank=True)
drafted_by = models.ForeignKey(Team, related_name='drafted by', null=True, blank=True)
def __unicode__(self):
return u'%s %s' % (self.first_name, self.last_name)
Injury models.py
class PlayerInjury(models.Model):
player = models.ForeignKey(Player)
injury_type = models.ForeignKey(Injury)
injury_date = models.DateField(verbose_name='Injured On', null=True, blank=True)
description = models.CharField(verbose_name='Description', max_length=180, null=True, blank=True)
status = models.ForeignKey(Status)
projected_return = models.DateField(verbose_name='Projected Return Date', null=True, blank=True)
hide = models.BooleanField(default=False)
returned = models.BooleanField(default=False)
timestamp = models.DateTimeField(auto_now_add=True)
source = models.URLField(max_length=200, null=True, blank=True)
source_label = models.CharField(null=True, blank=True, max_length=200)
def __unicode__(self):
return u'%s - %s' % (self.player, self.injury_type)
Is there a way I can filter the annotation so that it will only count the currently injured players?
Just filter before calling annotate: .filter(player__playerinjury__returned=False).annotate(...).