This is my models.py file
class Report_item(models.Model):
owner = models.ForeignKey(settings.AUTH_USER_MODEL)
title = models.CharField(max_length=255, help_text='*Title for the post e.g. item identity')
item_type = models.CharField(default="", max_length=100,
help_text='*Enter the item name you found e.g. Marksheet,key,wallet')
location = models.CharField(max_length=60, help_text='*Enter the address/street where you find this item')
city = models.CharField(max_length=60, help_text='*Enter the city name')
date = models.DateTimeField(default=timezone.now)
Description = models.TextField(blank=True,null=True,help_text='*Enter full description about item')
publish = models.BooleanField(default=False)
image = models.ImageField(default="add Item image",
help_text='*Please uplocad a item image to identify by the owner')
def __str__(self):
return self.title + " " + str(self.publish)
def get_absolute_url(self):
return reverse('feed:detail', kwargs={'pk': self.pk})
class Meta:
ordering = ["-date"]
This is my upload views:
class ReportCreate(generic.CreateView):
model = Report_item
fields = ['title', 'item_type', 'location', 'city', 'image', 'Description']
def form_valid(self, form):
self.object = form.save(commit=False)
self.object.owner = self.request.user
self.object.save()
return FormMixin.form_valid(self, form)
This is my view.py file
def IndexView(request):
query_list = Report_item.objects.filter(publish=True)
query = request.GET.get('q')
if query:
query_list = query_list.filter(Q(title__icontains=query) |
Q(item_type__icontains=query) |
Q(city__icontains=query) |
Q(location__icontains=query) |
Q(Description__icontains=query)).distinct()
context = {
"object_list": query_list
}
return render(request, "feed/index.html", context)
This is my feed/index file
{% for obj in object_list %}
<div class="thumbnail" onclick="window.open('{% url 'feed:detail' obj.id %}','mywindow');" style="cursor: pointer;">
<div class="row">
<div class="col-md-9">
<table class="mytable table-responsive">
<tr><td class="my-td-item">Title</td><td>{{ obj.title }}</td></tr>
<tr><td class="my-td-item">Item Type</td><td>{{ obj.item_type }}</td></tr>
<tr><td class="my-td-item">Location</td><td>{{ obj.location }}</td></tr>
<tr><td class="my-td-item">City</td><td>{{ obj.city }}</td></td></tr>
</table>
</div>
<div class="col-md-3">
<img class="img-responsive center" src="{{ obj.image.url }}" alt="backmyitem" width="80" height="100" style="margin: 0 auto;">
<br><b><p style="font-size: 10px;text-align:center;">Posted Date</b><br>{{ obj.date }}</p>
</div>
</div>
<div class="row">
<div class="more-detail-div col-md-12">
<a class="">More Detail</a>
</div>
</div>
</div>
{% endfor %}
When I upload an image from my laptop in my application, the image upload successfully and also images display in feed/index.html but at the same time when the same image I upload using my mobile phone or any other mobile devices then It causes the error. Even the image upload successfully but in the admin section as well as in the feed page image upload successfully and its name and path is also correct but is not display in admin as well as in the index file When I try to open the image in a new tab then it shows 403 forbidden.
The error in the ngin
2018/08/20 19:34:37 [error] 4498#4498: *89 open() "/home/ubuntu/media/153476127499997915256.jpg" failed (13: Permission denied), client: 103.201.$
x-error log is following:
Related
I am working on my project and the main idea is to add some items to the watchlist or "bookmark" some items:
when I render the page to see the watchlist that I add them by clicking on the "Add to watchlist button " Django give me this error:
NoReverseMatch at /watchlist/
Reverse for 'viewList' with arguments '('',)' not found. 1 pattern(s) tried: ['Post/(?P[0-9]+)$']
my code:
Model.py file
class Post(models.Model):
#data fields
title = models.CharField(max_length=64)
textarea = models.TextField()
#bid
price = models.FloatField(default=0)
currentBid = models.FloatField(blank=True, null=True)
imageurl = models.CharField(max_length=255, null=True, blank=True)
category = models.ForeignKey(Category, on_delete=models.CASCADE, default="No Category Yet!", null=True, blank=True)
creator = models.ForeignKey(User, on_delete=models.PROTECT)
date = models.DateTimeField(auto_now_add=True)
# for activated the Category
activate = models.BooleanField(default=True)
buyer = models.ForeignKey(User, null=True, on_delete=models.CASCADE, related_name="auctions_Post_creator")
############################### this is the watchers
watchers = models.ManyToManyField(User, blank=True, related_name='favorite')
def __str__(self):
return f"{self.title} | {self.textarea} | {self.date.strftime('%B %d %Y')}"
urls.py
urlpatterns =[
# Watchlist
path('Post/<int:id>/watchlist_post/change/<str:reverse_method>',
views.watchlist_post, name='watchlist_post'),
path('watchlist/', views.watchlist_list, name='watchlist_list')
path('Post/<int:id>', views.viewList, name='viewList'),
]
views.py
#start watchlist
def viewList(request, id):
# check for the watchlist
listing = Post.objects.get(id=id)
if listing.watchers.filter(id=request.user.id).exists():
is_watched = True
else:
is_watched = False
context = {
'listing': listing,
'comment_form': CommentForm(),
'comments': listing.get_comments.all(),
'Bidform': BidForm(),
# IS_WATCHED method
'is_watched': is_watched
}
return render(request, 'auctions/item.html', context)
#login_required
def watchlist_post(requset, id, reverse_method):
listing = get_object_or_404(Post, id=id)
if listing.watchers.filter(id=requset.user.id).exists():
listing.watchers.remove(requset.user)
else:
listing.watchers.add(requset.user)
if reverse_method == "viewList":
return viewList(requset, id)
return HttpResponseRedirect(reverse(reverse_method))
#login_required
def watchlist_list(request):
user = requset.user
watchers_items = user.favorite.all()
context = {
'watchers_items': watchers_items
}
return render(requset, 'auctions/watchlist.html', context)
HTML FILE: (item.html) this file for showing the post for exapmple : (title/ description/ date etc..)
<!-- check to add to watchlist -->
<div class="col">
{% if is_watched %}
Remove To Watchlist
<!-- remove it -->
{% else %}
Add To Watchlist
{% endif %}
</div>
HTML FILE (layout.html) for adding a link to the navbar for the page
<li class="nav-item">
<a class="nav-link" href="{% url 'watchlist_list' %}">Watchlist</a>
</li>
HTML FILE(whitchlsit page)
{% for post in watchers_items %}
<div class="col-sm-4">
<div class="card my-2">
<img src="{{post.imageurl}}" class="img-fluid">
<div class="card-body">
<div class="text-center py-2">
<h5 class="card-title text-info">{{post.title}}</h5>
<p class="alert alert-info">{{post.textarea}}</p>
<ul class="list-group">
<li class="list-group-item list-group-item-info">category: {{post.category.name}}</li>
<li class="list-group-item list-group-item-info">Price: {{post.price}}$</li>
<li class="list-group-item list-group-item-info">Created by: {{post.creator}}</li>
</ul>
</div>
<!-- Buttons -->
<div class="row">
<div class="col">
View
</div>
</div>
</div>
<div class="card-footer">
<small class="text-muted">Created since:{{post.date}}</small>
</div>
</div>
{% endfor %}
The culprit of this problem is that you are calling "{% url 'viewList' listing.id %}" even though viewList does not exist in your urls.py.
So, you can create one like this:
path("some/path", views.some_func, name="viewList")
EDIT
As the error says, listing.id is empty ({% url 'viewList' listing.id %}). So, you might want to do post.id instead because you are looping with the name of post.
I'm still a beginner in Django and building a management system, I wish to display content from the database using a for loop from 2 tables(GoCustomerRegisration and GoCustomerStatus). But unfortunately, when I iterate over one table the other table brings me only the last element of that table. What I really wish to do is iterate over both tables at once and each element should correspond to it on the other table.
Check out my code below:
something.html
{% for item in detail %}
<tr>
<td>
<a class="text-black text-decoration-none" href="{{ item.photo.url }}">
<img class="rounded-circle me-2" style="object-fit: contain; background-color:#91debb; border:1px solid palegreen;" alt="" width="30" height="30" src="{{ item.photo.url }}"></a>
</td>
<td>
<a class="text-black lg:hover:text-blue-400 text-decoration-none" href="{% url 'customer_detail' pk=item.id %}">{{ item.name }}</a>
</td>
<td class="text-capitalize">{{ item.type }}</td>
<td>{{ item.destination }}</td>
<td>{{ item.age }}</td>
<td>{{ item.time_of_submission }}</td>
<td>
<span>{{ hello.value }}%</span>
<div class="col">
<div class="progress progress-sm">
<div class="progress-bar progress-bar-striped bg-success" aria-valuenow="{{ hello.value }}" aria-valuemin="0" aria-valuemax="100" style="width: {{ h.value }}%;"><span class="visually-hidden"></span>
</div>
</div>
</div>
</td>
{% endfor %}
my views.py
#login_required
def preview(request):
global hello
detail = GoCustomerRegistration.objects.all()
next_event = Event.objects.last()
for i in range(1, (len(detail))+1):
print(i)
hello = GoCustomerStatus.objects.get(name_id=i)
print(hello)
context = {
'detail': detail,
'event': next_event,
'hello': hello,
}
return render(request, 'customers_preview.html', context)
my urls.py
from django.urls import path
urlpatterns = [
path('preview/', preview, name='preview'),
]
my models.py
class GoCustomerRegistration(models.Model):
name = models.CharField(max_length=300, verbose_name='Full name')
email = models.EmailField(null=False)
type = models.CharField(max_length=20, verbose_name='Customer Type')
destination = models.CharField(max_length=30, null=False, verbose_name='Destination')
time_of_submission = models.DateTimeField(auto_now_add=True, null=False, verbose_name=' Submit Time')
phone_number = models.IntegerField(verbose_name='Phone number')
age = models.IntegerField(verbose_name="Age", null=False)
photo = models.ImageField(max_length=10000, verbose_name='Customer Picture',
null=False, upload_to='customers/profiles/')
documents = models.FileField(upload_to='%Y/customers/documents/')
class Meta:
ordering = ["time_of_submission"]
verbose_name = "Customer Registration"
verbose_name_plural = "Customers Registration"
def __str__(self):
return self.name
class GoCustomerStatus(models.Model):
name = models.OneToOneField(GoCustomerRegistration,
max_length=300, verbose_name='Full name',
on_delete=models.CASCADE, primary_key=True,
null=False,
)
value = models.IntegerField(default=0, verbose_name='Level', null=False, primary_key=False)
class Meta:
verbose_name_plural = 'Customers Status'
verbose_name = 'Customer\'s Status'
def __str__(self):
return self.name.name
I have a dashboard of items displayed from my uniform model. I am attempting to send the item to a cart for checking out the item. I am not having issues loading my internal server, and I am getting no debugging issues. But when looking at my admin Order Item model, nothing has been pushed to it:
urls.py
from apparelapp import views
...
# TEMPLATE URLS
app_name = 'apparelapp'
urlpatterns = [
...
path('add_to_cart/<slug>/', views.add_to_cart, name="add_to_cart"),
...
]
views.py
# add to cart
def add_to_cart(request, slug):
item = get_object_or_404(Uniform, slug=slug)
order_item = OrderItem.objects.create(item = uniform)
order_qs = Transaction.objects.filter(user=request.user, ordered=False)
if order_qs.exists():
order = order_qs[0]
if transaction.items.filter(item__slug=item.slug).exists():
order_item.quantity += 1
order_item.save()
else:
transaction.item.add(item)
else:
ordered_date = timezone.now()
order = Transaction.objects.create(user=request.user, ordered_date = ordered_date)
order.items.add(order_item)
messages.success(request, "Added to cart!")
return redirect('apparelapp:item_list')
models.py
#OrderItem
class OrderItem(models.Model):
uniform = models.OneToOneField(Uniform, on_delete = models.PROTECT)
start_date = models.DateTimeField(auto_now_add=True)
ordered_date = models.DateTimeField(null = True)
quantity = models.IntegerField(default = 1)
def __str__(self):
return self.uniform.description
#Item
class Uniform(models.Model):
category = models.CharField(choices = CATEGORY_CHOICES, max_length=11)
description = models.CharField(max_length = 50)
price = models.FloatField(max_length = 6)
size = models.CharField(choices=CLOTHES_SIZE, max_length=4, blank=True)
style = models.CharField(choices=STYLE_CHOICES, max_length=15, blank=True)
image = models.ImageField(upload_to='uniforms/')
slug = models.SlugField()
class Meta:
ordering = ['category']
def __str__(self):
return '{}: {} - {} - ${}'.format(self.category, self.description, self.size, self.price)
def add_to_cart_url(self):
return reverse("apparelapp:add_to_cart", slug=slug)
html
<h2>List of items</h2>
<section class="text-center mb-4">
<div class="row wow fadeIn">
{% for item in object_list %}
<div class="col-lg-3 col-md-6 mb-4">
<div class="card">
<div class="view overlay">
<img src="{{ item.image.url }}" alt="Oh no!" width="200" height="200">
<a>
<div class="mask rgba-white-slight"></div>
</a>
</div>
<div class="card-body text-center">
<label>
<h5>{{ item.description }}</h5>
</label>
<h5>
{% if object.description %}
<strong>
<label for="">{{ item.category }}</label>
</strong>
{% endif %}
</h5>
<div class="row">
<div class="col-lg-2">
Size
</div>
<div class="col-lg-10">
Add to Cart
</div>
</div>
</div>
</div>
</div>
{% endfor %}
</div>
Initially I tried out the button once adding an item and it worked, but wouldn't add any additinoal items, now the link doesn't work as a whole. Am I missing something in my views.py?
You can easily use name attribute of path element of your urlpatterns list to navigate through project without changing url itself, if needed. To use this feature, you can specify url template tag with syntax like:
{{ url '<name_of_path_element>' arg1=arg.data }}
Where is name attribute of path element of your urlpatterns, like I said above; and arg1 is not required argument to pass as query string, and, arg.data is data to be passed.
HTML
<div class="col-lg-10">
Add to Cart
</div>
Please, let me know if it doesn't work.
Django blog posts not appearing
I am new to Django and am trying to return a list of published blog posts.
The page is appearing and no errors are produced, however no posts are showing. I have checked in the admin page and all posts are published.
Model:
class BlogPost(models.Model):
title = models.CharField(max_length=200)
snippet = models.CharField(max_length=400, null=True)
Blog_pic = models.ImageField(upload_to='blog_pics',blank=True)
hero_pic = models.ImageField(upload_to='blog_pics',blank=True)
content = models.TextField()
blogcategory = models.CharField(max_length=200, default='uncategorised')
create_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 get_absolute_url(self):
return reverse("BlogPost_detail",kwargs={'pk':self.pk})
Views:
class BlogPostListView(ListView):
model = BlogPost
def get_queryset(self):
return BlogPost.objects.all().order_by('-published_date')
class BlogPostDetailView(DetailView):
model = BlogPost
Template:
{% for BlogPost in BlogPost_list %}
<div class="col-sm-6">
<a href="{% url 'BlogPost_detail' pk=BlogPost.pk %}">
<div class="card">
<img src="#">
<div class="">
<h4><span class="">{{ BlogPost.category }}</span></h4>
<p class="">{{ BlogPost.tile }}</p>
<p class="">{{ BlogPost.snippet }}</p>
<p style="">{{ BlogPost.published_date }</p>
<p style="">x min</p>
</div>
</div>
</a>
</div>
{% endfor %}
Let's say I have these models:
class Profile(models.Model):
headline = models.CharField(max_length=200)
class ProfilePhoto(models.Model):
photo = models.ImageField(upload_to='profiles/photos')
owner = models.ForeignKey(Profile, related_name='photos', on_delete=models.CASCADE)
type_choices = (
('PR', 'Primary'),
('AD', 'Additional'),
)
type = models.CharField(max_length=2, choices=type_choices, default='AD')
and the following view:
def profiles(request):
# Retrieve all active profiles
profiles = Profile.objects.filter(status='AC').order_by('-updated_at')#.filter(photos__)
context = {'profiles': profiles}
return render(request, 'profiles.html', context)
and this in my template file:
{% for profile in profiles %}
<div class="col-lg-6 col-md-6 col-sm-6 col-xs-12">
<div class="panel panel-default">
<div class="panel-body">
<p>{{ profile.headline }}</p>
<img src="{{ MEDIA_URL }}profiles/thumbs/{{ profile.photos.first.photo }}">
</div>
</div>
</div>
{% endfor %}
Here I get one photo for each profile because of profile.photos.first.photo in the template but what I want instead is to select a single photo for each profile with the condition that it has a type of 'PR'. Any help would be appreciated.
You can use a model method. Something like this:
class Profile(models.Model):
headline = models.CharField(max_length=200)
#property
def primary_profile_photo(self):
primary_photo = self.photos.filter(type='PR').order_by('?').first()
return primary_photo.photo
That would get you a random (order_by='?') photo, with type PR, that you could then access as primary_profile_photo in the template.