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.
Related
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.
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 the Goal Model and every Goal can have one Mastergoal and or multiple Subgoals.
Goals are connected with Links and every Link can have a different weight.
How do I achieve this with Django?
What I've got so far:
class Goal(models.Model):
user = models.ForeignKey(CustomUser, related_name='goals', on_delete=models.CASCADE)
name = models.CharField(max_length=300)
sub_goals = models.ManyToManyField(to='self', through='Link', symmetrical=False, related_name='master_goals')
class Link(models.Model):
master_goal = models.ForeignKey(Goal, on_delete=models.CASCADE, related_name="sub_links")
sub_goal = models.OneToOneField(Goal, on_delete=models.CASCADE, related_name="master_links")
weight = models.PositiveSmallIntegerField(default=1)
I can't just add an ForeignKey Field on Goal to itself, because every Link can have a different weight.
The solution I've got now works, but it feels wrong. I want to be able to access a Goal's Mastergoal like this: goal.master_goal
I have a problem with retrieving data from this ManyToManyField (users) of a model Event:
class Event(models.Model):
name = models.CharField(max_length=26)
description = models.CharField(max_length=200)
date = models.DateField()
user = models.ForeignKey(User)
users = models.ManyToManyField(User, related_name="users", blank=True)
image = models.ImageField(
upload_to='images/',
default='images/default.png'
)
users = models.ManyToManyField creates an additional table "events_event_users", It stores user_id and event_id fields. So I want to output all event information from Event model, where user_id from that additional table is equal to request.user. Please help, how should I do this?
You can do request.user.users.all()
Note, this is unnecessarily confusing because of the related_name you've set, which defines the backwards relation from User to Event. Leave that out, and the code is more comprehensible:
request.user.event_set.all()
(If you must set one, at least call it events, not users.)