Putting username of logged in user as label in django form field
up vote
0
down vote
favorite
I created simple django blog app where user can login and logout. In this app user can create new posts only when he is logged in. For that i created a form for creating post for authenticated user where he has to put Title , author name and context.
But i want to put username of that logged in user as a label in Author_name field which user cant edit. so i made that field disabled for editing but i couldn't put username of logged in user inside that field as a label.
Need help guys.
My code goes here ....
views.py
from django.shortcuts import render , redirect , get_object_or_404
from .models import Article , members
from django.views.generic import ListView , DetailView , TemplateView
from .forms import create_form
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
class article_view(ListView):
model = Article
template_name = "article.html"
context_object_name = "articles"
@login_required
def post_creator(request):
form = create_form()
if request.method == "POST":
form = create_form(request.POST)
if form.is_valid():
form.save()
return redirect("/blog/home/")
else:
form = create_form()
return render(request , "post_create.html" , {"form":form})
def registration(request):
if request.method == "POST":
form = members(request.POST)
if form.is_valid():
form.save()
return redirect("/blog/home/")
else:
form = members()
return render(request , "register.html" , {"form":form})
class post_detail_view(LoginRequiredMixin , DetailView):
model = Article
template_name = "detail.html"
#class profile(TemplateView):
# model = members
# template_name = "profile.html"
def counts(request):
counts = Article.objects.filter(author=request.user).count()
context = {
"counts":counts
}
return render(request , "profile.html" , context)
forms.py
from django import forms
from datetime import date
from .models import Article
import datetime
from django.contrib.auth.models import User
class create_form(forms.ModelForm):
author = forms.CharField(required=False , widget=forms.TextInput(attrs={'readonly':'True'}))
class Meta:
model = Article
fields = ["title" , "author" , "content"]
models.py
from django.db import models
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class Article(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
date_pub = models.DateTimeField(auto_now=True)
content = models.TextField()
def __str__(self):
return self.title
class members(UserCreationForm):
email = models.EmailField()
class Meta:
model = User
fields = ["username" , "email"]
create_post.html
{% load crispy_forms_tags %}
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Create Post</title>
</head>
</head>
<body style="background-color: darkgrey;">
<div>
<fieldset style="width: 50%;background-color: white;padding: 25px ;margin-left: 350px;margin-top: 15px;border-color: black;">
<form method="POST">
<legend>Create New Post</legend>
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-outline-info" type="submit">Create</button>
</form>
</fieldset>
</div>
</body>
</html>
Hope this helps understand my problem.
django forms label username django-2.1
New contributor
add a comment |
up vote
0
down vote
favorite
I created simple django blog app where user can login and logout. In this app user can create new posts only when he is logged in. For that i created a form for creating post for authenticated user where he has to put Title , author name and context.
But i want to put username of that logged in user as a label in Author_name field which user cant edit. so i made that field disabled for editing but i couldn't put username of logged in user inside that field as a label.
Need help guys.
My code goes here ....
views.py
from django.shortcuts import render , redirect , get_object_or_404
from .models import Article , members
from django.views.generic import ListView , DetailView , TemplateView
from .forms import create_form
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
class article_view(ListView):
model = Article
template_name = "article.html"
context_object_name = "articles"
@login_required
def post_creator(request):
form = create_form()
if request.method == "POST":
form = create_form(request.POST)
if form.is_valid():
form.save()
return redirect("/blog/home/")
else:
form = create_form()
return render(request , "post_create.html" , {"form":form})
def registration(request):
if request.method == "POST":
form = members(request.POST)
if form.is_valid():
form.save()
return redirect("/blog/home/")
else:
form = members()
return render(request , "register.html" , {"form":form})
class post_detail_view(LoginRequiredMixin , DetailView):
model = Article
template_name = "detail.html"
#class profile(TemplateView):
# model = members
# template_name = "profile.html"
def counts(request):
counts = Article.objects.filter(author=request.user).count()
context = {
"counts":counts
}
return render(request , "profile.html" , context)
forms.py
from django import forms
from datetime import date
from .models import Article
import datetime
from django.contrib.auth.models import User
class create_form(forms.ModelForm):
author = forms.CharField(required=False , widget=forms.TextInput(attrs={'readonly':'True'}))
class Meta:
model = Article
fields = ["title" , "author" , "content"]
models.py
from django.db import models
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class Article(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
date_pub = models.DateTimeField(auto_now=True)
content = models.TextField()
def __str__(self):
return self.title
class members(UserCreationForm):
email = models.EmailField()
class Meta:
model = User
fields = ["username" , "email"]
create_post.html
{% load crispy_forms_tags %}
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Create Post</title>
</head>
</head>
<body style="background-color: darkgrey;">
<div>
<fieldset style="width: 50%;background-color: white;padding: 25px ;margin-left: 350px;margin-top: 15px;border-color: black;">
<form method="POST">
<legend>Create New Post</legend>
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-outline-info" type="submit">Create</button>
</form>
</fieldset>
</div>
</body>
</html>
Hope this helps understand my problem.
django forms label username django-2.1
New contributor
add a comment |
up vote
0
down vote
favorite
up vote
0
down vote
favorite
I created simple django blog app where user can login and logout. In this app user can create new posts only when he is logged in. For that i created a form for creating post for authenticated user where he has to put Title , author name and context.
But i want to put username of that logged in user as a label in Author_name field which user cant edit. so i made that field disabled for editing but i couldn't put username of logged in user inside that field as a label.
Need help guys.
My code goes here ....
views.py
from django.shortcuts import render , redirect , get_object_or_404
from .models import Article , members
from django.views.generic import ListView , DetailView , TemplateView
from .forms import create_form
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
class article_view(ListView):
model = Article
template_name = "article.html"
context_object_name = "articles"
@login_required
def post_creator(request):
form = create_form()
if request.method == "POST":
form = create_form(request.POST)
if form.is_valid():
form.save()
return redirect("/blog/home/")
else:
form = create_form()
return render(request , "post_create.html" , {"form":form})
def registration(request):
if request.method == "POST":
form = members(request.POST)
if form.is_valid():
form.save()
return redirect("/blog/home/")
else:
form = members()
return render(request , "register.html" , {"form":form})
class post_detail_view(LoginRequiredMixin , DetailView):
model = Article
template_name = "detail.html"
#class profile(TemplateView):
# model = members
# template_name = "profile.html"
def counts(request):
counts = Article.objects.filter(author=request.user).count()
context = {
"counts":counts
}
return render(request , "profile.html" , context)
forms.py
from django import forms
from datetime import date
from .models import Article
import datetime
from django.contrib.auth.models import User
class create_form(forms.ModelForm):
author = forms.CharField(required=False , widget=forms.TextInput(attrs={'readonly':'True'}))
class Meta:
model = Article
fields = ["title" , "author" , "content"]
models.py
from django.db import models
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class Article(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
date_pub = models.DateTimeField(auto_now=True)
content = models.TextField()
def __str__(self):
return self.title
class members(UserCreationForm):
email = models.EmailField()
class Meta:
model = User
fields = ["username" , "email"]
create_post.html
{% load crispy_forms_tags %}
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Create Post</title>
</head>
</head>
<body style="background-color: darkgrey;">
<div>
<fieldset style="width: 50%;background-color: white;padding: 25px ;margin-left: 350px;margin-top: 15px;border-color: black;">
<form method="POST">
<legend>Create New Post</legend>
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-outline-info" type="submit">Create</button>
</form>
</fieldset>
</div>
</body>
</html>
Hope this helps understand my problem.
django forms label username django-2.1
New contributor
I created simple django blog app where user can login and logout. In this app user can create new posts only when he is logged in. For that i created a form for creating post for authenticated user where he has to put Title , author name and context.
But i want to put username of that logged in user as a label in Author_name field which user cant edit. so i made that field disabled for editing but i couldn't put username of logged in user inside that field as a label.
Need help guys.
My code goes here ....
views.py
from django.shortcuts import render , redirect , get_object_or_404
from .models import Article , members
from django.views.generic import ListView , DetailView , TemplateView
from .forms import create_form
from django.contrib.auth.mixins import LoginRequiredMixin
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
class article_view(ListView):
model = Article
template_name = "article.html"
context_object_name = "articles"
@login_required
def post_creator(request):
form = create_form()
if request.method == "POST":
form = create_form(request.POST)
if form.is_valid():
form.save()
return redirect("/blog/home/")
else:
form = create_form()
return render(request , "post_create.html" , {"form":form})
def registration(request):
if request.method == "POST":
form = members(request.POST)
if form.is_valid():
form.save()
return redirect("/blog/home/")
else:
form = members()
return render(request , "register.html" , {"form":form})
class post_detail_view(LoginRequiredMixin , DetailView):
model = Article
template_name = "detail.html"
#class profile(TemplateView):
# model = members
# template_name = "profile.html"
def counts(request):
counts = Article.objects.filter(author=request.user).count()
context = {
"counts":counts
}
return render(request , "profile.html" , context)
forms.py
from django import forms
from datetime import date
from .models import Article
import datetime
from django.contrib.auth.models import User
class create_form(forms.ModelForm):
author = forms.CharField(required=False , widget=forms.TextInput(attrs={'readonly':'True'}))
class Meta:
model = Article
fields = ["title" , "author" , "content"]
models.py
from django.db import models
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class Article(models.Model):
title = models.CharField(max_length=100)
author = models.CharField(max_length=50)
date_pub = models.DateTimeField(auto_now=True)
content = models.TextField()
def __str__(self):
return self.title
class members(UserCreationForm):
email = models.EmailField()
class Meta:
model = User
fields = ["username" , "email"]
create_post.html
{% load crispy_forms_tags %}
<!DOCTYPE html>
<html>
<head>
<!-- Required meta tags -->
<meta charset="utf-8">
<meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no">
<!-- Bootstrap CSS -->
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous">
<title>Create Post</title>
</head>
</head>
<body style="background-color: darkgrey;">
<div>
<fieldset style="width: 50%;background-color: white;padding: 25px ;margin-left: 350px;margin-top: 15px;border-color: black;">
<form method="POST">
<legend>Create New Post</legend>
{% csrf_token %}
{{ form|crispy }}
<button class="btn btn-outline-info" type="submit">Create</button>
</form>
</fieldset>
</div>
</body>
</html>
Hope this helps understand my problem.
django forms label username django-2.1
django forms label username django-2.1
New contributor
New contributor
New contributor
asked 19 hours ago
Nitin Khandagale
51
51
New contributor
New contributor
add a comment |
add a comment |
1 Answer
1
active
oldest
votes
up vote
0
down vote
accepted
The easiest solution that directly applies to your code, you can do
form = create_form(initial={'author':request.user.username}) #or request.user may work because it returns the username as a string
As a more general solution, that also updates the username in case it changes for any reason, would be to use a ForeignKey
In you models.py
class Article(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
date_pub = models.DateTimeField(auto_now=True)
content = models.TextField()
def __str__(self):
return self.title
In your forms.py do not list it in the fields
list it as one of the fields (keep it as-is).
Then in your views.py, assign it is as follows:
if form.is_valid():
instance=form.save(commit=False)
instance.author=request.user
instance.save()
You change the author
in your example to author_name
, for consistency. The idea here is that you can filter by the user (or any other property of the user, such as age or gender or whatever your model actually contains)
and yes , this worked like charm ! amazing explaination dude. thank you very very much ! god bless
– Nitin Khandagale
17 hours ago
No worries! Welsome to the StackOverflow community :)
– robotHamster
10 hours ago
add a comment |
1 Answer
1
active
oldest
votes
1 Answer
1
active
oldest
votes
active
oldest
votes
active
oldest
votes
up vote
0
down vote
accepted
The easiest solution that directly applies to your code, you can do
form = create_form(initial={'author':request.user.username}) #or request.user may work because it returns the username as a string
As a more general solution, that also updates the username in case it changes for any reason, would be to use a ForeignKey
In you models.py
class Article(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
date_pub = models.DateTimeField(auto_now=True)
content = models.TextField()
def __str__(self):
return self.title
In your forms.py do not list it in the fields
list it as one of the fields (keep it as-is).
Then in your views.py, assign it is as follows:
if form.is_valid():
instance=form.save(commit=False)
instance.author=request.user
instance.save()
You change the author
in your example to author_name
, for consistency. The idea here is that you can filter by the user (or any other property of the user, such as age or gender or whatever your model actually contains)
and yes , this worked like charm ! amazing explaination dude. thank you very very much ! god bless
– Nitin Khandagale
17 hours ago
No worries! Welsome to the StackOverflow community :)
– robotHamster
10 hours ago
add a comment |
up vote
0
down vote
accepted
The easiest solution that directly applies to your code, you can do
form = create_form(initial={'author':request.user.username}) #or request.user may work because it returns the username as a string
As a more general solution, that also updates the username in case it changes for any reason, would be to use a ForeignKey
In you models.py
class Article(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
date_pub = models.DateTimeField(auto_now=True)
content = models.TextField()
def __str__(self):
return self.title
In your forms.py do not list it in the fields
list it as one of the fields (keep it as-is).
Then in your views.py, assign it is as follows:
if form.is_valid():
instance=form.save(commit=False)
instance.author=request.user
instance.save()
You change the author
in your example to author_name
, for consistency. The idea here is that you can filter by the user (or any other property of the user, such as age or gender or whatever your model actually contains)
and yes , this worked like charm ! amazing explaination dude. thank you very very much ! god bless
– Nitin Khandagale
17 hours ago
No worries! Welsome to the StackOverflow community :)
– robotHamster
10 hours ago
add a comment |
up vote
0
down vote
accepted
up vote
0
down vote
accepted
The easiest solution that directly applies to your code, you can do
form = create_form(initial={'author':request.user.username}) #or request.user may work because it returns the username as a string
As a more general solution, that also updates the username in case it changes for any reason, would be to use a ForeignKey
In you models.py
class Article(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
date_pub = models.DateTimeField(auto_now=True)
content = models.TextField()
def __str__(self):
return self.title
In your forms.py do not list it in the fields
list it as one of the fields (keep it as-is).
Then in your views.py, assign it is as follows:
if form.is_valid():
instance=form.save(commit=False)
instance.author=request.user
instance.save()
You change the author
in your example to author_name
, for consistency. The idea here is that you can filter by the user (or any other property of the user, such as age or gender or whatever your model actually contains)
The easiest solution that directly applies to your code, you can do
form = create_form(initial={'author':request.user.username}) #or request.user may work because it returns the username as a string
As a more general solution, that also updates the username in case it changes for any reason, would be to use a ForeignKey
In you models.py
class Article(models.Model):
title = models.CharField(max_length=100)
author = models.ForeignKey(User, null=True, on_delete=models.SET_NULL)
date_pub = models.DateTimeField(auto_now=True)
content = models.TextField()
def __str__(self):
return self.title
In your forms.py do not list it in the fields
list it as one of the fields (keep it as-is).
Then in your views.py, assign it is as follows:
if form.is_valid():
instance=form.save(commit=False)
instance.author=request.user
instance.save()
You change the author
in your example to author_name
, for consistency. The idea here is that you can filter by the user (or any other property of the user, such as age or gender or whatever your model actually contains)
answered 18 hours ago
robotHamster
13011
13011
and yes , this worked like charm ! amazing explaination dude. thank you very very much ! god bless
– Nitin Khandagale
17 hours ago
No worries! Welsome to the StackOverflow community :)
– robotHamster
10 hours ago
add a comment |
and yes , this worked like charm ! amazing explaination dude. thank you very very much ! god bless
– Nitin Khandagale
17 hours ago
No worries! Welsome to the StackOverflow community :)
– robotHamster
10 hours ago
and yes , this worked like charm ! amazing explaination dude. thank you very very much ! god bless
– Nitin Khandagale
17 hours ago
and yes , this worked like charm ! amazing explaination dude. thank you very very much ! god bless
– Nitin Khandagale
17 hours ago
No worries! Welsome to the StackOverflow community :)
– robotHamster
10 hours ago
No worries! Welsome to the StackOverflow community :)
– robotHamster
10 hours ago
add a comment |
Nitin Khandagale is a new contributor. Be nice, and check out our Code of Conduct.
Nitin Khandagale is a new contributor. Be nice, and check out our Code of Conduct.
Nitin Khandagale is a new contributor. Be nice, and check out our Code of Conduct.
Nitin Khandagale is a new contributor. Be nice, and check out our Code of Conduct.
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
StackExchange.ready(
function () {
StackExchange.openid.initPostLogin('.new-post-login', 'https%3a%2f%2fstackoverflow.com%2fquestions%2f53237454%2fputting-username-of-logged-in-user-as-label-in-django-form-field%23new-answer', 'question_page');
}
);
Post as a guest
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Post as a guest
Sign up or log in
StackExchange.ready(function () {
StackExchange.helpers.onClickDraftSave('#login-link');
});
Sign up using Google
Sign up using Facebook
Sign up using Email and Password
Sign up using Google
Sign up using Facebook
Sign up using Email and Password