I am new to django. I have a model like this:
class Standup(models.Model):
team = models.ForeignKey("Team", on_delete=models.CASCADE)
standup_time = models.DateTimeField(auto_now_add=True)
class StandupUpdate(models.Model):
standup = models.ForeignKey("Standup", on_delete=models.CASCADE)
employee = models.ForeignKey("Employee", on_delete=models.CASCADE)
update_time = models.DateTimeField(auto_now_add=True)
status = models.CharField(max_length=50)
work_done_yesterday = models.TextField()
work_to_do = models.TextField()
blockers = models.TextField()
If I write view for this model, every employee will have to hit API for his/her standup update. But I am supposed create a single API which takes updates of all the employees and saves it into database. In frontend, it will be something like this:
Employee will select on a team as one employee can be a part of
multiple teams.
Then the employee will give his/her stadup updates.
Then another employee will do the same thing and so on.
At the end,by clicking on submit button, whole data will be saved together.
Any guidance on how to do it?
Not sure why you need a separate model for Updates.
I would try to approach it like that:
make the Standup model reference both Team and Employee models;
last_update, status, work_to_do etc. as its fields;
make a custom serializer that accepts a list with Standup field values and takes the authorized user's ID from request object's data. last_update time can be now(), status calculated according to your business logic
This part of DRF documentation could probably be helpful.
Related
The following is in my models.py:
class SensorType(models.Model):
hardware_type = models.CharField(max_length=100)
is_static = models.BooleanField(default=False)
# Some other fields
class Sensor(models.Model):
device_id = models.CharField(max_length=100, primary_key=True)
sensor_type = models.ForeignKey(SensorType, on_delete=models.PROTECT)
# Some other fields
class Asset(models.Model):
name = models.CharField(max_length=100)
sensor_type = models.ForeignKey(SensorType, on_delete=models.PROTECT) # I need to use this field to filter below
sensor = models.ForeignKey(Sensor, on_delete=models.PROTECT, limit_choices_to={'sensor_type': WHAT DO I PUT HERE?},)
# Some other fields
I need to limit the choices in the sensor field of asset so that only sensors with the sensor_type set in the field immediately above, show up.
The reasoning behind this is that there will eventually be many sensors and it would be very useful to filter this. Initially I only need this to work from the admin page but this will eventually extend when I make my Create and Update Views.
Is this even possible? I'm essentially trying to access attributes before the object has actually been created.
After reading several other questions such as this one I have also looked into ModelChoiceField but the same issue exists of trying to access the form data before it has been submitted.
I'm very open to changing the model structure if that is what is required.
Similar to this: User defined fields model in django
I am creating a COVID Prescreening system for a school project. Event creators will be able to create forms, which consist of basic questions such as temperature, contact with covid in the last 14 days, etc. as well as provide custom questions for the attendee to answer which I cannot predict.
For example, the event creator could ask 2 questions:
How are you feeling today?
Have you been to a party in the last week?
And every attendee for that event would have to fill out these 2 questions in addition to the standard questions.
The model for this is:
class Event(models.Model):
''' model for an event '''
creator = models.ForeignKey("Account", on_delete=models.CASCADE)
title = models.CharField(max_length=200, help_text="Enter a title for this event")
start_time = models.DateTimeField()
uuid = models.UUIDField(primary_key=True, default=uuid.uuid4)
custom_questions = models.ManyToManyField(CustomQuestion)
def __str__(self):
return f'{self.title} {self.uuid}'
Each custom question is essentially a key/value model:
class CustomQuestion(models.Model):
question = models.CharField(max_length=200)
response = models.CharField(max_length=200, blank=True)
The user will fill out the COVID Form, which will create an object as such:
class CovidScreenData(models.Model):
custom_responses = models.ManyToManyField(CustomQuestion)
temperature = models.DecimalField(max_digits=5, decimal_places=2, default=98.6)
contact_with_covid = models.BooleanField(default=False)
This data is embedded in the larger response, which ties everything together
class Response(models.Model):
''' model for a completed covid screen '''
account = models.ForeignKey('Account', on_delete=models.SET_NULL, null=True)
time = models.DateTimeField()
event = models.ForeignKey('Event', on_delete=models.CASCADE)
details = models.ForeignKey('CovidScreenData', on_delete=models.CASCADE)
def __str__(self):
return f'{self.account.user.username}\'s Response ({self.event.title})'
When the attendee is filling out the form, I want them to be given the custom_questions for the event they are filling out.
My idea is that when they are presented with the form, each question in custom_questions will be looped through and displayed. When the user submits, their response, as well as the original question, are saved in the custom_responses variable.
What is the correct organization to do this? I am asking this rather than how do I display the questions to the user and save their responses in the model.
If you want to save the response correspond to the question I think you can not use ManytoMany field on this part
class Event(models.Model):
...
custom_questions = models.ManyToManyField(CustomQuestion)
...
you should use ManytoOne for Event relationship with CustomQuestion (adding foreign key to Event on CustomQuestion). It's because you store the answer on the same row with the question so other event should not use the same row of CustomQuestion(containing question and answer).
also you can't store a ManytoMany in the CovidScreenData about the custom_response that actually contains CustomQuestion because the reason on my first explanation.
If you want to get and store the answer just go through the Response item, then get the Event item, and then get pairs of question-answer using foreign key on CustomQuestion join with the Event item.
I have a live web-based chat app made in Django. Users can form groups where other users can congregate, leave messages (called replies) and photos. The url every user visits to access a group is:
url(r'^group/(?P<pk>\d+)/reply/$', auth(GroupView.as_view()), name="group_reply"),
where pk is group.pk.
My question is: how can I get a list (or set) of all distinct users who accessed a certain group's URL in the last 5 mins? Essentially, I'm trying to calculate the number of unique recent visitors for each group. I can't seem to wrap my head around how to do this, though I guess sessions information could help? (I'm using django user_sessions in this project, which
"makes session objects a first class citizen like other ORM objects"
).
In case required, the model behind a group is:
class Group(models.Model):
topic = models.TextField(validators=[MaxLengthValidator(200)], null=True)
rules = models.TextField(validators=[MaxLengthValidator(500)], null=True)
owner = models.ForeignKey(User)
private = models.CharField(max_length=50, default=0)
category = models.CharField(choices=TYPE, default=1, max_length=25)
created_at = models.DateTimeField(auto_now_add=True)
And the model behind posting a reply in each group is:
class Reply(models.Model):
text = models.TextField(validators=[MaxLengthValidator(500)])
which_group = models.ForeignKey(Group)
writer = models.ForeignKey(User)
submitted_on = models.DateTimeField(auto_now_add=True)
image = models.ImageField(upload_to=upload_pic_to_location, null=True, blank=True )
And User is a vanilla django.contrib.auth user.
You don't have anything that is collecting the data you need. If you want to record visits to a page, you will need to build a model to do that; a simple one with FKs to User (for the visitor) and Group (for the group being visited), plus a timestamp, should be enough. Then your GroupView can make an entry in that table every time a user visits.
from django.contrib.auth.models import User
from django.db import models
class Team(models.Model):
team_name = models.CharField(max_length=255, unique=True) ## they can create a new team here
description = models.TextField()
slug = models.SlugField(unique=True)
user = models.OneToOneField(User, blank=True, null=True) ## I connect my User here, so they can "own" this info...
Users have the option to create a new team (via the 'team_name' field), but I also want to give users the option to join another team (created by a different user), can I just add a new field to my Team model? And preferably, on the form, they could see a list of created teams, check the one they want to join and save the form.
Could I add something like this to my Team class:
team = forms.ModelMultipleChoiceField(queryset=Team.objects.all()).filter('team_name')
or maybe something like:
TEAM_CHOICES = Team.objects.all()).filter('team_name')
team = forms.CharField(widget=forms.Select(choices=TEAM_CHOICES))
And, how would that data be saved correctly?
If you wanted to allow users to join a team, I'd have a team attribute on the user model that was a FK to the Team.
Then in a form, you could define the list of available teams as you've suggested;
team = forms.ModelMultipleChoiceField(queryset=Team.objects.all())
And I'd also suggest looking at Select2 which creates a javascript 'search' type field that will filter the teams when someone starts to type characters.
Furthermore, the user field in your Team model would be better named as creator or owner so that you don't confuse them with a standard user associated with the team.
So I want to make habit tracking web page, I have 3 models (habits are called category)
class Day(models.Model):
name = models.CharField(max_length=8)
date = models.DateField()
class Category(models.Model):
name = models.CharField(max_length=100)
categoryBD = models.ManyToManyField(Day, through='CategoryByDay')
class CategoryByDay(models.Model):
day = models.ForeignKey(Day)
category = models.ForeignKey(Category)
status = models.CharField(max_length=64)
As you can see it's rather simple. To get track of what I did this specific day I connect each category with each new day.
Now I managed to put some neat buttons next to each category and even got jquery magic to make ajax request when each button is clicked and to hide each button and update status. However, when I refresh the page I still get all the buttons.
So I need to check in the template, if the category this day has a created CategoryByDay model, and if the status is set to 0 or 1.
Can I do it throught template syntax?
It would require some strange querying. I pass to my template today's date and list of categories. Maybe I should expand the list of categories to add a status here?
I don't understand why you need a name for your Day class, but anyway all three classes can be done in one simple class:
class Category(models.Model):
name = models.CharField(max_length=100)
date = models.DateField()
status = models.BooleanField()
Next you want to check what have been done at specific date? Simply make a query:
categorybyday = Category.objects.filter(date=your_date)