how to know when an activity date has passed - django - python

so i'm still on my todo list and i want to know when an activity has passed so as to flag it as expired.
my views.py
def progress(request):
activities = ToDo.objects.all()
today = timezone.localtime(timezone.now())
context = {
'activities' : activities,
'today' : today,
}
return render(request, 'percent.html', context)
in my templates i have it as:
{% for activity in activities %}
{% if activity.end.date < today.date %}
{{activity}} <br>
{% endif %}
{% endfor %}
i'm going to add my models.py for referencing
class ToDo(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
todo = models.CharField(max_length=50)
description = models.TextField(max_length=200, blank=True)
created = models.DateField(auto_now=True)
end = models.DateField()
start = models.DateField()
completed = models.BooleanField(default=False)
def __str__(self):
return f'{self.owner} - {self.todo}'
or would it be easier to add an expired boolean field to my models? i'm so confused

Note: You need to use Celery Beat as a scheduler.
import datetime
def expired_activity():
today = datetime.date.today()
expired_activity = ToDo.objects.filter(end=today)
if expired_activity:
expired_activity.update(completed=True)

If you don't want to use any scheduler, you can get expired items in another request, using ORM Manager:
from django.db import models
class ToDoManager(models.Manager):
def active(self):
return self.excude(end__lt=today().date)
def expired(self):
return self.filter(end__lt=today().date)
class ToDo(models.Model):
owner = models.ForeignKey(User, on_delete=models.CASCADE)
todo = models.CharField(max_length=50)
description = models.TextField(max_length=200, blank=True)
created = models.DateField(auto_now=True)
end = models.DateField()
start = models.DateField()
completed = models.BooleanField(default=False)
objects = ToDoManager()
def __str__(self):
return f'{self.owner} - {self.todo}'
And in your view you'll get them in a different requests:
ToDo.objects.active()
ToDo.objects.expired()
Or you can change manager with setting expired flag and saving results when requesting data from db

Related

how to show my post only to my friends in django

I want to show my post only to my friends, How can I filter my post only to my friends? I have tried to filter in html code but as my friends get more, it repeats my post more (I mean repeat one post few times )
My models.py
class PostUser(models.Model):
posttype = models.CharField(max_length=3000, default='postuser')
content = models.TextField(null = True, blank= True)
media_image = models.FileField(null = True, blank= True)
media_video = models.FileField(null = True, blank= True)
per_to = models.CharField(max_length=300, null=True, blank=True, default='everyone')
status = models.CharField(max_length=3000, default='active')
date = models.DateField(auto_now_add=True)
time = models.TimeField(auto_now_add=True)
datetime = models.DateTimeField(auto_now_add=True)
like = models.IntegerField(null=True, blank=True)
comment = models.IntegerField(null=True, blank=True)
share = models.IntegerField(null=True, blank=True)
user_pk = models.IntegerField()
class Friends(models.Model):
# Sender
friend_one = models.IntegerField()
# Reciver
friend_two = models.IntegerField()
per_to = models.CharField(max_length=300, null=True, blank=True, default='everyone')
status = models.CharField(max_length=3000, default='active')
datetime = models.DateTimeField(auto_now_add=True)
date = models.DateField(auto_now_add=True)
time = models.TimeField(auto_now_add=True)
and this is my views.py
allmyfriends = Friends.objects.filter(Q(friend_one = request.user.pk) | Q(friend_two = request.user.pk))
You can do it like :-
models.py
Choices = (
(True,'Friends can see Post'),
(False,'Friends cannot see Post'),
)
class Friends(models.Model):
...................
only_friends = models.BooleanField(max_length=30,choices=Choices,default=True)
Accessing Friends model objects in views Because our BooleanField is in Friends model so we have to access Friends model first to access only_friends BooleanField
def some_view(request,user_id):
allmyfriends = get_object_or_404(Friends,user_user_id)
p = request.user
you = p.user
friends = p.friends.all()
context = {'allmyfriends':allmyfriends,'friends':friends}
return render(request, 'mains:your_template.html', context}
urls.py
path('some_view/<int:user_id>/',views.some_view,name='some_view'),
your_template.html
Now do work carefully here.
In showing post, I assume that you're using loop for showing all of users Post. like :-
{% for posts in post %}
{% if posts.user.only_friends == True and posts.user in request.user.friends.all %}
{{ post.posttype }}
{% endif %}
{% endfor %}
Note :- This FrontEnd will only work after you set your PostUser ForeignKey relationship with User like :-
from django.contrib.auth.models import User
class PostUser(models.Model):
..................
user = models.ForeignKey(User,on_delete=models.CASCADE,default='',unique=True)
Also Set your Friends model ForeignKey RelationShip with User
class Friends(models.Model):
.............
user = models.ForeignKey(User,on_delete=models.CASCADE,default='',unique=True)
Explanation :-
In models.py :- I add a BooleanField with Choices.
In views.py :- I access Friends model to access its objects with user_id. ( Check carefully in template urls while using user_id )
In template :- I use a for loop to show all the Posts. AND In for loop i started if statement that If the user who posted a post is in request.user's friends and have BooleanField True then Post will show and if request.user isnot in posted user then the post will not be shown.
#Ramin Zamani- Your friend model is messed up. Have a look at this.
Rename your model Friends to UserFriend. It's a model that shows the relation between 2 entities - The user and his/her friends/followers. The model name shouldn't be plural.
from django.conf import settings
class UserFriend(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL)
friend = models.ForeignKey(settings.AUTH_USER_MODEL)
................
Also, I could have used a many-to-many relation but I prefer the foreign key relation. It's up to your preference.
Your post model needs to be fixed
class Post(models.Model):
created_by= models.ForeignKey(settings.AUTH_USER_MODEL)
...............
And if you want only specific users to let's say view a post then you can do the following.
in your views.py
post = Post.objects.get(slug=self.kwargs.get('name'))
#to check if the user trying to access the post is a friend of the postcreator user.
friend = UserFriend.objects.get(user=post.created_by,friend=self.request.user)
if friend:
render()
else:
return HttpResponseForbidden()

How to compare DateTime in django template in Oneweek

I'm trying to use different stylesheet in django template if the time since publish is less than 7 days.
but Its not works.
please help me to make code works
model.py
class Post(models.Model):
author = models.ForeignKey(Author, on_delete=models.CASCADE)
title = models.CharField(max_length=100)
overview = models.TextField()
created = models.DateTimeField(default=timezone.now)
updated = models.DateTimeField(auto_now=True))
class Meta:
ordering = ('-created',)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('post-detail',kwargs={
'id':self.id
})
#property
def less_than_week(self):
if self.created.datetime.date + datetime.timedelta(days=7) <= datetime.date.today():
return False
else:
return True
template.html
{% if post.created.date.less_than_week %}
<h1>sample test</h1>
{% endif %}

i have issues with while rendering dynamic data for templates

Code below models
class Events(models.Model):
event_author=models.ManyToManyField(Author)
event_title=models.CharField(max_length=300)
event_title_image = models.ImageField(upload_to='images/', blank=True, null=False)
event_description=models.TextField(blank = True)
event_image_description = models.ImageField(upload_to='images/', blank=True, null=True)
event_release_date = models.DateField(null="false")
def __str__(self):
return self.event_title
def publish(self):
self.event_release_date = timezone.now()
self.save()
views
def Event(request):
events=Events.objects.filter(published_date__lte=timezone.now()).order_by('event_title')
return render(request, 'polls/events.html', {})
templates
<p>Events page </p>
{{ events }}
Error
FieldError at /events
Cannot resolve keyword 'published_date' into field. Choices are: event_author, event_description, event_image_description, event_release_date, event_title, event_title_image, id
while I am running a server I got an error like filed error please help out of this i am new django.
That's because you're filtering on a field which not included on your model.
events=Events.objects.filter(published_date__lte=timezone.now()).order_by('event_title')
as I can see, your published_date is correspond to field event_release_date on your model, so it supposed to be like this:
events=Events.objects.filter(event_release_date__lte=timezone.now()).order_by('event_title')

Django fields in form

I am a beginner in Django, hence this might be a simple issue. But I'm not able to get past this successfully.
This is my models.py
class Category(models.Model):
name = models.CharField(max_length=128)
abbr = models.CharField(max_length=5)
def __unicode__(self):
return self.name
class Fabric(models.Model):
name = models.CharField(max_length=128)
abbr = models.CharField(max_length=5)
def __unicode__(self):
return self.name
class Manufacturer(models.Model):
name = models.CharField(max_length=128)
location = models.CharField(max_length=128)
name_abbr = models.CharField(max_length=5, default=None)
loc_abbr = models.CharField(max_length=5, default=None)
def __unicode__(self):
return self.name
class Images(models.Model):
design_id = models.CharField(max_length=128)
file = models.ImageField(upload_to='images')
cost_price = models.FloatField()
category = models.ForeignKey(Category, on_delete=models.CASCADE)
fabric = models.ForeignKey(Fabric, on_delete=models.CASCADE)
manufacturer = models.ForeignKey(Manufacturer, on_delete=models.CASCADE)
selling_price = models.FloatField()
aliveness = models.IntegerField()
date_added = models.DateTimeField(default=datetime.datetime.now)
set_cat = models.IntegerField()
set_cat_no = models.IntegerField()
set_cat_name = models.CharField(max_length=50, blank=True)
I'm building an apparel management database system which contains cloth designs.
My forms.py is
class ImagesForm(forms.ModelForm):
class Meta:
model = Images
fields = ('file','cost_price','set_cat_no','set_cat_name',)
My views.py
#login_required
def uploadphoto(request):
context = RequestContext(request)
context_dict = {}
if request.method == 'POST':
form = ImagesForm(request.POST,request.FILES)
if form.is_valid():
image = form.save(commit=False)
image.save()
return render_to_response(request,'cms/upload-photo.html', {'upload_image': form})
else:
print form.errors
else:
form = ImagesForm()
context_dict = {'upload_image': form}
return render_to_response('cms/upload-photo.html',context_dict, context)
My upload-photo.html is
{% block main %}
<form id="upload_form" method="post" action="/zoomtail/upload-photo/" enctype="multipart/form-data">
{% csrf_token %}
{{ upload_image }}
</form>
{% endblock %}
The problem here is when I goto /upload-photo/ I don't see the drop-downs to the foreign keys to categories, fabric and manufacturers. I have read that it should be automatically generated but I don't see any.
And selling_price has to be calculated based on the given percentage increase from the cost_price which has to be entered in the form. How do I do this? And aliveness of an apparel has to be set by default as 1. How to do this?
set-cat field of an apparel is 1 if it belongs to a set and 2 if it belongs to a catalogue. How do I get a radio button asking whether set or catalogue and that to be captured as an integer in the database?
And design-id field of an apparel has to be a string which contains abbreviations of category, fabric, manufacturer, etc etc all the fields it belongs to. How do I do this dynamically?
I know, this is a very long question but I'm a newbie and these are literally giving me headache since days. I shall be very thankful to those who answer this.
I believe the issue with the dropdown is that you've excluded the fields from ImageForm. You have:
fields = ('file','cost_price','set_cat_no','set_cat_name',)
but should have:
fields = ('file','cost_price','set_cat_no','set_cat_name', 'category', 'fabric', 'manufacturer,)`
if that doesn't work, are there any options in your database for Categories, Fabric, and Manufacturer? If your tables are empty, the dropdown will be empty. If there are values in the database, is there HTML being generated but the label value is blank (i.e. <option>{this is blank}</option>)? In django, you can override the __str__ function to specify how the dropdown options get labeled
Override __str__ as follows:
class Category(models.Model):
name = models.CharField(max_length=128)
abbr = models.CharField(max_length=5)
def __unicode__(self):
return self.name
def __str__(self):
return self.name
You can compute the value of selling_price and any other computed value in the block if request.method == 'POST'.
Example:
def uploadphoto(request):
context = RequestContext(request)
context_dict = {}
if request.method == 'POST':
form = ImagesForm(request.POST,request.FILES)
#- Calculate value(s) here -#
if form.is_valid():
image = form.save(commit=False)
image.save()`
Please see this post here for using radio buttons
You would do this in the same place as #2 above

Disply the list of users with total posts

How can I display the list of users with the count of total number of posts made by them in a separate HTML page ?
models.py
class Post(models.Model):
author = models.ForeignKey(User.request, on_delete = models.CASCADE)
title = models.CharField(max_length=100)
text = models.TextField()
slug = models.SlugField(unique=True, blank=True, default=uuid.uuid1)
created_date = models.DateTimeField(default=timezone.now)
likes = models.ManyToManyField(User, related_name='post_likes', blank = True)
def get_like_url(self):
return reverse("posts:like-toggle", kwargs={"slug": self.slug})
def get_api_like_url(self):
return reverse("posts:like-api-toggle", kwargs={"slug": self.slug})
def get_absolute_url(self):
return reverse("post_detail",kwargs={'pk':self.pk})
def __str__(self):
return self.title
def count_posts_of(user):
return Post.objects.filter(author=user).count()
You have to learn MVC architecture(MVT in django).
As a beginner first create a sample project to understand this - https://docs.djangoproject.com/en/2.0/intro/tutorial01/
Learn how models.py are written - https://docs.djangoproject.com/en/2.0/topics/db/models/
and how to writeviews.py - https://docs.djangoproject.com/en/2.0/topics/class-based-views/
Then connect them in urls.py - https://docs.djangoproject.com/en/2.0/topics/http/urls/
This is my solution at the moment, but it could be done differently.
First, add count_posts_of method to your User model whatever it is.
For instance I myself created a user model and add this method to it as following:
models.py
class User(models.Model):
name = models.CharField(max_length=100, blank=True, null=True)
#property
def count_posts_of(self):
return self.post_set.all().count()
now in the view pass all the users as context:
views.py
def user_post(request):
context = {'users': User.objects.all()}
return render(request, 'future/user_post_view.html', context)
and finally in the template show the user and their posts' count:
user_post_view.html
{% for user in users %}
{{ user.name }} :
{{ user.count_posts_of }},
{% endfor %}

Categories

Resources