DJANGO 2.0
So basically I was tasked to make a drag and drop form, in which I would have a table of available users, and create a team from that table, by dragging and dropping the users.
My problem is, that I have no idea where to start tackling this problem, mostly because I'm not sure how to validate the data that is dropped after I hit submit.
So my goals are:
Validate drag-n-drop data
Add a user status so it won't be reassigned to another team.
Assign credits to users upon competition of the given task (this is used for making reports and to add an "achievements" functionalities)
Anything leading to drag-n-drop validation in django will be helpful too
My models.py for users
class Employee(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
department = models.CharField(
max_length=100,
default=''
)
title = models.CharField(
max_length=60,
default=''
)
date_joined = models.DateField(
default=datetime.date.today
)
avatar = models.ImageField(
upload_to="avatars"
)
My models.py for creating the teams, (I still need to write a Foreign Key or something to store the users that will be on the team):
class Task(models.Model):
Task_name = models.CharField(
max_length=15,
default=""
)
Task_date = models.DateField()
Task_deadline = models.DateField()
Task_credits = models.DecimalField(
max_digits=2,
decimal_places=0
)
Task_reference = models.CharField(
max_length=100,
default=''
)
Task_description = models.TextField(
max_length=3000
)
Task_notes = models.TextField(
max_length=500
)
Task_completition = models.CharField(
max_length=15,
default=_lazy('Assigned')
choices=
)
Task_tags = models.CharField(
max_length=20,
default='',
)
Related
I created the following context variables context["genders"] and context["ages"].
Currently, there is a lot of work done by Python under #Filtering, while I think it would be better done in #Query.
However, that's where I currently struggle. Do you have an idea on how to achieve the pre-filtering in the #Query section via SQL?
Please not the int(answer_obj.answer) as answer is a TextField.
# Query
responses = Response.objects.filter(
survey__event=12, survey__template=settings.SURVEY_POST_EVENT
).order_by("-created")
# Filtering
filtered_responses = []
for response in responses:
for answer_obj in response.answers.all():
if (
answer_obj.question.focus == QuestionFocus.RECOMMENDATION_TO_FRIENDS
and int(answer_obj.answer) >= 8
):
filtered_responses.append(response)
# Context
gender_list = []
age_list = []
for response in filtered_responses:
for answer_obj in response.answers.all():
# Here a list of all the genders that gave that answer:
if answer_obj.question.focus == QuestionFocus.GENDER:
gender_list.append(answer_obj.answer)
# Here a list of all the ages that gave that answer:
if answer_obj.question.focus == QuestionFocus.AGE:
age_list.append(answer_obj.answer)
context["genders"] = gender_list
context["ages"] = age_list
models.py
class Answer(TimeStampedModel):
question = models.ForeignKey(
"surveys.Question", on_delete=models.CASCADE, related_name="answers"
)
response = models.ForeignKey(
"Response", on_delete=models.CASCADE, related_name="answers"
)
answer = models.TextField(verbose_name=_("Answer"))
choices = models.ManyToManyField(
"surveys.AnswerOption", related_name="answers", blank=True
)
class Response(TimeStampedModel):
class Language(Choices):
CHOICES = settings.LANGUAGES
survey = models.ForeignKey(
"surveys.Survey", on_delete=models.CASCADE, related_name="responses"
)
order = models.ForeignKey(
"orders.Order",
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="response",
)
attendee = models.ForeignKey(
"attendees.Attendee",
on_delete=models.SET_NULL,
null=True,
blank=True,
related_name="response",
)
total_time = models.PositiveIntegerField(
null=True, blank=True, verbose_name=_("Total time")
)
ip_address = models.GenericIPAddressField(null=True, verbose_name=_("IP Address"))
language = models.CharField(
max_length=Language.get_max_length(),
choices=Language.CHOICES,
verbose_name=_("Language"),
)
class Question(TimeStampedModel):
survey = models.ForeignKey(
"surveys.Survey", on_delete=models.CASCADE, related_name="questions"
)
question_set = models.ForeignKey(
"QuestionSet", on_delete=models.CASCADE, related_name="questions"
)
title = models.CharField(max_length=100, verbose_name=_("Title"))
help_text = models.TextField(null=True, blank=True, verbose_name=_("Help text"))
type = models.CharField(
max_length=QuestionType.get_max_length(),
choices=QuestionType.CHOICES,
verbose_name=_("Question type"),
)
focus = models.CharField(
max_length=QuestionFocus.get_max_length(),
choices=QuestionFocus.CHOICES,
verbose_name=_("Question focus"),
)
required = models.BooleanField(default=False, verbose_name=_("Is required?"))
position = models.PositiveSmallIntegerField(
null=True, blank=True, verbose_name=_("Position")
)
# Translatable fields
i18n = TranslationField(fields=("title", "help_text"))
class Meta:
ordering = ("position", "pk")
Filtering
It looks to me, that you want all responses, where answer is higher than eight for question focused on friend recommendation. Is it expected that you might have the same response appended to the filtered responses more than once, or will there be only one question of this type? I think you could rewrite it as follows:
filtered_response = responses.filter(
answers__question__focus=QuestionFocus.RECOMMENDATION_TO_FRIENDS
).annotate(
answer_num=Cast("answers__answer", IntegerField()),
).filter(
answer_num__gt=8,
)
And populating the context:
context["genders"] = Answer.objects.filter(
response_id__in=filtered_response.values_list("id", flat=True),
question__focus=QuestionFocus.GENDER,
).values_list("answer", flat=True)
context["ages"] = Answer.objects.filter(
response_id__in=filtered_response.values_list("id", flat=True),
question__focus=QuestionFocus.AGE,
).values_list("answer", flat=True)
This should allow you to avoid firing the queries to iterate over response.answers.all(), and hopefully achieve the same result.
I need help with creating models for my simple Django app.
The purpose of the application is to let users (referees) register for matches, then admin will choose 2 users (referees) from the list of registered for given match. Right now my Matches model looks like below:
class Match(models.Model):
match_number = models.CharField(
max_length=10
)
home_team = models.ForeignKey(
Team,
on_delete=models.SET_NULL,
null=True,
related_name='home_team'
)
away_team = models.ForeignKey(
Team,
on_delete=models.SET_NULL,
null=True,
related_name='away_team'
)
match_category = models.ForeignKey(
MatchCategory,
on_delete=models.SET_NULL,
null=True
)
date_time = models.DateTimeField(
default=timezone.now
)
notes = models.TextField(
max_length=1000,
blank=True
)
What I thought to do is to create new Model named MatchRegister where I will be saving match_id and user_id, something like below:
class MatchRegister(models.Model):
match_id = models.ForeignKey(
Match
)
user_id = models.ForeignKey(
Users
)
And than admin will have list of registered user for given match from which he will choose two, so I thought to modify my Match model like this (add two new Fields):
class Match(models.Model):
match_number = models.CharField(
max_length=10
)
home_team = models.ForeignKey(
Team,
on_delete=models.SET_NULL,
null=True,
related_name='home_team'
)
away_team = models.ForeignKey(
Team,
on_delete=models.SET_NULL,
null=True,
related_name='away_team'
)
match_category = models.ForeignKey(
MatchCategory,
on_delete=models.SET_NULL,
null=True
)
date_time = models.DateTimeField(
default=timezone.now
)
notes = models.TextField(
max_length=1000,
blank=True
)
ref_a = models.ForeignKey(
Users,
on_delete=models.SET_NULL,
null=True,
related_name='ref_a'
)
ref_b = models.ForeignKey(
Users,
on_delete=models.SET_NULL,
null=True,
related_name='ref_b'
)
This is my solution but I don't know if it is done in proper way so I want to ask you for help.
If you know for certain that matches will only ever have two refs, then what you propose is just fine. However, if there's an opportunity in the future for the number to change (only one, or perhaps three), an alternative would be to add a flag to the intermediate table:
class MatchRegister(models.Model):
match_id = models.ForeignKey(Match)
user_id = models.ForeignKey(Users)
chosen = models.BooleanField(default=False)
You would need business logic to constrain the number of "chosen" refs to the number you anticipate. This option makes it easy to increase or decrease the number of refs without adding or removing columns (just change the business logic).
Is it possible to add a custom fields validation on the serializers that will only show a specific field in the views depending on the condition stated. e.g from the model below there is a visit class that accounts for patient visits. Depending on the following statuses below,one will only view certain specific fields e.g suppose a patient arrives, one should only see the visit_start_date, the status_time will be recorded etc.
STATUSES=('
('ARRIVED','Arrived'),
('CHECKED_IN','Checked In'),
('IN_ROOM','In Room'),
('CANCELLED','Cancelled'),
('COMPLETE','Complete')
)
class Visit(models.Model):
patient = models.ForeignKey(
settings.AUTH_USER_MODEL,
related_name='rel_visits')
discharge_notes = models.TextField(
default=None,
blank=True,
null=True)
discharged = models.NullBooleanField(default=False, null=True, blank=True)
admitted = models.NullBooleanField(default=False, null=True, blank=True)
current = models.NullBooleanField(default=False, null=True, blank=True)
status_time = models.DateTimeField(auto_now_add=True)
status = models.ChoiceField(max_length=20,choices=STATUSES)
visit_start_time = models.DateTimeField(blank=True)
visit_duration = models.IntegerField(blank=True)
session_start_time = models.DateTimeField(blank=True)
session_end_time = models.DateTimeField(blank=True)
check_in = models.BooleanField(default=False)
check_out = models.BooleanField(default=False)
Here is how the complete form looks like :
In your visit model patient is an auth_user_model(Django user) so you can add permission in patient(auth_user_model),
1)create custom permission of auth user then
2)create a group called patient, add custom permission on this group.
then write a query in views.py according to permission.
I am building a website in django that will allow players to be matched with other players. I have the following model:
class Session(models.Model):
# id = AutoField(primary_key=True) added automatically.
sport = models.ForeignKey('Sport', unique=False, blank=False, null=False, on_delete=models.CASCADE, )
hostplayer = models.ForeignKey('Member', unique=False, blank=False, null=False, on_delete=models.CASCADE, related_name='member_host', )
guestplayer = models.ForeignKey('Member', unique=False, blank=True, null=True, on_delete=models.CASCADE, related_name='member_guest', )
date = models.DateField(blank=False, null=False, )
time = models.TimeField(blank=False, null=False, )
city = models.ForeignKey('City', unique=False, blank=False, null=False, on_delete=models.CASCADE, )
location = models.CharField(max_length=64, unique=False, blank=False, null=False, )
price = models.FloatField(unique=False, blank=False, null=False, default=0, )
details = models.TextField(unique=False, blank=True, null=False, )
def __unicode__(self):
return unicode(self.id)
As you can see, both hostplayer and guestplayer are foreign keys of the Member table.
The problem is that when I go into django admin, if I select the hostplayer as jack, I can also select the guestplayer as jack. This is obviously wrong as a player cannot play against himself.
How can I limit the options of guestplayer to not include the hostplayer?
Also, on the models level, is there a way to specify that the value of one attribute must be different from the value of another attribute in the same tuple? An obvious way would be to use forms and validate them but I am curious whether a simpler alternative exists.
earlier this week, I asked this question about having foreign keys in your main model from your subclasses: Django Form With Foreign Key
I used the answer given to make a model and sub-models (code at the end). My question is, I know about admin inlines for foreign keys, but I can't use that since the main model has the foreign key to the subclasses, not the other way around. I want the foreign keys in my main class to be displayed in the admin.
Sorry it that sounds confusing, here's my model:
Subclass 1 PreObservation
class PreObservation( models.Model ):
pre_observation = models.CharField(
max_length=255,
choices=OBS_STANDARD_TYPES,
verbose_name="Pre-Observation Standard"
)
obs__meter_reading = models.FloatField( blank=True, null=True )
obs_if_other = models.FloatField( blank=True, null=True )
Subclass 2 FieldObservation
class FieldObservation( models.Model ):
site_id = models.CharField( max_length=255, choices=STATION_CHOICES )
site_name = models.CharField( max_length=255 )
stage_reading = models.FloatField( )
specific_conductance = models.FloatField( )
water_temp = models.FloatField( )
Main class Record
class Record( models.Model ):
observers = models.CharField( max_length=255, verbose_name="Name of Observer(s)")
pre_observation_standard_1 = models.ForeignKey(
PreObservation,
related_name="pre_observation_1"
)
pre_observation_standard_2 = models.ForeignKey(
PreObservation,
related_name="pre_observation_2",
blank=True, null=True
)
field_observation_1 = models.ForeignKey(
FieldObservation,
related_name="field_observation_1"
)
field_observation_2 = models.ForeignKey(
FieldObservation,
related_name="field_observation_2",
blank=True, null=True
)
cloud_coverage = models.CharField( max_length=255, choices=CLOUD_COVERAGE )
rain_past_three_days = models.BooleanField( verbose_name="Rain in Past 3 Days" )
snow = models.BooleanField( )
snow_melt = models.FloatField( )
temperature = models.CharField( max_length=255, choices=TEMPERATURE )
wind = models.CharField( max_length=255, choices=WIND )
field_notes = models.TextField( )
teachers_comments = models.TextField( )
user = models.ForeignKey( User )
group_name = models.CharField( max_length=255, blank=True )
You can use
class RecordAdmin(admin.ModelAdmin):
list_display = ('pre_observation__pre_observation_standard_1',
'pre_observation__pre_observation_standard_2', )
admin.site.register(Record, RecordAdmin)