Django - UserEditView is missing a QuerySet? - django

trying to create an edit profile for users and i keep getting this error what should i add or change ? is my models right for UserEditView
this is my views.py (all of it edited)
maybe the vendor its not compatitable with User edit view
anything elses needs to be added or should i just change something
all imports are for vendor and UserEditView
from tkinter import Entry
from django.contrib.auth.models import User
from xml.dom.minidom import Entity
from django.contrib.auth import login
from django.contrib.auth.decorators import login_required
from django.urls import reverse_lazy
from django.views import generic
from django.contrib.auth.forms import UserCreationForm , UserChangeForm
from django.utils.text import slugify
from django.shortcuts import render, redirect
from .models import Profile, Vendor
from products.models import Product
from .forms import ProductForm
# Create your views here.
def become_vendor(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
user = form.save()
login(request, user)
vendor = Vendor.objects.create(name=user.username, created_by=user)
return redirect('home')
else:
form = UserCreationForm()
return render(request, 'vendor/become_vendor.html', {'form': form})
#login_required
def vendor_admin(request):
context = {
'user':request.user
}
vendor = request.user.vendor
products = vendor.products.all()
return render(request,'vendor/vendor_admin.html',{'vendor': vendor , 'products': products ,'context':context})
#login_required
def add_house(request):
if request.method == 'POST':
form = ProductForm (request.POST, request.FILES)
if form.is_valid():
product = form.save(commit=False)
product.vendor = request.user.vendor
product.slug = slugify(product.عنوان)
product.save()
return redirect('vendor_admin')
else:
form = ProductForm()
return render(request,'vendor/add_house.html',{'form': form})
class UserEditView(generic.UpdateView):
models = User
form_class = UserChangeForm
template_name = 'vendor/edit_profile.html'
seccess_url = reverse_lazy('vendor_admin')
def get_object(self):
return self.request.user
urls.py
from django.urls import path
from .import views
from .views import UserEditView
from django.contrib import admin
from django.contrib.auth import views as auth_views
urlpattern =[
path('signup/', views.become_vendor, name='become_vendor'),
path('profile/', views.vendor_admin, name='vendor_admin'),
path("logout/", auth_views.LogoutView.as_view(), name="logout"),
path('login/', auth_views.LoginView.as_view(template_name='vendor/login.html'), name='login'),
path('edit_profile/', UserEditView.as_view(template_name='vendor/edit_profile.html'), name='edit_profile'),
]
edit_profile.html
(where the error pops up)
{% extends "base.html"%}
{% load static %}
{% block content %}
<title>title</title>
<div class="section pt-9 pb-9">
<div class="container">
<div class="row">
<div class="col-md-12">
<div class="section-title">
<div class="wrap-title">
<h3 class="title">
<span class="first-word"></span>
</h3>
<br>
<form method="post" >
{% csrf_token %}
<table>
{{ form.as_p }}
</table>
<button class='button'>Update</button>
</form>
</div>
<hr>
{% endblock content %}

I think that you didn't declare your model correctly:
class UserEditView(generic.UpdateView):
# models = UserChangeForm #That has no sense.
model = User #The name of your model (Probably the default one: User).
form_class = UserChangeForm
template_name = 'vendor/edit_profile.html'
success_url = reverse_lazy('vendor_admin')
def get_object(self):
return self.request.user
Other thing. You have declared your template name twice. According to your views.py you can delete the template_name on your urls.py:
path('edit_profile/', UserEditView.as_view(), name='edit_profile'),

Related

How to sum up entire column of a table values in django website?

I am very new to programming. I want to sum up my entire column payment_amount. I don't know which code should I use to sum up entire column and save it on home server. I have tried to create a function but it didn't work. Can I use multiple function on same page or will have to write all different function in same def function()? I will be very grateful for your kind help.
HTML part: I
<h1>Hellow</h1>
{% extends 'base.html' %}
{% block content %}
Payment Completed
<table border="1">
<tr>
<th>Name</th>
<th>Mobile</th>
<th>Payment</th>
</tr>
{% for payment in payments %}
<tr><td>{{ payment.payee_name }}</td><td>{{ payment.phone_number }}</td><td>{{ payment.payment_amount }}</td></tr>
{% endfor %}
{% for totalpayment in totalpayments %}
<tr>
<td>{{ Payment.totaldonation }}</td>
</tr>
{% endfor %}
</table>
{% endblock %}
admin.py part:
from django.contrib import admin
from .models import ToDo, Payment
class PaymentAdmin(admin.ModelAdmin):
list_display = ('payee_name', 'phone_number', 'payment_amount')
admin.site.register(Payment, PaymentAdmin)
**forms.py part:**
from django.forms import ModelForm
from .models import ToDo, Payment
class PaymentForm(ModelForm):
class Meta:
model = Payment
fields = ['payee_name', 'phone_number', 'payment_amount']
models.py part:
from django.db import models
from django.contrib.auth.models import User
from django import forms
class Payment(models.Model):
payee_name = models.CharField(max_length=50)
phone_number = models.CharField(max_length=14)
payment_amount = models.IntegerField()
def __str__(self):
return self.name
views.py part:
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
from django.db import IntegrityError
from django.contrib.auth import login, logout, authenticate
from .forms import ToDoForm, PaymentForm
from .models import ToDo, Payment
from django.utils import timezone
from django.contrib.auth.decorators import login_required
from django.db.models import Sum
#login_required
def payment(request):
if request.method == "GET":
return render(request, 'builderpage/payment.html', {'form':PaymentForm()})
else:
try:
form = PaymentForm(request.POST)
newpayment = form.save(commit=False)
newpayment.user = request.user
newpayment.save()
return redirect('completedpayment')
except ValueError:
return render(request, 'builderpage/payment.html', {'form':PaymentForm(),'error':'Bad Data Pressed In'})
#login_required
def completedpayment(request):
payments = Payment.objects.filter(payee_name=request.user)
return render(request, 'dashboards/paymentcompleted.html', {'payments':payments})
def totaldonation(request):
data = Payment.objects.aggregate(Sum('payment_amount'))
return render(request, 'dashboards/index.html', {'data':data})
#login_required
def viewpaymentown(request, payment_pk):
payment = get_object_or_404(Payment, pk=payment_pk, name=request.user)
if request.method == 'GET':
form = PaymentForm(instance=payment)
return render(request, 'dashboards/payment.html', {'payment':payment, 'form':form})
else:
try:
form = PaymentForm(request.POST, instance=payment)
form.save()
return redirect('completedpayment')
except ValueError:
return render(request, 'dashboards/paymentcompleted.html', {'payment':payment, 'form':'form', 'error':'Bad Data. Try again.'})
you can use a python for loop, to sum up the entire column and show it on the dashboard.
def totaldonation(request):
data = Payment.objects.all()
total_sum = 0
for item in data:
total_sum += item.payment_amount
return render(request, 'dashboards/index.html', {'sum':total_sum})
This will sum all the values that are in the payment_amount of each item in the payment model.

Django form won't render (modelForm)

I have an existing site, and I'm trying to render a form to it
I tried looping trough the form and rendering it field by field, but no luck. I think i might screwed up something in my views, im a beginner to django
HTML:
{%block wform%}
<form method="POST" class="form">
{% csrf_token %}
{{ form.as_p }}
<div class="form__group">
{%if user.is_authenticated%}
<input type="submit" class="submit" value="Submit Your Data">
{%else%}
Submit Your Data
{%endif%}
</div>
</form>
{%endblock wform%}
Forms.py
from django.forms import ModelForm
from users.models import Profile
class WeightForm(ModelForm):
class Meta:
model = Profile
fields = ['weight','height','goal']
Views.py
from django.shortcuts import render
from django.contrib import messages
from users import models
from users.models import Profile
from .forms import WeightForm
# Create your views here.
def home(request):
return render(request, 'Landing/index.html')
def formsave(request):
form = WeightForm()
return render(request, 'Landing/index.html', {'form': form})
from django.shortcuts import render
from django.contrib import messages
from users import models
from users.models import Profile
from .forms import WeightForm
# Create your views here.
def home(request):
form = WeightForm()
return render(request, 'Landing/index.html', {'form': form})

Django #login_required redirects to home page

I have an issue with the below code. When I login below and try to submit the create.html template it redirects me to Home page (via home function in views and record is not saved in database). When i remove #login_required and directly navigate to /products/create , the record is saved down in database. I am confused why this is happening. Any assistance will be appreciated
I removed (#login_required) and directly navigated to /products/create and it works perfectly. However whenever I login and then use /products/create the record is not saved in database
Create.html
{%extends 'base.html'%}
{%block content%}
{%if error%}
{{error}}
{%endif%}
<h2> Create </h2>
{% csrf_token %}
<form action="create" method="POST" enctype="multipart/form-data">
{% csrf_token %}
Title:
<br/>
<input type="text" name = "title"/>
<br/><br/>
Body:
<br/>
<input type="textbox" name = "body"/>
<br/><br/>
URL:
<br/>
<input type="text" name = "url"/>
<br/><br/>
<input type="submit" class = "btn btn-primary" value = "Add Product"/>
</form>
{%endblock%}
Main url.py
from django.contrib import admin
from django.urls import path,include
from products import views
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/',include('accounts.urls')),
path('products/',include('products.urls')),
path('',views.home,name='home'),]
Sub project url.py
from django.urls import path,include
from . import views
urlpatterns = [
path('create',views.create,name='create'),]
views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.urls import path
from .models import Product
from django.utils import timezone
def home(request):
return render(request, 'products/home.html')
#login_required
def create(request):
if request.method == 'POST':
if request.POST['title'] and request.POST['body'] and request.POST['url']:
product=Product()
product.title = request.POST['title']
product.body = request.POST['body']
product.url = request.POST['url']
product.pub_date = timezone.datetime.now()
product.save()
return render(request,'products/test.html',{'error':'all conditions checked'})
else:
return render(request,'products/test.html',{'error':'all conditions not checked'})
else:
return render(request, 'products/create.html',{'error':'post method not checked'})
For reference
models.py
from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
title = models.CharField(max_length=255)
pub_date = models.DateTimeField()
body = models.TextField()
url = models.TextField()
image = models.ImageField(upload_to='images/')
icon = models.ImageField(upload_to='images/')
votes_total = models.IntegerField(default=1)
def __str__(self):
return self.title
def summary(self):
return self.body[:100]
def pub_date_pretty(self):
return self.pub_date.strftime('%b %e %Y')
* Login function *
def login(request):
if request.method == 'POST':
user = auth.authenticate(username=request.POST['username'],password=request.POST['password'])
if user is not None:
auth.login(request,user)
return redirect('home')
else:
return render(request,'accounts/login.html',{'error':'incorrect username or password'})
else:
return render(request,'accounts/login.html')

Django - Url Dispatching - Page Not Found

I am very puzzled as to why the URL dispatcher is try to look for an empty path although a url was specified for it? Does it imply that it is unable to find the specified url and therefore trying to find the default.
This happens when I try to POST and HttpResponseRedirect searches for an empty path instead of following the specified path. Assume that the other.
Using Django version: 2.0
Thanks in advance!
main/urls.py (ROOT_URLCONF)
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('app/', include('shorterner.urls'))
]
shorterner/urls.py
from django.urls import path
from . import views
urlpatterns = [
path('request/', views.RequestView.as_view(), name="request"),
path('list/', views.IndexView.as_view(), name="list")
]
shorterner/views.py
from django.shortcuts import render, redirect
from django.http import HttpResponseRedirect
from django.conf import settings
from django.urls import reverse
from django.views import View, generic
from .models import Urls
import requests
import json
from .forms import SubmitUrlForm
class RequestView(View):
form_class = SubmitUrlForm
initial = { 'url': ''}
template_name = "shorterner/request.html"
context_object_name = 'url'
def form_valid(self, form):
return super().form_valid(form)
def get(self, request, *args, **kwargs):
form = self.form_class(initial=self.initial)
return render(request, self.template_name, {'form': form})
def post(self, request, *args, **kwargs):
form = self.form_class(request.POST)
if form.is_valid():
input_url = form.cleaned_data['url']
short_url = google_url_shorten(input_url)
print(input_url)
print(short_url)
new_url = Urls.create(short_url, input_url)
new_url.save()
return HttpResponseRedirect('/app/request/')
return render(request, self.template_name, {'form': form})
shorterner/templates/shorterner/request.html
{% extends 'shorterner/base.html' %}
{% block content %}
<form action="/" method="POST">
{% csrf_token %}
<input type="text" name="url" placeholder="Url..." required/>
<input type="submit" value="Submit"/>
</form>
{% endblock %}
Screenshot of the problem
Error Page
Looks like you're sending form data to this path /. But you've not defined that route in main/urls.py.

HttpResponseRedirect doesn't work after new_join.save()

I tried to make simple request form. And I need to redirect user to "thank you" page after successful form sent. But after user hit "send" button - nothing happens. Just reload form page without form cleaning also.
Form is on "call" page, redirect needs "confirm" page...
So, task is: user fill the form on page "call" and after hitting "send" button, goes to "confirm" page.
My model:
# -*- coding: utf-8 -*-
from django.db import models
from django.forms import ModelForm
# Create your models here.
class Join(models.Model):
class Meta():
db_table = 'expert_request'
user_expert = models.CharField(max_length=100)
user_name = models.CharField(max_length=100)
user_cost = models.CharField(max_length=100)
user_email = models.EmailField()
timestamp = models.DateTimeField(auto_now_add=True, auto_now=False)
updated = models.DateTimeField(auto_now_add=False, auto_now=True)
def __unicode__(self):
return self.user_email
my "forms.py":
from django import forms
from userform.models import Join
class JoinForm(forms.ModelForm):
class Meta:
model = Join
This is my "views.py":
from django.shortcuts import render
from django.shortcuts import HttpResponseRedirect, Http404
# Create your views here.
from userform.forms import JoinForm
from userform.models import Join
def userform(request):
form = JoinForm(request.POST or None)
if form.is_valid():
new_join = form.save(commit=False)
new_join.save()
HttpResponseRedirect('/confirm/')
context = {"form": form}
template = "userform.html"
return render(request, template, context)
def confirm(request):
return render(request, 'confirm.html')
This is my URL's:
from django.conf.urls import patterns, include, url
from django.contrib import admin
urlpatterns = patterns('',
url(r'^admin/', include(admin.site.urls)),
(r'^tinymce/', include('tinymce.urls')),
url(r'^$', 'expert.views.index', name='index'),
url(r'^(\d+)/?$', 'expert.views.index'),
url(r'^call/$', 'userform.views.userform', name='call'),
url(r'^confirm/$', 'userform.views.confirm', name='confirm'),
)
My template "userform.html":
{% load staticfiles %}
<form style="position:relative" method="POST" action="">{% csrf_token %}
{{ form.user_expert }}
<p style="position:absolute; top:50px; left:20px; color:#FF0000;">{{ form.user_expert.errors.as_text }}</p>
{{ form.user_name }}
<p style="position:absolute; top:182px; left:20px; color:#FF0000;">{{ form.user_name.errors.as_text }}</p>
{{ form.user_cost }}
<p style="position:absolute; top:50px; left:380px; color:#FF0000;">{{ form.user_cost.errors.as_text }}</p>
{{ form.user_email }}
<p style="position:absolute; top:182px; left:380px; color:#FF0000;">{{ form.user_email.errors.as_text }}</p>
<button type="submit">Send</button>
<div class="clear"></div>
</form>
Maybe you forgot the return statement in userform view function? Fix its beginning like this:
def userform(request):
form = JoinForm(request.POST or None)
if form.is_valid():
new_join = form.save(commit=False)
new_join.save()
return HttpResponseRedirect('/confirm/')