USERS can Upvote or Downvote Posts/Projects posted by Other Users:
screenshot of 'jammed' active dropdown selection box
THIS CODE DIRECTLY BELOW is the models.py that contains the Project class (model) with the vote_total and vote_ratio fields.
It also contains the Review class (model) which is the basis for the ReviewForm in forms.py (code included later)
class Project(models.Model):
owner = models.ForeignKey(Profile, null=True, blank=True, on_delete=models.CASCADE)
title = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
featured_image = models.ImageField(null=True, blank=True, default="default.jpg")
demo_link = models.CharField(max_length=2000, null=True, blank=True)
source_link = models.CharField(max_length=2000, null=True, blank=True)
tags = models.ManyToManyField('Tag', blank=True)
vote_total = models.IntegerField(default=0, null=True, blank=True)
vote_ratio = models.IntegerField(default=0, null=True, blank=True)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
def __str__(self):
return self.title
class Meta:
# ordering = ['-created']
ordering = ['-vote_ratio', 'vote_total', 'title']
AND here is the Review class (model)
class Review(models.Model):
VOTE_TYPE = (
('up', 'Up Vote'),
('down', 'Down Vote'),
)
owner = models.ForeignKey(Profile, on_delete=models.CASCADE, null=True)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
body = models.TextField(null=True, blank=True)
value = models.CharField(max_length=200, choices=VOTE_TYPE)
created = models.DateTimeField(auto_now_add=True)
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
class Meta:
unique_together = [['owner', 'project']]
def __str__(self):
return self.value
Here is the ReviewForm from the forms.py
class ReviewForm(ModelForm):
class Meta:
model = Review
fields = ['value', 'body']
labels = {
'value': 'Place your vote',
'body': 'Add a comment with your vote'
}
def __init__(self, *args, **kwargs):
super(ReviewForm, self).__init__(*args, **kwargs)
for name, field in self.fields.items():
field.widget.attrs.update({'class': 'input'})
Here is the html template where the form is located
<div class="comments">
<h3 class="singleProject__subtitle">Comments</h3>
<h5 class="project--rating">
{{project.vote_ratio}}% Postitive ({{project.vote_total}} Vote{{project.vote_total|pluralize:"s"}})
</h5>
{% if request.user.profile.id in project.reviewers %}
<p>You have already submitted a comment!</p>
{% elif request.user.profile == project.owner %}
<p>You can't comment your own work!</p>
{% elif request.user.is_authenticated %}
<form class="form" action="{% url 'project' project.id %}" method="POST">
{% csrf_token %}
{% for field in form %}
<div class="form__field">
<label for="formInput#textarea">{{field.label}} </label>
{{field}}
</div>
{% endfor %}
<input class="btn btn--sub btn--lg" type="submit" value="Add Review" />
</form>
{% else %}
Please login to leave a comment
{% endif %}
It was working okay when first implemented and has somehow developed this issue
This is running in venv with Python 3.9.6
Thank you for considering this question !
ADDED - rendered html
rendered html
Related
I want the value of username from forms that I get as a string so that when I upload an image it is stored in a subdirectory with that username.
i.e. if 'bob' registers the image should be saved in 'static/auth_image/bob/image_name.extension'.
Also if I could it during the registration form filling that would be great.
models.py
class User_data(models.Model):
username = models.CharField(max_length=256, null=True, blank=True)
email = models.EmailField(max_length=254, null=True, blank=True)
four_digit_pass = models.CharField(max_length=256, null=True, blank=True)
private_key = models.CharField(max_length=256, null=True, blank=True)
profile_pic = models.ImageField(upload_to='static/profilepic', null=True)
def getUsername(self):
return self.username
def __str__(self):
return str(self.username)
class AuthImages(models.Model):
owner = models.ForeignKey('User_data', null=True, on_delete=models.CASCADE)
uname=owner.
def save_auth_image(self):
uname = self.username
self.auth_image_file = models.ImageField(
upload_to='static/auth_image/%s' % uname, null=True)
forms.py
class RegistrationForm(forms.ModelForm):
four_digit_pass = forms.CharField(widget=forms.PasswordInput())
class Meta:
model = User_data
fields = ['username', 'email', 'four_digit_pass',
'profile_pic', 'private_key']
register.html
{% extends "storage_app/base.html" %}
{% block body_block %}
<div class="jumbotron">
<h1>Register Page</h1>
</div>
<div>
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<p>Private Key should not be changed or shared with anyone</p>
<button type="submit">Upload</button>
</form>
</div>
{% endblock body_block %}
here in HTML, i want to take input for the second i.e. auth_image directly from webcam if possible
This is my first question also I am new to Django so please help me out if there is a cleaner way to write this and please excuse any mistakes.
i am trying to show data from multiple models in one single view and one single template and i succeed with that but i have problem , the problem is posts from android model keep show at first because i have added android first in html page but what i want to do is show posts by date published what should i do
models.py :
class android(models.Model):
name = models.CharField(max_length=50,default="")
slug = models.SlugField(max_length=250,default="")
post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
def get_image(self):
if self.app_image and hasattr(self.app_image, 'url'):
return self.app_image.url
else:
return '/path/to/default/image'
def __str__(self):
return self.name
class Meta:
ordering = ('-post_date',)
class PCgames(models.Model):
name = models.CharField(max_length=50,default="")
slug = models.SlugField(max_length=250,default="")
post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
def get_image(self):
if self.app_image and hasattr(self.app_image, 'url'):
return self.app_image.url
else:
return '/path/to/default/image'
def __str__(self):
return self.name
class Meta:
ordering = ('-post_date',)
views.py :
def home_page(request):
pcgamesforhome = PCgames.objects.all()
androidforhome = Android.objects.all()
context = {'pcgamesforhome' : pcgamesforhome,'androidforhome' : androidforhome}
return render(request,'html_file/home.html',context=context)
home.html :
<div class="container">
<div class='row'>
{% for android in androidforhome %}
<div class='col-xs-12 col-sm-6 col-md-4 website-thumb'>
<a href="{{ android.slug }}">
<img src="{{ android.get_image }}" class='image_control_for_home_page_pc_games' alt=''> </a>
<h3>{{ android.name }}</h3> </div>
{% endfor %}
</div>
<div class="container">
<div class='row'>
{% for home_page in pcgamesforhome %}
<div class='col-xs-12 col-sm-6 col-md-4 website-thumb'>
<a href="{{ home_page.slug }}">
<img src="{{ home_page.get_image }}" class='image_control_for_home_page_pc_games' alt=''> </a>
<h3>{{ home_page.name }}</h3> </div>
{% endfor %}
</div>
so now what should i do to show posts from all models order by date ?
your database structure is wrong. instead of having two model for android and PC, you can have one model and a field specifying object type with choices
class Foo(models.Model):
Type = (
('android', 'android'),
('pc', 'pc'),
)
name = models.CharField(max_length=50,default="")
slug = models.SlugField(max_length=250,default="")
post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
type = models.CharField(max_length=10, choices=Type)
if you like to have a special field for each android or pc, you can create fields with blank and null true attr.
views.py:
# get all of them and order them by creation date
Foo.obejcts.all().order_by('-post_date')
# get android type objects
Foo.objects.filter(type='android')
# get pc type objects
Foo.objects.filter(type='pc')
a basic example would be
class Category(models.Model):
name = models.CharField(max_length=30)
slug = models.SlugField(max_length=50)
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=100)
content = models.TextField(blank=True)
post_date = models.DateTimeField(auto_now_add=True, null=True, blank=True)
slug = models.SlugField(max_length=50)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
def __str__(self):
return self.title
class Meta:
#recent post in top
ordering = ['-post_date']
in views to filter based on category:
pc_games = Post.objects.select_related("category_set").filter(category__name='pc_games')
android = Post.objects.select_related("category_set").filter(category__name='android')
So I use a model which is linked to my custom user (AbstractUser) in Django. I want to loop over all the objects of the current logged in user that belong to him.
So these are the models:
class CustomUser(AbstractUser):
# Define all the fields
company = models.CharField(blank=True, null=True, max_length=150, unique=True)
email = models.EmailField(blank=True, null=True)
username = models.CharField(blank=True, null=True, max_length=150)
first_name = models.CharField(blank=True, null=True, max_length=150)
last_name = models.CharField(blank=True, null=True, max_length=150)
phone_number = models.CharField(max_length=15, blank=True, null=True)
kvk_number = models.IntegerField(blank=True, null=True)
vat_number = models.CharField(blank=True, null=True, max_length=150)
customer_type = models.CharField(max_length=1, choices=CUSTOMER_CHOICES, null=True, blank=True) # Choices are defined before the model
# Username is required here otherwise createsuperuser will throw a error. We define the usernamefield here as the email
REQUIRED_FIELDS = ['username', 'email']
USERNAME_FIELD = 'company'
def __str__(self):
return self.company
class UserLinks(models.Model):
# Define all the fields
user = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True)
name = models.CharField(max_length=2, choices=LINK_CHOICES, null=True, blank=True)
link = models.URLField(blank=True, null=True)
login_name = models.CharField(blank=True, null=True, max_length=150)
password = models.CharField(blank=True, null=True, max_length=150)
def __str__(self):
return self.name
class Meta:
verbose_name = "User link"
verbose_name_plural = "User links"
And this is my view:
def get(self, request):
user = CustomUser.objects.all()
return render(request, self.template_name ,{'user': user})
Then when I want to loop through the objects through the foreingkey I use:
{% for entry in user %}
{{ entry.company }}
{{ entry.first_name }}
{% for a in entry.userlinks_set.all %}
{{ a.name }}
{{ a.link }}
{% endfor %}
{% endfor %}
However now I am displaying all the objects, but I only want to display the objects of the current logged in user, how to do this?
You can access the currently logged-in user at
request.user
although you should consider that if a user is not logged in this will return AnonymousUser. You can prevent this by wrapping your view with a login_required decorator.
You can change your view code in the following way:
def get(self, request):
return render(request, self.template_name ,{'user': request.user})
and your template code should look like
{{ user.company }}
{{ user.first_name }}
{% for a in user.userlinks_set.all %}
{{ a.name }}
{{ a.link }}
{% endfor %}
You can access your logged in user via request in template
{% if not request.user.is_anonymous %}
{{request.user.company}}
{{request.user.first_name}}
{% for link in request.user.userlinks_set.all %}
{{link.name}}
{{link.link}}
{% endfor %}
{% endif %}
I have a case, where on my template view I would like to display list of all objects (Issues) and categories (Sprints). I already applied also another filtering to display Issues that belongs to particular Project.
I've managed so far to display Sprints and within each Sprint I am displaying list of issues. How can I apply additional filtering on issues, that only issues belongs to particular sprint will be displayed?
Final result should be to display list of all issues divided per sprint.
My code below:
#views.py
class ProjectBacklogView(DetailView):
model = Project
template_name = 'project-backlog.html'
context_object_name = 'backlog'
def get_context_data(self, **kwargs):
context = super(ProjectBacklogView, self).get_context_data(**kwargs)
context['project'] = Project.objects.all()
context['issue'] = Issue.objects.all().order_by('sprint')
# context['epic'] = Epic.objects.all()
# context['initiative'] = Initiative.objects.all()
context['sprint'] = Sprint.objects.all()
return context
# template.html
{% extends 'base-project.html' %}
{% block content %}
{% for sprint in backlog.sprint_set.all %}
<h4>{{ sprint.name }}</h4>
<div id="simpleList" class="list-group" style="margin-bottom: 2%;">
{% for issue in backlog.issue_set.all %}
<div class="list-group-item">
<div style="float:left;"><strong>{{ issue.title }}</strong></div>
<div style="float: right;"><i class="fas">{{ issue.remaining_estimate }}</i></div>
<br /><br /><hr style="border-top: dashed 1px;"></hr>
<div style="float: left;"><small>Assignee: <strong>{{ issue.assignee }}</strong></small></div>
<div style="float: right;"><small>Initiative: <strong>{{ issue.initiative }}</strong></small></div><br />
<div style="float: left;"><small>Priority: <strong>{{ issue.priority }}</strong></small></div>
<div style="float: right;"><small>Epic: <strong>{{ issue.epic }}</strong></small></div>
</div>
{% endfor %}
<br />
</div>
{% endfor %}
{% endblock %}
#models.py
class Project(models.Model):
PROJECT_TYPE = (
('SCR', 'Scrum'),
('KAN', 'Kanban'),
)
# slug = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
alias = models.CharField(max_length=8, primary_key=True)
name = models.CharField(max_length=160)
project_type = models.CharField(max_length=10, choices=PROJECT_TYPE, default="SCR")
lead = models.ForeignKey(CustomUser, on_delete=models.CASCADE, null=True, blank=True)
date_created = models.DateTimeField(auto_now_add=True)
# Definicja nazwy modelu w Adminie Django
def __str__(self):
return self.name
def get_absolute_url(self):
return reverse('project-detail', args=[str(self.alias)])
class Sprint(models.Model):
# sprint_type = models.TextField(default='Sprint', editable=False)
name = models.CharField(max_length=32)
goal = models.TextField(null=True, blank=True)
start_date = models.DateField()
end_date = models.DateField()
project = models.ForeignKey(Project, on_delete=models.CASCADE)
def __str__(self):
return self.name
class Issue(models.Model):
ISSUE_PRIORITY = (
('Critical', 'C'),
('High', 'H'),
('Medium', 'M'),
('Low', 'L'),
)
issue_type = models.TextField(default='Issue', editable=False)
issue_id = models.AutoField(primary_key=True)
# slug = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
date_created = models.DateTimeField(auto_now_add=True)
date_updated = models.DateTimeField(auto_now=True)
project = models.ForeignKey(Project, on_delete=models.CASCADE)
title = models.CharField(max_length=128)
description = models.TextField(null=True, blank=True)
initiative = models.ForeignKey(Initiative, on_delete=models.CASCADE, null=True, blank=True)
epic = models.ForeignKey(Epic, null=True, blank=True, on_delete=models.CASCADE)
sprint = models.ForeignKey(Sprint, on_delete=models.CASCADE, null=True, blank=True)
priority = models.CharField(max_length=8, choices=ISSUE_PRIORITY, default='Medium')
assignee = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='assignees', null=True, blank=True) # zczytywane z tabeli userów
author = models.ForeignKey(CustomUser, on_delete=models.CASCADE, related_name='authors') # zczytywane z tabeli userów
remaining_estimate = models.IntegerField(null=True, blank=True, default='0') # w minutach
time_logged = models.IntegerField(default='0') # w minutach
attachment = models.FileField(null=True, blank=True) # To Do - multiple files??
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('issue-detail', args=[str(self.issue_id)])
My issue is I don't know how to apply dynamically filter (based on field sprint) as sprints are listed in for loop
i currently try to display who many posts a category has.
Therefor i created the Post Model and the Category Model (See below):
models.py
# Categorys of Post Model
class Category(models.Model):
title = models.CharField(max_length=255, verbose_name="Title")
class Meta:
verbose_name = "Category"
verbose_name_plural = "Categories"
ordering = ['title']
def __str__(self):
return self.title
#Post Model
class Post(models.Model):
author = models.ForeignKey('auth.User', on_delete=models.CASCADE)
title = models.CharField(max_length=200)
text = models.TextField(max_length=10000)
category = models.ForeignKey(Category, verbose_name="Category", on_delete=models.CASCADE, null=True)
tag = models.CharField(max_length=50, blank=True)
postattachment = fields.FileField(upload_to='postattachment/%Y/%m/%d/', blank=True, null=True)
postcover = fields.ImageField(upload_to='postcover/%Y/%m/%d/', blank=True, null=True, dependencies=[
FileDependency(processor=ImageProcessor(
format='JPEG', scale={'max_width': 300, 'max_height': 300}))
])
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
def publish(self):
self.published_date = timezone.now()
self.save()
def __str__(self):
return self.title
category_list.html
{% extends 'quickblog/base.html' %}
{% block content %}
{% for categories in categories %}
<div>
<h1><u>{{ categories.title }} {{ $NumCountGetHere }}</u></h1>
</div>
{% endfor %}
{% endblock %}
Now i have no idea how to get the related objects counted...?
You can use something like this:
{% for cat in categories %}
<div>
<h1><u>{{ cat.title }} {{ cat.post_set.count }}</u></h1>
</div>
{% endfor %}
The model Post has a Foreignkey field to the model Category. You can access the related Post instances from a given Category instance using the manager category_instance.post_set. Read about it in the docs.
Finally, we use the method .count() on this manager to get the number of related posts for that given category. This way the code ends up looking like {{ cat.post_set.count }}.