The main problem for me was: If a user is the owner of the prime then it should return True. But it always returns False.
My models.py:
from django.db import models
from django.contrib.auth.models import User
from django.core.urlresolvers import reverse
class Prime(models.Model):
prime_owner = models.ForeignKey(User, null=True)
prime_name = models.CharField(max_length=100)
prime_address = models.CharField(max_length=250)
My views.py:
class PrimeDetails(generic.DetailView):
template_name ='prime/primedetails.html'
model = Prime
def get_context_data(self, **kwargs):
context = super(PrimeDetails, self).get_context_data(**kwargs)
user = self.request.user
prime_owner = Prime.prime_owner
if user == prime_owner:
owner = True
else:
owner = False
context['owner'] = owner
return context
primedetails.html
{% extends 'prime/base.html' %}
{% block content %}
<div class="container">
<h1>{{ owner }}</h1>
<h1>{{object.prime_name }}</h1>
<h3>{{object.prime_address}}</h3>
</div>
{% endblock %}
Prime is a model, not the object.
Try change the Prime to self.get_object(), like this:
def get_context_data(self, **kwargs):
context = super(PrimeDetails, self).get_context_data(**kwargs)
user = self.request.user
prime_owner = self.get_object().prime_owner
if user == prime_owner:
owner = True
else:
owner = False
context['owner'] = owner
return context
Related
I am in a middle of a project. I have a model :-
class CustomersModels(models.Model):
def servChoices(servs):
lst = [x.serv_name for x in servs]
ch =()
for a in lst:
ch += (a,a),
return ch
customer_name = models.CharField(max_length=100)
comp_name = models.CharField(max_length=100)
ph_no = models.CharField(max_length=12)
webs_name = models.URLField(max_length=200)
service_insterested = models.OneToOneField(ServiceModel, on_delete = models.CASCADE)
def __str__(self):
return self.customer_name
I have a corresponding form for this model.
Now what i want is the fields customer_name, comp_name, webs_name
to be optional in one page. And required in another page.
Please guide me to establish the task in the most convenient manner
Deleted in 'def servChoices', service_insterested because I don't have access to them in the model. I also made it to return a string with the name of the class return 'CustomersModels', so that you can edit, delete records with empty values.
The field class 'customer_name', 'comp_name' ,'webs_name' are set to blank=True to make them optional.
In the NoForm, the required field is 'ph_no'. YesForm requires all fields to be filled in. For this, a validator (clean) is used, which will display a message on the page which field is not filled in (the form will not be sent until all fields are filled). You can read about clean here:
In the bboard views, replace with your folder where you have the templates (this is the string template_name = 'bboard/templ_yes.html').
urls.py
urlpatterns = [
path('yes/', YesCreateView.as_view(), name='yes'),
path('no/', NoCreateView.as_view(), name='no'),
]
views.py
from django.views.generic.edit import CreateView
from django.urls import reverse_lazy
from .forms import NoForm, YesForm
class NoCreateView(CreateView):
template_name = 'bboard/templ_no.html'
form_class = NoForm
success_url = reverse_lazy('no')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
class YesCreateView(CreateView):
template_name = 'bboard/templ_yes.html'
form_class = YesForm
success_url = reverse_lazy('yes')
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
return context
forms.py
from django.forms import ModelForm
from .models import CustomersModels
from django.core.exceptions import ValidationError
class YesForm(ModelForm):
class Meta:
model = CustomersModels
fields = ('customer_name', 'comp_name', 'ph_no', 'webs_name')
def clean(self):
cleaned_data = super().clean()
customer_name = cleaned_data.get('customer_name')
comp_name = cleaned_data.get('comp_name')
webs_name = cleaned_data.get('webs_name')
if len(customer_name) <= 0 or customer_name == '':
raise ValidationError(
"fill in the field customer_name"
)
if len(comp_name) <= 0 or comp_name == '':
raise ValidationError(
"fill in the field comp_name"
)
if len(webs_name) <= 0 or webs_name == '':
raise ValidationError(
"fill in the field webs_name"
)
class NoForm(ModelForm):
class Meta:
model = CustomersModels
fields = ('customer_name', 'comp_name', 'ph_no', 'webs_name')
models.py
class CustomersModels(models.Model):
customer_name = models.CharField(max_length=100, blank=True)
comp_name = models.CharField(max_length=100, blank=True)
ph_no = models.CharField(max_length=12)
webs_name = models.URLField(max_length=200, blank=True)
def __str__(self):
return 'CustomersModels'
tepmplate(templ_yes.html)
<h2>form</h2>
<form method="post" action="{% url 'yes'%}">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="adding">
</form>
tepmplate(templ_no.html)
<h2>form</h2>
<form method="post" action="{% url 'no'%}">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="adding">
</form>
So i have a model called folder, i want to show all the folder created by current user on HomeView, but somehow it's not working, what i think is that folders are not getting connected to user who created them.
models.py
from django.db import models
from django.contrib.auth.models import User
from django.db.models.deletion import CASCADE
from django.core.validators import MinValueValidator
from django.core.exceptions import PermissionDenied
# The Folders Model.
class Folder(models.Model):
name = models.CharField(max_length = 250)
parent = models.ForeignKey('self', on_delete = CASCADE, null = True, blank = True )
cr_date = models.DateTimeField(auto_now_add = True)
user = models.OneToOneField(to=User, on_delete=CASCADE, null=True, blank=True)
def __str__(self):
return "%s" % self.name
view.py
class HomeView(TemplateView):
template_name = "ahmed_drive/home.html"
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
user = self.request.user
home_folders = Folder.objects.filter(user=user).order_by('-cr_date')
home_files = Fileshare.objects.filter(uploaded_by=user).order_by('-id')
context['home_folders'] = home_folders
context['home_files'] = home_files
return context
#method_decorator(login_required, name="dispatch")
class FolderCreate(CreateView):
model = Folder
fields = ["name", "parent"]
def formvalid():
if form.is_valid():
form.save()
return redirect('home.html')
else :
return render(request,{'form': form})
home.html
{% extends 'base.html' %}
{% block content %}
{% for Folder in home_folders %}
<h1> {{Folder.name}} </h1>
{% endfor %}
{% endblock %}
when you create folder you don't connect user to it.
you need to do it before saving form
def form_valid(self, form):
folder = form.save(commit=False)
folder.user = request.user
folder.save()
return redirect('home.html')
Please forgive me if this has already been asked
I am following a course online, albeit 3 years old, so somethings have been updated since then
However datetime seems to be roughly the same from what I can see.
The problem arises when we use timedelta to filter all the sales in the last month
I have added some test sales over the weeks and when I tried to filter it down to the last 48 hours, nothing
with a bit of testing i went back 12 days (as of this question and a list of items sold back on the 20th February showed up but nothing sooner.
I went into the admin and updated one of them and refreshed the page. and it disappeared completely
Can anyone provide any insight as to what i am missing?
If you need more information please say:
Models.py
from decimal import Decimal
import datetime
from django.conf import settings
from django.db import models
from django.db.models import Count, Sum, Avg
from django.db.models.signals import pre_save, post_save
from django.urls import reverse
from django.utils import timezone
from addresses.models import Address
from billing.models import BillingProfile
from carts.models import Cart
from ecommerce.utils import unique_order_id_generator
from products.models import Product
ORDER_STATUS_CHOICES = (
('created', 'Created'),
('paid', 'Paid'),
('shipped', 'Shipped'),
('refunded', 'Refunded'),
)
class OrderManagerQuerySet(models.query.QuerySet):
def recent(self):
return self.order_by("-updated", "-timestamp")
def by_date(self):
now = timezone.now() - datetime.timedelta(days=12)
return self.filter(updated__day__gte=now.day)
def totals_data(self):
return self.aggregate(Sum("total"), Avg("total"))
def cart_data(self):
return self.aggregate(Sum("cart__products__price"), Avg("cart__products__price"), Count("cart__products"))
def by_status(self, status="shipped"):
return self.filter(status=status)
def not_refunded(self):
return self.exclude(status='refunded')
def by_request(self, request):
billing_profile, created = BillingProfile.objects.new_or_get(request)
return self.filter(billing_profile=billing_profile,)
def not_created(self):
return self.exclude(status='created')
class OrderManager(models.Manager):
def get_queryset(self):
return OrderManagerQuerySet(self.model, using=self._db)
def by_request(self, request):
return self.get_queryset().by_request(request)
def new_or_get(self, billing_profile, cart_obj):
created = False
qs = self.get_queryset().filter(
billing_profile=billing_profile,
cart=cart_obj,
active=True,
status='created'
)
if qs.count() == 1:
obj = qs.first()
else:
obj = self.model.objects.create(
billing_profile=billing_profile,
cart=cart_obj
)
created = True
return obj, created
class Order(models.Model):
billing_profile = models.ForeignKey(BillingProfile, null=True, blank=True, on_delete=models.CASCADE)
order_id = models.CharField(max_length=120, blank=True)
shipping_address = models.ForeignKey(Address, related_name="shipping_address", null=True, blank=True, on_delete=models.CASCADE)
billing_address = models.ForeignKey(Address, related_name="billing_address", null=True, blank=True, on_delete=models.CASCADE)
cart = models.ForeignKey(Cart, on_delete=models.CASCADE)
status = models.CharField(max_length=120, default='created', choices=ORDER_STATUS_CHOICES)
shipping_total = models.DecimalField(default=5.99, max_digits=100, decimal_places=2)
total = models.DecimalField(default=0.00, max_digits=100, decimal_places=2)
active = models.BooleanField(default=True)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.order_id
objects = OrderManager()
class Meta:
ordering = ['-timestamp', '-updated']
def get_absolute_url(self):
return reverse("orders:detail", kwargs={'order_id': self.order_id})
def get_status(self):
if self.status == "refunded":
return "Refunded order"
elif self.status == "shipped":
return "Shipped"
return "Shipping Soon"
def update_total(self):
cart_total = self.cart.total
shipping_total = self.shipping_total
new_total = Decimal(cart_total)+Decimal(shipping_total)
formatted_total = format(new_total, '.2f')
print(type(new_total))
self.total = formatted_total
self.save()
return new_total
def check_done(self):
shipping_address_required = not self.cart.is_digital
shipping_done = False
if shipping_address_required and self.shipping_address:
shipping_done = True
elif shipping_address_required and not self.shipping_address:
shipping_done = False
else:
shipping_done = True
billing_profile = self.billing_profile
billing_address = self.billing_address
total = self.total
if billing_profile and shipping_done and billing_address and total > 0:
return True
return False
def update_purchases(self):
for p in self.cart.products.all():
obj, create = ProductPurchase.objects.get_or_create(
order_id = self.order_id,
product = p,
billing_profile= self.billing_profile,
)
return ProductPurchase.objects.filter(order_id = self.order_id).count()
def mark_paid(self):
if self.status != 'paid':
if self.check_done():
self.status = "paid"
self.save()
self.update_purchases()
return self.status
def pre_save_create_order_id(sender, instance, *args, **kwargs):
if not instance.order_id:
instance.order_id = unique_order_id_generator(instance)
qs= Order.objects.filter(cart=instance.cart).exclude(billing_profile=instance.billing_profile)
if qs.exists():
qs.update(active=False)
pre_save.connect(pre_save_create_order_id, sender=Order)
def post_save_cart_total(sender, instance, created, *args, **kwargs):
if not created:
cart_obj = instance
cart_total = cart_obj.total
cart_id = cart_obj.id
qs = Order.objects.filter(cart__id=cart_id)
if qs.count() ==1:
order_obj = qs.first()
order_obj.update_total()
post_save.connect(post_save_cart_total,sender=Cart)
def post_save_order(sender, instance, created, *args, **kwargs):
print("running")
if created:
print("updating...first")
instance.update_total()
post_save.connect(post_save_order,sender=Order)
class ProductPurchaseQuerySet(models.query.QuerySet):
def active(self):
return self.filter(refunded=False)
def digital(self):
return self.filter(product__is_digital=True)
def by_request(self, request):
billing_profile, created = BillingProfile.objects.new_or_get(request)
return self.filter(billing_profile=billing_profile,)
class ProductPurchaseManager(models.Manager):
def get_queryset(self):
return ProductPurchaseQuerySet(self.model, using=self._db)
def all(self):
return self.get_queryset().active()
def digital(self):
return self.get_queryset().active().digital()
def by_request(self, request):
return self.get_queryset().by_request(request)
def products_by_id(self, request):
qs = self.by_request(request).digital()
ids_ = [x.product.id for x in qs]
return ids_
def products_by_request(self, request):
ids_ = self.products_by_id(request)
product_qs = Product.objects.filter(id__in=ids_).distinct()
return product_qs
class ProductPurchase(models.Model):
order_id = models.CharField(max_length=120)
billing_profile = models.ForeignKey(BillingProfile, on_delete=models.CASCADE) # billingprofile.productpurchase_set.all()
product = models.ForeignKey(Product, on_delete=models.CASCADE) # product.productpurchase_set.count()
refunded = models.BooleanField(default=False)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
objects = ProductPurchaseManager()
def __str__(self):
return self.product.title
Views.py
from django.contrib.auth.mixins import LoginRequiredMixin
from django.db.models import Count, Sum, Avg
from django.http import HttpResponse
from django.views.generic import TemplateView
from django.shortcuts import render
from orders.models import Order
class SalesView(LoginRequiredMixin, TemplateView):
template_name = 'analytics/sales.html'
def dispatch(self, *args, **kwargs):
user = self.request.user
if not user.is_staff:
return render(self.request, "401.html", {})
return super(SalesView, self).dispatch(*args, **kwargs)
def get_context_data(self, *args, **kwargs):
context = super(SalesView, self).get_context_data(*args, **kwargs)
qs = Order.objects.all().by_date()
context['orders'] = qs
context['recent_orders'] = qs.recent().not_refunded()
context['recent_orders_data'] = context['recent_orders'].totals_data()
context['recent_orders_cart_data'] = context['recent_orders'].cart_data()
context['shipped_orders'] = qs.recent().not_refunded().by_status("shipped")
context['shipped_orders_data'] = context['shipped_orders'].totals_data()
context['paid_orders'] = qs.recent().not_refunded().by_status("paid")
context['paid_orders_total'] = context['paid_orders'].totals_data()
return context
Sales.html
{% extends "base.html" %}
{% block content%}
<div class="row">
<div class="col-12">
<h1>Sales Data</h1>
</div>
</div>
<div class="row">
<div class="col">
<p>Recent Toal: £{% if recent_orders_data.total__sum %} {{ recent_orders_data.total__sum }}{% else %}0 {% endif %}</p>
<ol>
{% for order in recent_orders %}
<li>{{ order.order_id}}
{{ order.total}}
{{ order.updated}} </li>
{% endfor %}
</ol>
</div>
<div class="col">
<p>Shipped Total: £{% if shipped_orders_data.total__sum %}{{ shipped_orders_data.total__sum }}{% else %}0{% endif %}</p>
<ol>
{% for order in shipped_orders %}
<li>{{ order.order_id}}
{{ order.total}}
{{ order.updated}}</li>
{% endfor %}
</ol>
</div>
<div class="col">
<p>Paid Totals: £{% if shipped_orders_data.total__sum %}{{ paid_orders_total.total__sum }}{% else %}0{% endif %}</p>
<ol>
{% for order in paid_orders %}
<li>{{ order.order_id}}
{{ order.total}}
{{ order.updated}}</li>
{% endfor %}
</ol>
</div>
</div>
{% endblock %}
In your filter by_date method you are using a filter on the day not the date. This won't help as it'll return the day of the month. So if the date was 2020-03-11 it would return 29 for now.day. If you change .day for .date() as well as updated__day__gte for updated__date__gte it should be okay
def by_date(self):
now = timezone.now() - datetime.timedelta(days=12)
return self.filter(updated__date__gte=now.date())
The following should work fine:
now = timezone.now().date() - datetime.timedelta(days=12)
return self.filter(updated__date__gte=now)
1
I'm working on Django. I'm getting the error below. I didn't find the solution despite the much increased.Please refer the this link for trace back
Codes in views.py
class UpdateVote(LoginRequiredMixin,UpdateView):
form_class = VoteForm
queryset = Vote.objects.all()
def get_object(self,queryset=None):
vote = super().get_object(queryset)
user = self.request.user
if vote.user != user:
raise PermissionDenied('can not change another user vote')
return vote
def get_success_url(self):
movie_id = self.object.movie.id
return reverse('core:movie_detail', kwargs={'pk':movie_id})
def render_to_response(self, context, **response_kwargs):
movie_id = context['object'].id
movie_detail_url = reverse('core:movie_detail',kwargs={'pk':movie_id})
return redirect(to=movie_detail_url)
class MovieDetail(DetailView):
queryset = Movie.objects.all_with_prefetch_persons()
def get_context_data(self, **kwargs):
ctx = super().get_context_data(**kwargs)
if self.request.user.is_authenticated:
vote = Vote.objects.get_vote_or_unsaved_blank_vote(movie=self.object,user=self.request.user)
if vote.id:
vote_url_form = reverse('core:UpdateVote',kwargs={'movie_id':vote.movie.id,'pk':vote.id})
else:
vote_url_form = (reverse('core:create_vote',kwargs={'movie_id':self.object.id}))
vote_form = VoteForm(instance=vote)
ctx['vote_form'] = vote_form
ctx['vote_url_form'] = vote_url_form
return ctx
Codes in form.py
I have used this form to link with UpdateView
from django import forms
from django.contrib.auth import get_user_model
from .models import Movie,Vote
class VoteForm(forms.ModelForm):
user = forms.ModelChoiceField(widget=forms.HiddenInput,queryset=get_user_model().objects.all(),disabled=True)
movie = forms.ModelChoiceField(widget=forms.HiddenInput,queryset = Movie.objects.all(),disabled=True)
value = forms.ChoiceField(widget=forms.RadioSelect,choices=Vote.VALUE_CHOICE)
class Meta:
model = Vote
fields = ('value','user','movie',)
urls.py
This is the url mapping for the view.
from django.contrib import admin
from django.urls import path
from .views import MovieList,MovieDetail,PersonDetail,CreateVote,UpdateVote
app_name = 'core'
urlpatterns = [
path('movies/', MovieList.as_view(), name='movie_list'),
path('movie/<int:pk>/', MovieDetail.as_view(), name='movie_details'),
path('person/<int:pk>/', PersonDetail.as_view(), name='person_details'),
path('movie/<int:movie_id>/vote/', CreateVote.as_view(), name='create_vote'),
path('movie/<int:movie_id>/vote/<int:pk>', UpdateVote.as_view(), name='UpdateVote'),
]
HTML template
This is the template I used.
{% block sidebar %}
<div>
{% if vote_form %}
<form action="{{vote_form_url}}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ vote_form.as_p }}
<button class="btn btn-primary" type="submit" >Vote</button>
</form>
{% else %}
<p>Login to vote for this movie</p>
{% endif %} </div> {% endblock %}
Your UpdateVote view is using VoteForm and the queryset on that view is from Vote model, so that the object field inside that view is the instance of Vote model, not Movie model.
This code movie_id = context['object'].id also not work because context might not included object of UpdateVote view, that caused the error KeyError, Exception Value: 'object'. You could get movie_id via kwargs field inside UpdateVote view because you've already defined movie_id in the path.
With this:
path('movie/<int:movie_id>/vote/<int:pk>', UpdateVote.as_view(), name='UpdateVote'),
Your view can get the values by using kwargs like so:
class UpdateVote(LoginRequiredMixin,UpdateView):
form_class = VoteForm
queryset = Vote.objects.all()
def get_object(self,queryset=None):
vote = super().get_object(queryset)
user = self.request.user
if vote.user != user:
raise PermissionDenied('can not change another user vote')
return vote
def get_success_url(self):
movie_id = self.kwargs.get('movie_id')
return reverse('core:movie_detail', kwargs={'pk':movie_id})
def render_to_response(self, context, **response_kwargs):
movie_id = self.kwargs.get('movie_id')
movie_detail_url = reverse('core:movie_detail',kwargs={'pk':movie_id})
return redirect(to=movie_detail_url)
I want to show the data of a user which he has entered. This is my model
class IgaiaContent(models.Model):
CONTENT_CHANNELS = (
('YouTube','Youtube'),
('FaceBook','FaceBook'),
('Flickr','Flickr'),
('Instagram','Instagram'),
)
content_name = models.CharField(max_length=255, primary_key=True)
content_type = models.CharField(max_length=255,null=True)
content_source = models.CharField(max_length=255,null=True, choices=CONTENT_CHANNELS)
content_location = models.CharField(max_length=255,null=True)
content_latitude = models.DecimalField(max_digits=20,decimal_places=2,null=True)
content_longitude = models.DecimalField(max_digits=20,decimal_places=2,null=True)
content_embed_code = models.TextField(null=True)
content_description = models.TextField(null=True)
content_tags_user = models.CharField(max_length=255,null=True)
content_time_uploaded = models.DateTimeField(auto_now_add=True)
content_time_updated = models.DateField(null=True)
def __unicode__(self):
return self.content_name
return self.content_type
return self.content_source
return self.content_location
return self.content_latitude
return self.content_longitude
return self.embed_code
return self.description
return self.tags_user
return self.time_uploaded
return self.time_updated
tagging.register(IgaiaContent)
My view
def create_page(request):
if request.method == 'POST':
form = AuthorForm1(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/thanks/')
else:
form = AuthorForm1()
c = {}
c.update(csrf(request))
return render_to_response('portal/form1.htm',{'form':form},context_instance=RequestContext(request))
My form template:
<form method="post" style="height: 553px; width: 594px">
<div class="style12">
{% csrf_token %}
</br>{{ form.as_p }}
</div>
</form>
thats how i am showing my model values
employee_info1 = {
"queryset" : IgaiaContent.objects.all(),
"template_name" : "portal/emp1.html",
}
urlpatterns = patterns('',
(r'^view5/', list_detail.object_list, employee_info1),
)
emp1.html
{% if object_list %}
<table>
<ul>
{% for item in object_list %}
<li>{{item.content_name}}</li>
<li>{{item.content_type}}</li>
<li>{{item.content_source}}</li>
<li>{{item.content_location}}</li>
<li>{{item.content_latitude}}</li>
<li>{{item.content_longitude}}</li>
<li>{{item.content_embed_code}}</li>
<li>{{item.content_description}}</li>
<li>{{item.content_tags_user}}</li>
<li>{{item.content_time_uploaded}}</li>
<li>{{item.content_time_updated}}</li></ul>
{% empty %}
<td colspan="11">No items.</td>
{% endfor %}
</table>
{% endif %}
It is not displaying specific user value means it is displaying me everything.
can anyone tell me how to show specific user values/data?
You need to update your model so that it contains a field to store the user -
from django.contrib.auth.models import User
class IgaiaContent(models.Model):
#...
user = models.ForeignKey(User)
Then you need to create a ModelForm as described here.
class IgaiaContentForm(forms.ModelForm):
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
return super(MyModelForm, self).__init__(*args, **kwargs)
def save(self, *args, **kwargs):
kwargs['commit']=False
obj = super(MyModelForm, self).save(*args, **kwargs)
if self.request:
obj.user = self.request.user
obj.save()
class Meta:
model = IgaiaContent
Now update your view so that that you use your new ModelForm
def create_page(request):
if request.method == 'POST':
form = IgaiaContentForm(request.POST)
if form.is_valid():
form.save()
return HttpResponseRedirect('/thanks/')
else:
form = IgaiaContentForm()
#...
Now in your object_list view you do something like -
from django.shortcuts import render_to_response
def object_list(request):
#....
object_list = IgaiaContent.objects.filter(user=request.user)
return render_to_response('object_list_template.html', {'object_list': object_list})