I have 15 users in my django model and they are displayed on an html page by using the html code:
{% for user in users %}
<h3>{{ user.get_full_name }}</h3>
{% endfor %}
I want for each user to have a different html page. I would like for the name of the user to be a hyperlink and when you click on the link, it will go to the html page of that user's page.
views.py:
def user1(request):
if request.method =='POST':
if form.is_valid():
form.save()
return redirect('user1')
else:
return render(request, 'accounts/user1.html')
def user2(request):
if request.method =='POST':
if form.is_valid():
form.save()
return redirect('user2')
else:
return render(request, 'accounts/user2.html')
models.py:
class User(models.Model):
user = models.OneToOneField("auth.User", on_delete=models.CASCADE)
player_name = models.CharField(max_length=100, default='')
team = models.ForeignKey(Team, on_delete=models.CASCADE)
jersey_number = models.CharField(max_length=100, default='')
position = models.CharField(max_length=100, default='')
height = models.CharField(max_length=100, default='')
weight = models.CharField(max_length=100, default='')
grade = models.CharField(max_length=100, default='')
headshot = models.ImageField(upload_to='profile_image', blank=True)
status = models.CharField(max_length=100, choices=STATUS_CHOICES)
How do I connect each user in the "for users" with their own html page. Since I am not writing out every user manually and adding a tag, I am confused on how to give each user a separate html page using this format. I tried to use this code to give each user a separate profile page.
views.py:
def view_profile(request, pk=None):
if pk:
user = User.objects.get(pk=pk)
else:
user = request.user
args = {'user': user}
return render(request, 'accounts/profile.html', args)
Related
hi am working on a project where user-added the post onto the site and driver check his post and give him offer ( price) to ship their load .when the driver submits the post(price) ....at the admin level the selected post and which driver adds the price is working properly, however when the same user logged in (which added the post earlier)and want to see the price of his post-offer by a particular driver. so how can I show to the front end with filtration of the particular user?
this is my user post model
class Loader_post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="Loader")
pick_up_station = models.CharField(max_length=150)
destination_station = models.CharField(max_length=150)
sender_name = models.CharField(max_length=150)
phone_number = PhoneNumberField(null=False, blank=False, unique=True)
receiver_name = models.CharField(max_length=150)
def __str__(self):
return self.user.username
def get_absolute_url(self):
return reverse("Loader:my_job", kwargs={"pk": self.pk})
here is the price added to the post
class price(models.Model):
my_post = models.ForeignKey(Loader_post, related_name='prices',on_delete=models.CASCADE,
null=True, default='')
user = models.ForeignKey(get_user_model(), on_delete=models.CASCADE, null=True, default='')
driver_price = models.CharField(max_length=150, null=True)
driver_name = models.CharField(max_length=150, null=True)
approved_price = models.BooleanField(default=False)
status = models.BooleanField(default=False)
def get_absolute_url(self):
return reverse("Driver:Driverview")
def __str__(self):
return self.driver_price
this is the view of the user post(views.py)
class Loader_post_view(CreateView, LoginRequiredMixin):
form_class = forms.Loader_post_form
model = Loader_post
template_name = "post_detail.html"
success_url = reverse_lazy("Loader:my_job")
def form_valid(self, form):
print(form.cleaned_data)
self.object = form.save(commit=False)
self.object.user = self.request.user
self.object.save()
return super().form_valid(form)
and this is the view of added price o particular post
#login_required
def add_price_to_post(request, pk):
post = get_object_or_404(Loader_post, pk=pk)
user = request.user
if request.method == "POST":
form = price_form(request.POST)
if form.is_valid():
ps = form.save(commit=False)
ps.user = request.user
ps.status = True
ps.save()
ps.my_post.add(post)
return redirect('Driver:Driverview')
else:
form = price_form()
return render(request, 'price_form.html', {'form': form})
now how can I show at the front-end of particular logged in user-added price to the post
hi am working on a project where am using multiple user data
a user did a post onto the site and when driver see that post he adds their offer to that post but when driver submit the post ...at the admin level the particular is selected automatically but the post is not selected on which he adds price
this is my post model.py
class Loader_post(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE ,related_name="Loader")
pick_up_station = models.CharField(max_length=150)
destination_station = models.CharField(max_length=150)
sender_name = models.CharField(max_length=150)
phone_number = PhoneNumberField(null=False, blank=False, unique=True)
receiver_name = models.CharField(max_length=150)
this is my second model of adding price to a particular post
class price(models.Model):
my_post = models.ManyToManyField(Loader_post, related_name='prices')
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, default='')
driver_price = models.CharField(max_length=150, null=True)
driver_name = models.CharField(max_length=150, null=True)
approved_price = models.BooleanField(default=False)
status = models.BooleanField(default=False)
this is my adding price to the post views.py
#login_required
def add_price_to_post(request, pk):
post = get_object_or_404(Loader_post, pk=pk)
user = request.user
if request.method == "POST":
form = price_form(request.POST)
if form.is_valid():
ps = form.save(commit=False)
ps.user = request.user
ps.status = True
ps.post = post
ps.save()
return redirect('Driver:Driverview')
else:
form = price_form()
return render(request, 'price_form.html', {'form': form})
this is my html add post button
{% for loader in Loader %}
this is loop
and this is button
add price
It is a ManyToMany relation between price and Loader_post model, hence ps.post = post won't work. You need to use add() method to add new post. Like this:
ps.save()
ps.my_post.add(post)
I’m learning Django, but it’s hanging on such a seemingly simple moment. I need to check and allow the user to edit only his posts, and if he clicks the link for editing someone else’s - render a specific page.
I can not form a condition for user verification, please help:
views.py
#login_required
def blogs_edit_text_post(request, post_id):
post_form = PostForm(instance=TextPost.objects.get(id=post_id))
owner = TextPost.objects.get(pk=1)
if request.user == owner:
if request.method == "POST":
post_form = PostForm(request.POST, instance=TextPost.objects.get(id=post_id))
if post_form.is_valid():
post = post_form.save()
return redirect(blogs_blog)
return render(request, 'blogs/edit_text_post.html', {
'post_form': post_form
})
else:
return render(request, 'blogs/error_page.html', {})
models.py
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE, related_name='profile_user_id')
blog_title = models.CharField(max_length=300, verbose_name='Название блога')
blog_description = models.TextField(max_length=500, verbose_name='Пара слов о себе', blank=True)
profile_pic = models.ImageField(default='nophoto.jpg', upload_to='user_pics/', blank=True, verbose_name='Аватар')
class TextPost(models.Model):
author = models.ForeignKey(Profile, on_delete=models.CASCADE)
title = models.CharField(max_length=300, verbose_name='Заголовок')
post = models.TextField(max_length=500, verbose_name='Текст поста', blank=False)
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
urls.py
path('blogs/blog/', views.blogs_blog, name='blogs-blog')
Please note these points:
Don't relate TextPost to Profile model, relate it directly to the User model. It will be more easy for your project.
Always use "related_name" in OneToOneField or ForeignKeyField.
Always use context (or another named variable) to pass variable in template. in big projects, you will have to pass many variables.
models.py
class TextPost(models.Model):
author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user_name') # User, not Profiel, related_name added
title = models.CharField(max_length=300, verbose_name='Заголовок')
post = models.TextField(max_length=500, verbose_name='Текст поста', blank=False)
created_date = models.DateTimeField(default=timezone.now)
published_date = models.DateTimeField(blank=True, null=True)
views.py
#login_required
def blogs_edit_text_post(request, post_id):
post = TextPost.objects.get(id=post_id)
if post.author == request.user: # post.author.user == request.user if it's related to Profile
if request.method == "POST":
post_form = PostForm(request.POST, instance=TextPost.objects.get(id=post_id))
if post_form.is_valid():
post = post_form.save()
return redirect(blogs_blog)
else:
post_form = PostForm(instance=TextPost.objects.get(id=post_id))
context = {
'post_form': post_form
}
return render(request, 'blogs/edit_text_post.html', context)
else:
return render(request, 'blogs/error_page.html', {})
I have a form field in Django called Label. My problem is that the field shows the Labels of all users while I only want to show self created labels.
models
class Label(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
tag = models.CharField(max_length=25)
def __str__(self):
return self.tag
class Birthday(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
name = models.CharField(max_length=25, default="")
day = models.DateField()
label = models.ForeignKey(Label, on_delete=models.SET_NULL, default=0, null=True, blank=True)
def __str__(self):
return self.name
forms
class BirthdayForm(forms.ModelForm):
class Meta:
model = Birthday
fields = ('name', 'day', 'label')
class LabelForm(forms.ModelForm):
class Meta:
model = Label
fields = ('tag',)
template
<form method="POST">{% csrf_token %}
<table border="0">
{{ form }}
</table>
<button class="submitButton" type="submit">Submit</button>
</form>
This is the view for this template
view
#login_required
def index(request):
if request.method == "POST":
form = BirthdayForm(request.POST)
if form.is_valid():
birthday = form.save(commit=False)
birthday.user = request.user
birthday.save()
return redirect('index')
else:
#default_labels("Friend", request)
#default_labels("Family", request)
form = BirthdayForm()
birthday = Birthday.objects.filter(user=request.user)
username = request.user
return render(request, 'bd_calendar/index.html', {'form': form, 'birthday': birthday, 'username': username })
My app is project management tool where users can add, edit, and view Projects. Projects have titles, summaries, and authors (users). Users have ManyToMany relationships with Projects.
Adding new Projects was working fine until I added an edit project view. I can still create a new Project or edit an existing one, and the new title and summary get saved to the database, but the selected authors do not get saved. Note that I can still go into the shell and add authors to a project manually.
Here are the Project and User models:
class MyUser(AbstractBaseUser):
id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False)
bank_id = models.CharField("researcher's four-letter bank id", null=True, max_length=4, unique=True)
#division = models.CharField(max_length=30, blank = True)
department = models.CharField(max_length=3, choices=DEPARTMENTS)
job_title = models.CharField("job title", max_length=30, choices=JOB_TITLES)
citations = models.IntegerField(null=True, blank=True)
institution = models.CharField(max_length=30, choices=DEPARTMENTS, blank=True)
created_on = models.DateTimeField(auto_now_add=True)
updated_on = models.DateTimeField(auto_now=True)
#history = HistoricalRecords()
REQUIRED_FIELDS = ['email']
USERNAME_FIELD = 'username'
class Project(models.Model):
title = models.TextField('Title')
summary = models.TextField('Summary', default=DEFAULT_TEXT)
authors = models.ManyToManyField(MyUser)
internal_status = models.CharField('Internal Status', max_length = 20, choices = INTERNAL_STATUS,
default='wip')
external_status = models.CharField('External Status', max_length = 20, choices = EXTERNAL_STATUS,
blank=True)
mtp_goal = models.CharField(max_length = 50, choices = MTP_GOALS,
blank=True)
topics = ArrayField(models.CharField('Topics', max_length=30), size=4, null=True)
created_on = models.DateTimeField(auto_now_add=True, null=True)
updated_on = models.DateTimeField(auto_now=True, null=True)
history = HistoricalRecords()
views.py
def add_new(request):
if request.method == 'POST':
form = ProjectForm(request.POST)
if form.is_valid():
project = form.save(commit=False)
project.created_on = timezone.now()
project.save()
return redirect('project_profile', pk=project.pk)
else:
form = ProjectForm()
return render(request, 'add_new.html', {'form': form})
def edit_project(request, pk):
project = get_object_or_404(Project, pk=pk)
if request.method == 'POST':
form = ProjectForm(request.POST, instance=project)
if form.is_valid():
project = form.save(commit=False)
project.updated_on = timezone.now()
project.save()
return redirect('project_profile', pk=project.pk)
else:
form = ProjectForm(instance=project)
return render(request, 'edit_project.html', {'form': form})
forms.py:
from django import forms
from .models import Project, MyUser
class ProjectForm(forms.ModelForm):
class Meta:
model = Project
fields = ('title', 'authors', 'summary')
And finally, the add_project.html page (please excuse the horrific html):
<html>
<head>
<title>ResearchTracker</title>
</head>
<body>
<div>
<nav>
About us
Login
Admin
</nav>
</div>
<h1>New project</h1><br>
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Save</button>
</form>
Go home
</body>
</html>
Since you use commit=False in save, you need to explicitly call save_m2m to save the many to many fields.
From the documentation:
Calling save_m2m() is only required if you use save(commit=False).
When you use a simple save() on a form, all data – including
many-to-many data – is saved without the need for any additional
method calls. For example:
You would do
project.save()
project.save_m2m()