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})
Related
I'm facing an issue. My goal is to know if a user already exist in DB. If it's true add it to the channel and create it.
There is only two fields in the form for consumer.
title of channel
name of seller (check if it's valid and if so add it)
I don't really why that does not work.
class CreateChannelView(CreateView):
model = Channel
form_class = CreateChannelForm
template_name = 'channel_new.html'
def form_valid(self, form):
form.instance.consumer = self.request.user
sellers = self.request.POST.get("seller")
current_seller = User.objects.filter(username=sellers)
if current_seller.count()<1:
raise forms.ValidationError('Username does not exist')
else:
existed_seller = User.objects.get(username=sellers)
form.instance.seller.add(existed_seller)
form.save()
return super(CreateChannelView, self).form_valid(form)
def get_success_url(self):
return reverse_lazy('channel:channel_home')
class Channel(models.Model):
consumer = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_consumer", blank=True, null=True)
name = models.CharField(max_length=10)
seller = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="channel_seller")
def save(self, *args, **kwargs):
if not self.slug:
self.slug = unique_slugify(self, slugify(self.name))
super().save(*args, **kwargs)
def __str__(self):
return self.name
Here is my template with the form. I'm using classical field form and I add one field called seller which is related to my channel model
<form method="post" class="user-log">
{% csrf_token %}
{% for field in form %}
<div class="mt-10">
{{ field }}
</div>
{% endfor %}
<div class="mt-10">
<input type="text" name="seller" placeholder="Mike" onfocus="this.placeholder = ''" onblur="this.placeholder = 'Jean'" required="" class="single-input">
</div>
<input type="submit" class="" value=" Add a new channel">
</form>
ERROR:
RelatedObjectDoesNotExist at /channel/new/
Exception Value: Channel has no seller.
Trace:
form.instance.seller.add(existed_seller)
__class__
<class 'channel.views.CreateChannelView'>
current_seller
<QuerySet [<User: fredo>]>
existed_seller
<User: fredo>
form
<CreateChannelForm bound=True, valid=True, fields=(name)>
self
<channel.views.CreateChannelView object at 0x2b00798d3350>
sellers
'fredo'
Here is the answer :)
def form_valid(self, form):
form.instance.consumer = self.request.user
sellers = self.request.POST.get("seller")
current_seller = User.objects.filter(username=sellers)
if current_seller.count()<1:
raise forms.ValidationError('Username does not exist')
else:
existed_seller = User.objects.get(username=sellers)
form.instance.seller = existed_seller #here is the chnage
form.save()
return super(CreateChannelView, self).form_valid(form)
i've created web blog with django 2.2 each post has multiple images , but when i try to update the post the images wont updated
i use class based view
class Post(models.Model):
user= models.ForeignKey(Account,on_delete=models.CASCADE)
title= models.CharField(max_length=100)
#others
class PostImage(models.Model):
post= models.ForeignKey(Post,on_delete=models.CASCADE,related_name='images')
media_files = models.FileField(upload_to=random_url)
and this my forms.py
class PostImageForm(forms.ModelForm):
class Meta:
model = PostImage
fields = [
'media_files'
]
class PostUpdateForm(forms.ModelForm):
class Meta:
model = Post
fields = [
'title','description',#and others
]
my views.py
PostImageFormSet = inlineformset_factory(
Post,PostImage,form=PostImageForm,extra=1,can_delete=True,can_order=False
)
class PostUpdateView(LoginRequiredMixin,UserPassesTestMixin,UpdateView):
model = Post
form_class = PostUpdateForm
template_name = 'posts/update_post.html'
def get_context_data(self,**kwargs):
data = super().get_context_data(**kwargs)
if self.request.POST:
data['images'] = PostImageFormSet(self.request.POST or None,self.request.FILES,instance=self.object)
else:
data['images'] = PostImageFormSet(instance=self.object)
return data
def form_valid(self,form):
context = self.get_context_data()
images = context['images']
with transaction.atomic():
if form.is_valid() and images.is_valid():
self.object = form.save()
images.instance = self.object
images.save()
return super().form_valid(form)
def test_func(self):
post = self.get_object()
if self.request.user.username == post.user.username:
return True
return False
def get_success_url(self):
return reverse_lazy('post:post-detail',kwargs={'slug':self.object.slug})
my templates
<form enctype="multipart/form-data" method="post" action="">
{% csrf_token %}
{{images.management_form }}
{{ form|crispy }}
{% for img in images %}
<label>{{img.media_files.label}}</label>
{{img.media_files}}
{% endfor %}
<button type="submit" class="btn btn-block btn-primary">update</button>
</form>
it only save the post form not images , it doesnt affect images form
thanks
I think instead of writing:
images.instance = self.object
Please try this:
I noticed you are using the form is valid so it might be slightly different, but if you change it a bit it should work.
form = PostUpdateForm(request.POST)
if form.is_valid():
cd = form.cleaned_data
images = cd.get('images')
Or using your current setup(not tested yet)
if form.is_valid() //Remove this part -> and images.is_valid():
if form.is_valid():
self.object = form.save()
instance = self.object
cd = form.cleaned_data
images = cd.get('images')
images.save()
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)
I have a simple form witch ModelChoiceField. This is a part of my view.py file:
def premium(request, id):
context = {}
try:
site = Site.objects.get(id=id)
except Site.DoesNotExist:
raise Http404("Nie ma takiej strony")
if request.method == 'POST':
premium_form = PremiumForm(request.POST)
if premium_form.is_valid():
# group = Group.objects.get(id=request.POST["kod"])
print('OK')
else:
print('NOT OK')
else:
premium_form = PremiumForm(site)
premium_form.fields['group'].queryset =
premium_form.fields['group'].queryset.exclude(group_name=site.group)
context['site'] = site
context['form'] = premium_form
context['category'] = site.category
context['subcategory'] = site.subcategory
return render(request, 'mainapp/premium.html', context)
This is my form:
class PremiumForm(forms.Form):
def __init__(self, site, *args, **kwargs):
super(PremiumForm, self).__init__(*args, **kwargs)
self.fields['group'].initial = 2
self.fields['group'].empty_label = None
group = forms.ModelChoiceField(
queryset=Group.objects.filter(is_active=True),
help_text="<div id='group'></div>",
label="Some text",
required=False)
My premium.html file:
<form method="post" action="" class="form-horizontal">
{% csrf_token %}
{% bootstrap_form form layout='horizontal'%} <br>
{% bootstrap_button "Submit" size='large' button_type="submit" button_class="btn-primary btn-main-add" %}
</form>
When I press "Submit" button I get "NOT OK". I can't resolve this problem. I don't have any idea how to validate forms.ModelChoiceField. Thanks for any help.
Form should be initialised with kwargs:
premium_form = PremiumForm(site=site)
And inside init:
def __init__(self, *args, **kwargs):
site = kwargs['site']
However, site is not used inside form initialization so you can just remove it and it will solve the issue.
I have different models:
Cars
Pictures (models.ForeignKey(Cars))
CarsOptions(models.OneToOneField(Cars))
Then I want, that user can add new cars. Forms.py:
class NewCarsForm(ModelForm):
class Meta:
model = Cars
exclude = ('checked','user')
In views.py:
#login_required
def add_car(request):
form = NewCarsForm(request.POST or None)
if form.is_valid():
cmodel = form.save()
cmodel.save()
return redirect(profile)
return render(request, 'add_car.html', { 'form': form,})
I have a few questions (yes, I read this).
As you can see, user can add only "car", not pictures and options. How to do this on one page in one form?
exclude = ('checked','user'), it means, that I want to make all new positions with checked=0, so I can filter them. And the user-field - users cant choose user in a list. How to take user id (who adds car) in form.save()?
Thanks.
Update:
class Pictures(models.Model):
cars = models.ForeignKey(Cars, related_name='pictures')
width = models.PositiveIntegerField(editable=False, default=640)
height = models.PositiveIntegerField(editable=False, default=480)
image = models.ImageField(upload_to=lambda inst, fname: 'users_img/' + 'cars' + fname, height_field='height', width_field='width', max_length=100)
def __unicode__(self):
return str(self.id)
forms.py
class NewCarsForm(ModelForm):
class Meta:
model = Cars
exclude = ('checked','user')
PicturesFormset = inlineformset_factory(Cars, Pictures,
fields=('field_name', 'field_name'), can_delete=True)
CarsOptionsFormset = inlineformset_factory(Cars, CarsOptions,
fields=('field_name', 'field_name'), can_delete=True)
views.py
#login_required
def add_car(request):
cars = Cars(user=request.user)
if request.method == 'POST':
form = NewCarsForm(request.POST, instance=cars)
if form.is_valid():
cmodel = form.save()
picture_formset = PicturesFormset(request.POST, request.FILES,
instance=cmodel)
if picture_formset.is_valid():
picture_formset.save()
option_formset = CarsOptionsFormset(request.POST, instance=cmodel)
if option_formset.is_valid():
option_formset.save()
return redirect(profile)
form = NewCarsForm()
picture_formset = PicturesFormset(instance=Cars())
option_formset = CarsOptionsFormset(instance=Cars())
return render(request, 'add_car.html', {
'form': form,
'picture_formset': picture_formset,
'option_formset': option_formset,
})
template
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<h4>Car:</h4>
{{ form.as_p }}
<h4>Picture:</h4>
{{ picture_formset.as_p }}
<h4>Options:</h4>
{{ option_formset.as_p }}
<input type="submit" value="Submit">
</form>