Django access m2m model value in template - python

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)

Related

Django, many to many relationship, how to insert value for all keys in table?

I have 3 models Company, Discount and CompanyDiscountRelation as below:
class Company(models.Model):
name = models.CharField(max_length=150)
def __str__(self):
return self.name
class Discount(models.Model):
name = models.CharField(max_length=150)
discount_value = models.IntegerField()
def __str__(self):
return self.name
class DiscountCompanyRelation(models.Model):
company= models.ForeignKey(Company, on_delete=models.CASCADE)
discount = models.ForeignKey(Discount, on_delete=models.CASCADE)
is_active = models.BooleanField(default=True)
I know how to assign a previously created discount to one company. I do it by DiscountCompanyRelationForm and choose company from form list. But i want to assign discount to all companies by one-click. How to do this? I tried get all ID's by:
Company.objects.values_list('pk', flat=True)
and iterate through them but i don't think that's how it should be done and i have problem to save form by:
form.save()
I tried all day but now I gave up.
Sorry if this is basic knowledge. I've been working with django for a few days.
If I understand the question, you want to choose a subset of companies in the Company table, and apply a particular Discount.
The first can be a ModelMultipleChoiceField, the second a ModelChoiceField. Put these in a form with appropriate querysets for the companies and discount that can be chosen, and when the form validates, apply the discount:
discount = form.cleaned_data['discount']
companies = form.cleaned_data['companies']
for company in companies:
relation = DiscountCompanyRelation(
discount = discount,
company = company,
is_active = # whatever you need
)
relation.save()
You need to think about what happens when a discount is applied to a company which already has a discount. You'll put code in the above loop to check and implement the appropriate action.
I'd strongly recommend specifying a related_name on your ForeignKeys rather than relying on whatever Django generates automagically if you don't.
You might also want to look at the "through" option of a model ManyToManyField, because that's another way to create the same DB structure but brings Django's ManyToMany support code online for you.

How to create a single API which takes data of all Employees

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.

How do I limit a django model's field choices using one of the previous fields?

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.

Django - changing value from db in place and save it to db

I have table on my page like that:
And models.py like that:
models.py
class Book(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=30)
category = models.IntegerField()
offset_pages = models.IntegerField()
read_pages = models.IntegerField()
total_pages = models.IntegerField()
book_path = models.CharField(max_length=200, default='')
status = models.BooleanField(default=False)
def __str__(self):
return f'{self.category} | {self.title} | {self.author}'
I would like to click on value in "Read pages" column (404 in this case) and then modify it and save to database.
The only way I see it for now is to make an html input there with assigned value of 404, then change it within an input and submit it with additional button.
I know how to do so, but it seems to me like there has to be way better solution.
Does any onemay present me another solution?
You can use JavaScript for that. You can define an onclick attribute for the read pages values and when the user clicks it, you can replace the text with an input field whose value attribute should be dynamically set to the value of the text.
The input field can have a small "ok" button next to it, which when pressed have to use an ajax call to update the the database and changing the displayed value without reloading the page.

django admin, displaying all instances of a model1 associated with model2 on model2's change page?

Consider these two models Keyword and Statement (model1 and model2 respectively):
#python_2_unicode_compatible
class Keyword(models.Model):
word = models.CharField(max_length=200)
statement = models.ManyToManyField(Statement)
def __str__(self):
return self.word
#python_2_unicode_compatible
class Statement(models.Model):
statement_id = models.CharField(max_length=200)
title = models.CharField(max_length=200)
issue_date = models.DateField("Issue-Date")
author = models.ForeignKey(Person)
released_by = models.ForeignKey(Organization)
kicpairs = models.ManyToManyField('KeywordInContext')
So on the admin site right now, the only way one would be able to determine what keywords are associated with each statement is that they have to go check the Keyword model in admin, and check each Keyword's display page and scroll through the menu.
At least with regards to the admin site, it's important for someone to be able to see a Statement model's display with all of its associated Keywords visible, and for users to be able to choose additional Keywords within the database (or make new ones). I also hope to be able to have a Statement's keywords modifiable on the admin page via the filter_horizontal widget, since that seems to be the most user friendly.
But I'm having trouble just starting with that. I'm not sure what I need to use or how.

Categories