I am not able to retrive OneToOneField data from backend Django - python

i can get data from backend from User e.g user.id but when i want to get data from OneToOneField e.g user.checkAdmin.isAdmin its not displaying any data in html page
views.py
def registerView(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
isAdminForm = checkAdminForm(request.POST) #
if form.is_valid() and isAdminForm.is_valid():
user = form.save()
isAdminFormObject = isAdminForm.save(commit=False)
isAdminFormObject.user = user
isAdminFormObject.save()
return redirect('login_url')
else:
form = UserCreationForm()
isAdminForm = checkAdminForm()
return render(request, 'registration/register.html',{'form':form,'isAdminForm':isAdminForm})
Forms.py
from django import forms
from .models import checkAdmin
class checkAdminForm(forms.ModelForm):
class Meta:
model = checkAdmin
fields = ['isAdmin']
models.py
from django.db import models
from django.contrib.auth.models import User
# Create your models here.
class checkAdmin(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
isAdmin = models.BooleanField(default=False)
def __str__(self):
return self.user.username
dashboard.html
{% extends 'index.html' %}
{% block content %}
<h1>Welcome, {{ user.id }}</h1>
<h1>check?,{{ user.checkAdmin.isAdmin }}</h1>
<button>Mark Attendance</button> <button>Mark Leave</button> <button>View Attance</button>
Logout
{% endblock %}

use checkadmin instead of checkAdmin
{% extends 'base.html' %}
{% block content %}
<h1>Welcome, {{ user.id }}</h1>
<h1>check?,{{ user.checkadmin.isAdmin }}</h1>
<button>Mark Attendance</button> <button>Mark Leave</button> <button>View Attance</button>
Logout
{% endblock %}

Related

Django - Form not saving when submitted

Good afternoon all,
One of my form does not seem to save when submitted. I cannot see why, in particular as I have a similar form working just fine using the same code.
For some reason it work just fine using the admin panel.
My assumption is that I am missing something that tells the form it needs to be saved. But cannot find what.
Any ideas?
Models
RATING=(
(1,'1'),
(2,'2'),
(3,'3'),
(4,'4'),
(5,'5'),
)
class ProductReview(models.Model):
user=models.ForeignKey(User, on_delete=models.CASCADE)
product=models.ForeignKey(Product,related_name="comments", on_delete=models.CASCADE)
review_text=models.TextField(max_length=250)
review_rating=models.IntegerField(choices=RATING,max_length=150, default=0)
date_added = models.DateTimeField(auto_now_add=True)
updated_at = models.DateTimeField(auto_now_add=True)
Views
def add_review(request, product_id):
product = Product.objects.get(pk=product_id)
form = ReviewAdd(request.POST or None, instance=product) #instance=product (populate field with existing information)
if form.is_valid():
form.save()
return redirect('product')
return render(request, 'main/add_review.html',{'form':form})
URL
from django.urls import path
from . import views
urlpatterns = [
...
path('product/add_review/<product_id>', views.add_review,name="add_review"),
]
Forms
class ReviewAdd(forms.ModelForm):
class Meta:
model = ProductReview
fields = ('review_text', 'review_rating')
labels ={
'review_text': '',
'review_rating': '',
}
widgets = {
'review_text': forms.TextInput(attrs={'class':'form-control', 'placeholder':'Enter Review'}),
}
Admin
from django.contrib import admin
from .models import Venue, User, Product, ProductReview
from django.urls import path
admin.site.register(User)
admin.site.register(ProductReview)
class ProductReview(admin.ModelAdmin):
list_display=['user','product','review_text','get_review_rating']
HTML Page
{% extends 'main/base.html' %}
{% load crispy_forms_tags %}
{% block title %}
{% endblock %}
{% block content %}
<center>
<h1>Add ReviewTo Database</h1>
<br/><br/>
{% if submitted %}
Success!
{% else %}
<form action="" method="post">
{% csrf_token %}
{{ form|crispy }}
<input type="Submit" value="Submit" class="btn btn-secondary">
</form>
{% endif %}
</center>
{% endblock %}
I detect 2 fixes
On your url, the parameter product_id might need the type of data it will going to receive
path('product/add_review/<int:product_id>', views.add_review,name="add_review"),
And in your view, you are sending an instance, and no data for a new rating.
In your view:
from django.contrib.auth.decorators import login_required
from django.shortcuts import get_object_or_404
#login_required
def add_review(request, product_id):
product = get_object_or_404(Product, pk=product_id)
form = ReviewAdd(request.POST or None)
if form.is_valid():
new_rating = form.save(commit=False)
new_rating.product = product
new_rating.user = request.user
new_rating.save()
return redirect('product')
return render(request, 'main/add_review.html',{'form':form})

My form data is not being displayed on html template

i made a form and now i am trying to to view the data from the form on the html template but its not working, any help would be helpful i just want the the data entered through the the form to be displayed on the html page. Here is the code
views.py
from django.shortcuts import render
from .models import Post
from.forms import TaskForm
def add_task(request):
form = TaskForm()
if request.method == 'POST':
print(request.POST)
form = TaskForm(request.POST)
if form.is_valid():
form.save()
context = {'form': form}
return render(request, 'List/add_task.html', context)
def home(request):
return render(request, 'List/home.html')
def task_list(request):
context = {
'posts': Post.objects.all(),
}
return render(request, 'List/task.html', context)
models.py
from django.db import models
class Post(models.Model):
Task = models.CharField(max_length=50, default='pythons')
Detail = models.TextField(max_length=100, default='python')
date = models.DateTimeField(auto_now_add=True)
forms.py
from django.forms import ModelForm
from .views import Post
class TaskForm(ModelForm):
class Meta:
model = Post
fields = '__all__'
task.html
{% extends "List/Home.html" %}
{% block content %}
{% for post in posts %}
<h3>{{ post.title }}</h3>
<h3>{{ post.detail }}</h3>
{% endfor %}
{% endblock content %}
in your Post model you have fields name Task and Detail and in your template you are looking for field title and detail

Django user posts to be filtered from all posts and displayed in user profile

I am new to Python and Django and now developing a blog.I have this model that users can log in to the site and add their posts and all posts are displayed in home. At the same time I want the posts by the user to be displayed in user profile.
My model for the blogpost is
from django.db import models
from django.utils import timezone
class Blogpost(models.Model):
author = models.ForeignKey('auth.User')
title = models.CharField(max_length=200)
text = models.TextField()
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
and the views.py:
views.py
from django.contrib.auth.decorators import login_required
from django.shortcuts import render
from blogpost.models import Blogpost
def home(request):
context = {}
template = 'home.html'
return render(request,template,context)
def about(request):
context = {}
template = 'about.html'
return render(request,template,context)
#login_required(login_url='/accounts/login/')
def userprofile(request):
user = request.user
context = {'user': user}
user_posts=Blogpost.objects.filter(author=request.user).order_by('-published_date')
template = 'profile.html'
return render(request,template,context,{'user_posts':user_posts})
I am using this template to display the posts from users returned by the query set.
profile.html
{% extends 'base.html' %}
{% load staticfiles %}
{% block blogprofile %}
{{ user.username }}
{{ user.email }}
{% for Blogpost in user_posts %}
<div class="post">
<div class="date">
<p>{{ Blogpost.published_date }}</p>
<p>{{ Blogpost.author }}</p>
</div>
<h1>{{ Blogpost.title }}</h1>
<p>{{ Blogpost.text|linebreaksbr }}</p>
</div>
{% endfor %}
{% endblock %}
Now I am getting only user name and email when I open the profile.html where as the post is not getting retrieved. Can anyone please correct me on where I am making mistake.
Change your view to this:
#login_required(login_url='/accounts/login/')
def userprofile(request):
user = request.user
user_posts = Blogpost.objects.filter(author=request.user).order_by('-published_date')
template = 'profile.html'
return render(request, template, {'user_posts':user_posts,'user': user})

Django - Tango With Django upload picture

I'm on chapter 9 in Tango With Django - creating user authentication. In the registration page I have the option of uploading a picture. In my admin file everything looks good after I register myself. I show up in the User Profiles, and it even shows the image I uploaded:
Picture: Currently: profile_images/earth.jpeg Clear. However when I click on that picture this is the error message I get:
Page not found (404)
Request Method: GET
Request URL: http://localhost:8000/admin/rango/userprofile/1/change/profile_images/earth.jpeg/change/
Raised by: django.contrib.admin.options.change_view
user profile object with primary key u'1/change/profile_images/earth.jpeg' does not exist.
You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page.
models.py:
from __future__ import unicode_literals
from django.db import models
from django.template.defaultfilters import slugify
from django.contrib.auth.models import User
class Category(models.Model):
name = models.CharField(max_length=128, unique=True)
views = models.IntegerField(default=0)
likes = models.IntegerField(default=0)
slug = models.SlugField(unique=True)
def save(self, *args, **kwargs):
self.slug = slugify(self.name)
super(Category, self).save(*args, **kwargs)
class Meta:
verbose_name_plural = 'categories'
def __str__(self):
return self.name
class Page(models.Model):
category = models.ForeignKey(Category)
title = models.CharField(max_length=128)
url = models.URLField()
views = models.IntegerField(default=0)
def __str__(self):
return self.title
class UserProfile(models.Model):
user = models.OneToOneField(User)
website = models.URLField(blank=True)
picture = models.ImageField(upload_to='profile_images', blank=True)
def __str__(self):
return self.user.username
views.py - only the register():
def register(request):
registered = False
if request.method == 'POST':
user_form = UserForm(data=request.POST)
profile_form = UserProfileForm(data=request.POST)
if user_form.is_valid() and profile_form.is_valid():
user = user_form.save()
user.set_password(user.password)
user.save()
profile = profile_form.save(commit=False)
profile.user = user
if 'picture' in request.FILES:
profile.picture = request.FILES['picture']
profile.save()
registered = True
else:
print user_form.errors, profile_form.errors
else:
user_form = UserForm()
profile_form = UserProfileForm()
return render(request, 'rango/register.html',
{'user_form': user_form,
'profile_form': profile_form,
'registered': registered}
)
finally, my register.html file:
{% extends 'rango/base.html' %}
{% load staticfiles %}
{% block title_block %}
Register
{% endblock %}
{% block body_block %}
<h1>Register with Rango</h1>
{% if registered %}
Rango says: <strong>thank you for registering!</strong>
Return to the homepage<br/>
{% else %}
Rango says: <strong>register here!</strong>
Click here to go to the homepage<br/>
<form id="user_form" method="post" action="/rango/register/" enctype="multipart/form-data">
{% csrf_token %}
{{ user_form.as_p }}
{{ profile_form.as_p }}
<input type="submit" name="submit" value="Register" />
</form>
{% endif %}
{% endblock %}
user profile object with primary key u'1/change/profile_images/earth.jpeg' does not exist.
It looks like one of your URL patterns may be off; it probably just wants to capture that 1 to use as the PK for a lookup, but instead is capturing 1/change/profile_images/earth.jpeg.

Django: Form is not saving to database

I've seen similar types of problems on here but I still haven't been able to work out my problem. When I save PhotographerProfileForm in my view, the form is rendered correctly but after clicking update/submit nothing is actually saved.
No errors are shown either.
What I have now are the fields are prepopulated and I would like the ability to save over these in the database, but nothing happens and at the moment you can only update it from the admin panel.
models.py
from __future__ import unicode_literals
from django.contrib.auth.models import User
from django.db import models
# Create your models here.
class PhotographerProfile(models.Model):
user = models.OneToOneField(User)
location = models.CharField(max_length=200)
bio = models.TextField(max_length=500)
def __str__(self):
return self.user.username
User.profile = property(lambda u: PhotographerProfile.objects.get_or_create(user=u)[0])
from django.db.models.signals import post_save
from django.dispatch import receiver
#receiver(post_save, sender=User)
def create_profile(sender,instance,created,**kwargs):
if created:
profile, new = PhotographerProfile.objects.get_or_create(user=instance)
urls.py
urlpatterns = [
url(r'^profile/$', 'photoprofile.views.photographer_profile', name = 'photographer_profile'),
url(r'^profile/portfolio/$', 'photoprofile.views.photographer_portfolio', name='photographer_portfolio'),
]
views.py
#login_required
def photographer_profile(request):
photographerProfile = PhotographerProfile.objects.get(user=request.user)
form = PhotographerProfileForm(initial={'bio':photographerProfile.bio, 'location':photographerProfile.location})#This means you can prepoulate it
return render_to_response('photographerprofile.html',{'form':form}, RequestContext(request))
if request.method == 'POST':
form = PhotographerProfileForm(request.POST, instance = request.user.profile,)
if form.is_valid():
form.save()
return HttpResponseRedirect('/accounts/profile')
else:
user = request.user
profile = user.profile
form = PhotographerProfileForm()
return render(request, 'photographerprofile.html', {'form':form})
def photographer_portfolio(request):
photographerProfile = PhotographerProfile.objects.get(user=request.user)
return render_to_response('photographerportfolio.html', {'photographerProfile':photographerProfile}, RequestContext(request))
forms.py
class PhotographerProfileForm(forms.ModelForm):
class Meta:
model = PhotographerProfile
exclude = ('user',)
photographerprofile.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<h2> Profile</h2>
{% for field in form %}
{{ field.error}}
{% endfor %}
<form action='/accounts/profile/' method='post'>
{% csrf_token %}
{{form|crispy}}
<input type='submit' value='Update'/>
<p>Click <a href='/accounts/profile/portfolio/'>here</a> to view portfolio. </p>
</form>
{% endblock %}
You return in the third line of your view, before the form has been processed. Remove that line.

Categories