I have a problem. I have given some random numbers in admin page as a balance for users and connected it to database. Basically I want it to show for different users different payments. But I don't know what to write in views.py and html page so that it shows different payment for different users.
models.py
class Payment(models.Model):
payment_numbers = models.CharField(max_length=100)
views.py
def payment(request):
receiving1 = Payment.objects.all()
for field in receiving1:
field.payment_numbers
context = {
'receiving1': receiving1
}
return render(request, 'index.html', context)
HTML PAGE
{% for numbers1 in receiving1 %}
<li style="float: right;">Your Balance: Rs. {{numbers1.payment_numbers}}</li>
{% endfor %}
You need to modify your models so that payments have a relationship with your users.
A simple way to do that is a ForeignKey to your user model.
class Payment(models.Model):
payment_numbers = models.CharField(max_length=100)
owner = models.ForeignKey('yourusermodel')
Once this is done, you can update your views to pass only the right payments to the context.
receiving1 = Payment.objects.filter(owner=request.user)
This will of course require you to create new migrations and to ensure your users are properly logged in. Most of this is explained in the Django Tutorial
Related
I am building a website where user come and login, after login user publish articles with admin approval . I do not know how to do it. I made a user authentication system where user can login. But i do not know how to make him post data with admin approval.
Therefor you need a condition in your model to be able to query the approved objects (blog posts) to display.
A basic approach could look as follows:
Create a model to store the blog posts and its logic to the database
# models.py
class Blog_Post(models.Model):
text = models.CharField(max_length=500)
is_approved = models.BooleanField(default=False)
def __str__(self):
return self.name
Register your model in the admin so you can approve them via django-admin
from django.contrib import admin
from myproject.myapp.models import Blog_Post
admin.site.register(Blog_Post)
Create a view to only fetch blog posts that have been approved by an admin
# views.py
def get_blog_post(request):
# Only fetch the blog posts that are approved
queryset = Blog_Post.objects.filter(is_approved=True)
return render(request, 'your_html.html', {'queryset' : queryset})
Render the blog posts in your template
# your_html.html
{% for blog_post in queryset %}
<div>{{ blog_post.text }}</div>
{% endfor %}
That's a Good one. You can enable this with adding a new column to your database like onapproval Set it as an boolean variable like 0 or 1 either true or false. Then check for it. If it's true you can set the status as approved and if it is not set it as not approved. The same process will also takes place in admin panel too.
I am in the process of learning Django. I am trying to create a simple directory web app. I am able to print out all the users details for the main directory page. However, I want to add a feature that when a person logs into the directory app they are brought to their 'profile' page where they will be able to see all their own details e.g. business name, profile pic.
I know how to retrieve the default fields e.g. username and email. But cannot seem to retrieve the custom fields that I declared myself. Here is my attempts so far...
Models.py:
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class UserProfileInfo(models.Model):
user = models.OneToOneField(User,on_delete=models.DO_NOTHING)
#additional classes
business_name = models.CharField(max_length=191,blank=True)
trade = models.CharField(max_length=191,blank=True)
portfolio_site = models.URLField(blank=True)
profile_pic = models.ImageField(upload_to='profile_pics',blank=True)
def __str__(self):
return self.user.username
Views.py:
#login_required
def profile(request):
profile = UserProfileInfo.objects.filter(user=request.user)
context = { 'profile': profile }
return render(request, 'dir_app/profile.html',context)
Profile.html:
<div class="container-fluid text-center">
{% for p in profile %}
<h3>{{p.business_name}}</h3>
{% endfor %}
</div>
Since UserProfileInfo is related to User via OneToOneField, you can have one UserProfileInfo per User. So, instead of Filter, you can simply get your desired UserProfileInfo object through your current (logged in) User as follows.
views.py,
profile = UserProfileInfo.objects.get(user=request.user)
Also, before you can get a request.user object, you have to make sure that your user is authenticated and logged in. Otherwise, you might get None in place of a User object and therefore, no associated UserProfileInfo.
Since it is a OneToOneField there is only one Profile object for a User, you thus can obtain this with:
#login_required
def profile(request):
profile = request.user.userprofileinfo
return render(request, 'my_template.html',{'profile': profile})
Then in the template, you render it with:
{{ profile.business_name }}
you can use it directly on template without sending it f:
{{request.user.userprofile}}
I'm developing to-list app with registration . I have two models : Model for User and Model for Tasks . I add new task throw Ajax to one user it adding and displaying for every user. Is there any solutions ? Here some pictures
Here is my code:
models.py
class Task(models.Model):
title=models.IntegerField()
date = models.DateTimeField(default=datetime.now,blank=True)
is_published=models.BooleanField(default=True)
class CustomUser(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
image=models.FileField(upload_to='photos/%Y/%m/%d/',null=True,blank=True)
views.py
if request.method == 'POST' and request.POST['form_type'] == 'task':
if request.is_ajax():
addtask = AddTask(request.POST)
if addtask.is_valid():
user = request.user.id
addtask.objects.filter(user=user).cleaned_data
addtask.objects.filter(user=user).save()
task_object = Task.objects.filter(user=user)(addtask)
return JsonResponse({'error': False, 'data': task_object})
else:
print(addtask.errors)
return JsonResponse({'error': True, 'data': addtask.errors})
else:
error = {
'message': 'Error, must be an Ajax call.'
}
return JsonResponse(error, content_type="application/json")
addtask = AddTask()
task = Task.objects.order_by('-date').filter(is_published=True)
html page
{% if task %}
{% for tas in task %}
Task content
{% endfor %}
{% else %}
{% endif %}
Maybe you should add relation to CustomUser in Task model and filter tasks by owner in view before to render data to template?
class Task(models.Model):
title=models.IntegerField()
date = models.DateTimeField(default=datetime.now,blank=True)
is_published=models.BooleanField(default=True)
user=models.ForeignKey(CustomUser)
class CustomUser(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
image=models.FileField(upload_to='photos/%Y/%m/%d/',null=True,blank=True)
And in view:
...
addtask = AddTask()
task = Task.objects.filter(is_published=True, user_id=request.user.id).order_by('-date')
So the mistake is that you never connected your CustomUser model with your Task model. They should have a relationship like one to many. Once that is achieved, you have to retrieve only the tasks related to the user of interest from the database and send them to the HTML page. Then only the tasks related to one particular user will be displayed.
If you want to create CustomUser model, you should create a class and inherit it from AbstractBaseUser or AbstractUser(django documentation).
Your Task model hasn't relationships with CustomUser. You create AddTask(?) instance but didn't bind it with any user.
You did not submit a view which renders HTML template, but I think that your query is something like Tasks = Task.objects.all() which return all tasks.
This is how you should create CustomUser model
This is documentation about relationships in Django
This is about making queries in Django
I have a Django project that allows users to create their own Projects and add multiple Skills to each Project.
I am trying to write a view that will allow me to display the name of each Skill as well as the Count of that Skill for all of that particular user Profile's Projects that are published.
For example, if a user has three projects where they've added the Skill "HTML" I'd like to show HTML (3) on their Profile, and so on.
Below is my current code which mostly works however it displays the count for that Skill from ALL user projects and not the specific user whose profile is being viewed.
Models:
#accounts/models.py
class Profile(models.Model):
#...
skills = models.ManyToManyField('skills.skill')
#projects/models.py
class Project(models.Model):
user = models.ForeignKey(User)
#...
published = models.BooleanField(default=False)
skills = models.ManyToManyField('skills.skill')
#...
#skills/models.py
class Skill(models.Model):
name = models.CharField(max_length=100)
Views:
#accounts/views.py
def profile(request, username):
user = get_object_or_404(User, username=username)
skill_counts = Skill.objects.annotate(num_projects=Count('project')).filter(project__user_id=user.id).order_by('-num_projects')[:10]
return render(request, 'accounts/profile.html', {
'user': user,
'skill_counts': skill_counts,
})
Template:
#accounts/templates/accounts/profile.html
{% for skill in skill_counts %}
<div class="skill-container">
<div class="label-skill">{{ skill.name }}</div> <div class="label-skill-count">
{{skill.project_set.count}}</div>
</div>
{% endfor %}
Any help here would be much appreciated.
Thanks in advance.
Note that I'm voting to close this as this question has been answered here.
Basically you need to use django's conditional expressions Case and When.
Here is a quick example of how this could look:
from django.db.models import Count, Case, When
# ...
Skill.objects.annotate(
num_porjects=Count(Case(
When(project__user_id=user.id, then=1),
output_field=CharField(),
))
)
I'm using django's built-in contrib.auth module and have setup a foreign key relationship to a User for when a 'post' is added:
class Post(models.Model):
owner = models.ForeignKey('User')
# ... etc.
Now when it comes to actually adding the Post, I'm not sure what to supply in the owner field before calling save(). I expected something like an id in user's session but I noticed User does not have a user_id or id attribute. What data is it that I should be pulling from the user's authenticated session to populate the owner field with? I've tried to see what's going on in the database table but not too clued up on the sqlite setup yet.
Thanks for any help...
You want to provide a "User" object. I.e. the same kind of thing you'd get from User.objects.get(pk=13).
If you're using the authentication components of Django, the user is also attached to the request object, and you can use it directly from within your view code:
request.user
If the user isn't authenticated, then Django will return an instance of django.contrib.auth.models.AnonymousUser. (per http://docs.djangoproject.com/en/dev/ref/request-response/#attributes)
Requirements --> Django 3, python 3
1) For add username to owner = models.ForeignKey('User') for save that, in the first step you must add from django.conf import settings above models.py and edit owner = models.ForeignKey('User') to this sample:
class Post(models.Model):
slug = models.SlugField(max_length=100, unique=True, null=True, allow_unicode=True)
owner = models.ForeignKey(settings.AUTH_USER_MODEL, default=1, on_delete=models.CASCADE)
2) And for show detail Post, special owner name or family or username under the post, you must add the following code in the second step in views.py:
from django.shortcuts import get_object_or_404
.
.
.
def detailPost(request,slug=None):
instance = get_object_or_404(Post, slug=slug)
context = {
'instance': instance,
}
return render(request, template_name='detail_post.html', context=context)
3) And in the third step, you must add the following code for show user information like user full name that creates a post:
<p class="font-small grey-text">Auther: {{ instance.owner.get_full_name }} </p>
now if you want to use user name, you can use {{ instance.owner.get_username }}
or if you want to access short name, you can use {{ instance.owner.get_short_name }}.
See this link for more information.