I have this Django model:
#encoding:utf-8
from django.db import models
from django.contrib.auth.models import User
from django.contrib import admin
# Create your models here.
class Profile(models.Model):
user = models.ForeignKey(User, unique=True, related_name='user')
follows = models.ManyToManyField(User, related_name='follows', symmetrical=False, blank=True)
bio = models.TextField(blank=True)
avatar = models.ImageField(upload_to='avatar', blank=True)
website = models.CharField(max_length=100, blank=True)
place = models.CharField(max_length=100, blank=True)
def __unicode__(self):
return unicode(self.user)
admin.site.register(Profile)
admin.autodiscover()
Then, I have this view:
def profile(request, user_id):
user = get_object_or_404(Profile, user=user_id)
return render_to_response('user_view.html', {'user':user,})
Now, in user_view.html I display the 'User' data (username, avatar, website, etc):
{{user.user_id}}
{{user.user}}
{{user.website}}
{{user.avatar.url}}
But, also I need to display the username, avatar and website of the users I follow. I did this:
{% for element in user.follows.all %}
{{element.user}}
<img src="{{element.avatar.url}} />
{% endfor %}
But, instead of display the user's data, it shows this:
<django.db.models.fields.related.RelatedManager object at 0x022F34F0>
But if I do this:
{% for element in user.follows.all %}
<p>{{element}}</p>
{% endfor %}
It shows perfectly the user's name, but I still cannot display the website or the avatar. How can I do this?
I think you would try
{% for element in user_data.follows.all %}
<p>{{element.username}}</p>
<p>{{element.profile.website}}</p>
<p>{{element.profile.avatar}}</p>
{% endfor %}
element is an instance of User and not an instance of Profile.
But you can still retrieve the associated Profile instance by writing
element.profile
because it's a One-To-One relationship (OneToOneField or ForeignKey(unique=True))
Related
I have the following Post and Follow models:
class Post(models.Model):
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
date_modified = models.DateTimeField(auto_now=True)
author = models.ForeignKey(User, on_delete=models.CASCADE)
#property
def followers(self):
return self.follow_set.filter(post=self).values_list('user', flat=True)
class Follow(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
post = models.ForeignKey(Post, on_delete=models.CASCADE)
I tried the following code in shell to check for data in .followers property:
>>> from posts.models import Post
>>> x= Post.objects.get(id=22)
>>> x.followers
<QuerySet [1]>
What I ultimately want is to check if the authenticated user is among the followers. I have the following template code:
{% if user in object.followers %}
Unfollow
{% else %}
Follow
{% endif %}
The problem I have is that {% if user in object.followers %} always evaluates to False. P.S.: I always log-in the user id=1 (same as the queryset result from above).
Use
{% if user in object.followers.all %}
Nevermind. I just realized my mistake.
{% if user.id in object.followers %}
When I display a blog post in HTML using a for loop
{% for post in posts %}
<div class="blogpost">
<h3><strong>{{post.title}}</strong></h3>
<img class="thumbnail" src="{{author.imageURL}}">
<h7>{{post.date}} - {{post.author}}</h7>
<br>
<hr>
<br>
{{post.context|linebreaks}}<br><br>
</div>
<br>
{% endfor %}
it works perfectly fine, except the authors profile picture does NOT get displayed.
I get the posts by getting all posts in my views.py from my models.py. The thing is that the profile picture of the user posting the blog isn't stored in the "post" model in the database. It is stored in the "Customers". Everybody should be able to read and post blogs. The admin (me) can later delete unwanted posts.
I have tried making a for loop using an array key:value in JavaScript. That is not very secure, because everybody just gets all users and all profilepictures through the whole database. That might not be a good idea.
This is my models.py
class Customer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, null=True, blank = True)
name = models.CharField(max_length=200, null=True)
email = models.EmailField(max_length=200, null=True)
about = models.CharField(max_length=100, null=True)
image = models.ImageField(null=True, blank=True)
#property
def imageURL(self):
try:
url = self.image.url
except:
url = 'placeholder.png'
return url
def __str__(self):
return self.name
class Post(models.Model):
title = models.CharField(max_length=200, null=True)
context = models.TextField(max_length=250, blank=True,
validators=[MaxLengthValidator(250)])
author = models.CharField(max_length=200, null=True)
from datetime import date
date = models.DateField(("Date"), default=date.today)
views.py
def homepage(request):
if request.user.is_authenticated: # Everybody has to be logged in
posts = Post.objects.all()
authors = Customer.objects.filter()
context = {'posts':posts, 'authors':authors}
return render(request, 'store/homepage.html', context)
That means that I want the user to see the persons profile picture in the corner of the blog post.
First I think you need to link the author in the Post model to a Customer with a foreignkey:
Then you can acces author fields like
{{ post.author.xyz }}
Currently your context contains authors as a queryset:
authors = Customer.objects.filter()
context = {'posts':posts, 'authors':authors}
But in your template you use it as if it were a single Customer:
<img class="thumbnail" src="{{author.imageURL}}">
And be aware of the typo "author" and "authors"
It is unclear what you meant by {{author.imageURL}} as author is QuerySet( that results in collection of authors).
You probably meant the related author to post which would be post.author
Other than that you should pass image URL to template and not ImageField string representation as documented
So it should be something in a line of
{{ post.author.imageURL.url }}
I have 3 models - Project, Team and a CustomUser model. I'm trying to display a list of teams which a user is part of on the user's detail page, and display a list of users who are part of the project team on the project's detail page but I'm at a stand-still.
# project/users/models.py
class CustomUser(AbstractUser):
name = models.CharField(max_length=255)
# Relationship Fields
team = models.ManyToManyField(
'users.Team',
related_name="teams",
)
class Team(models.Model):
# Relationship Fields
project = models.OneToOneField(
'projects.Project',
on_delete=models.CASCADE, related_name="projects",
)
# project/projects/models.py
class Project(models.Model):
name = models.CharField(max_length=255)
project/projects/templates/projects/project_detail.html
{% for user in project.team.user.all %}
{{ user.name }}
{% endfor %}
I've tried variations of the above such as
{% for user in users.teams.projects.all %}
{{ user.name }}
{% endfor %}
but I can't seem to make anything show. I think I'm doing something simple wrong - I've read through the docs for displaying ManyToManyFields but I'm at a loss! Can anybody point me in the right direction?
im not sure but i think related_name are missed used in this situation:
class Team(models.Model):
# Relationship Fields
project = models.OneToOneField(
'projects.Project',
on_delete=models.CASCADE, related_name="projects",
)
this means that in one object of the class Project will have an attribute with the name projects that will be a reference to the teams. I believe you want:
class Team(models.Model):
# Relationship Fields
project = models.OneToOneField(
'projects.Project',
on_delete=models.CASCADE, related_name="team",
)
So you will be able to call project.team.
Changing your code:
# project/users/models.py
class CustomUser(AbstractUser):
name = models.CharField(max_length=255)
# Relationship Fields
team = models.ManyToManyField(
'users.Team',
related_name="customers",
)
class Team(models.Model):
# Relationship Fields
project = models.OneToOneField(
'projects.Project',
on_delete=models.CASCADE, related_name="team",
)
class Project(models.Model):
name = models.CharField(max_length=255)
So in the template now you could:
{% for user in project.team.customers.all %}
{{ user.name }}
{% endfor %}
I have a edit page which you can edit your personal information that you register, such as username, first_name, last_name, email. But inside the page i have some extra field such as description, city, website field that you can add/edit into your profile if you wanted to.But after i edit the personal info and fill in the extra field for testing and press the confirm button, the personal information being edit succesfully and there is no error occur. But the problem is when i check the data at Django admin, the UserExtraField model is empty. I hope my explanation is good enough.
the problem is i cant save the extra field to the user that login, but the personal information edit work fine, just the extra field cannot be save to the person. i want the user able to edit their personal profile and also add/edit the extra field if they want to.when they edit their personal profile, i want to add some field so they can have more information in their profile.
there is a picture link at the below too.Thank you.
views.py file
def UserProfileEdit(request):
if request.method == 'POST':
form_edit = EditForm(request.POST, instance= request.user)
form_extra = UserExtra(request.POST,instance=request.user)
if form_edit.is_valid() and form_extra.is_valid():
edit = form_edit.save()
extra = form_extra.save()
extra.user = edit
return redirect('/userprofile/user')
else:
form_edit = EditForm(instance = request.user)
form_extra = UserExtra(instance = request.user)
user_edit = {'form_edit':form_edit,'form_extra':form_extra}
return render(request,'user_profile/user_edit.html',context=user_edit)
forms.py
class EditForm(UserChangeForm):
class Meta():
model = User
fields = ('username', 'first_name', 'last_name', 'email', "password")
#make another forms for extra profile imformation
class UserExtra(forms.ModelForm):
class Meta():
model = UserExtraProfile
fields = ('description','city','website')
models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.signals import post_save
# Create your models here.
class UserExtraProfile(models.Model):
#inherit the User model pk
user = models.OneToOneField(User, on_delete = models.CASCADE)
description = models.CharField(max_length= 250,default= '')
city = models.CharField(max_length=250,default= '')
website = models.URLField(blank= True,default= '')
# image = models.ImageField(upload_to='media/profile_pic', blank=True)
def __str__(self):
return self.user.username
def create_profile(sender,**kwargs):
if kwargs['created']:
user_profile = UserExtraProfile.objects.create(user=kwargs['instance'])
post_save.connect(create_profile, sender = User)
user_edit.html
{% extends 'base.html'%}
{% load bootstrap3 %}
{% load staticfiles %}
{% block content %}
<div class="container">
<h1>User Profile Edit</h1>
<form method="POST">
{% csrf_token %}
{% bootstrap_form form_edit %}
{% bootstrap_form form_extra %}
<input type="submit" class="btn btn-default" value="Confirm">
</form>
</div>
{% endblock %}
enter image description here
You didn't save the extraprofile after assigning the user. Use commit=False in the form save so you don't hit the db twice.
user = form_edit.save()
extra = form_extra.save(commit=False)
extra.user = user
extra.save()
Also, you need to pass the profile, not the user, to the profile form.
form_extra = UserExtra(request.POST, instance=request.user.userextraprofile)
I am new to Django Python and I am learning how to use Django and passing data from view to template. Now, here is my situation and I really need some help in understanding where i can be doing wrong.
I am trying to pass data from view to template and then parse the object in the view but for some reason nothing is happening in the template. I have printed the registration object in my views.py and it works fine and displays the information that is correct. But when I send the registration object from views to template nothing happens.
models.py
from django.db import models
from datetime import datetime
from django.shortcuts import redirect
# Create your models here.
# Create your models here.
class Registration(models.Model):
first_name = models.CharField(max_length=255, null=True, blank=True)
last_name = models.CharField(max_length=255, null=True, blank=True)
email = models.CharField(max_length=255, null=True, blank=True)
password = models.CharField(max_length=255, null=True, blank=True)
mobilenumber = models.CharField(max_length=255, null=True, blank=True)
created_on = models.DateTimeField(auto_now_add=True, blank=True)
class Meta:
ordering = ('first_name',)
views.py
class Loginview(CreateView):
model = Registration
form_class = LoginForm
template_name = "loginvalentis/valentis_login.html"
def get(self, request):
form = LoginForm()
# returning form
return render(request, 'loginvalentis/valentis_login.html', {'form': form});
def form_valid(self,form):
user_email = form.cleaned_data.get('email')
user_password = form.cleaned_data.get('password')
try:
registration = Registration.objects.get(email=user_email)
print ("registration",registration.mobilenumber)
return redirect('/loginvalentis/home/',{'registration':registration})
except Registration.DoesNotExist:
user_info = None
return redirect('/loginvalentis/login/')
Template result.html --- ('/loginvalentis/home/')
<html>
<body>
<form id="form1">
{% csrf_token %}
<div>
hello world
<form id ="form1">
<ul>
{% for user in registration %}
<li>{{ user.mobilenumber }}</li>
{% endfor %}
</ul>
</form>
</div>
</form>
</body>
</html>
Your problem is with the redirect() function. You are trying to pass the registration object through it, but it doesn't support this, it's *args and **kwargs are simply a parameters for reversing the url, see here:
https://docs.djangoproject.com/en/2.0/topics/http/shortcuts/#django.shortcuts.redirect
You should use some other way to pass it to another view, e.g. pass only it's id as a parameter of that view's url (you will have to change the url conf appropriatelly), the other way is to use sessions etc.
see:
https://docs.djangoproject.com/en/2.0/topics/http/sessions/
https://docs.djangoproject.com/en/2.0/topics/http/urls/
But really, it would be much easier for you just to walk through this tutorial very carefully
https://docs.djangoproject.com/en/2.0/intro/tutorial01/ trust me, it will be really worth your time, because from your question I can easily tell that you just don't understand what you are doing.