delete function need write user into useredit - django-models

every one I got
models.py
....
class ProductsTbl(models.Model):
.....
slug = models.SlugField(unique=True)
user = models.ForeignKey(User, blank=True, null=True)
useredit = models.CharField(max_length=32, blank=True, null=True)
image = models.ImageField(upload_to=get_imagep_Product, blank=True)
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created = timezone.now()
return super(ProductsTbl, self).save(*args, **kwargs)
def get_image_path(instance, filename):
return '/'.join(['thing_images', instance.thing.slug, filename])
class Upload(models.Model):
thing = models.ForeignKey(ProductsTbl, related_name="uploads")
image = models.ImageField(upload_to=get_image_path) #delete or upload image for this one
def save(self, *args, **kwargs):
super(Upload, self).save(*args, **kwargs)
if self.image:
image = Image.open(self.image)
i_width, i_height = image.size
max_size = (640,480)
if i_width > 1000:
image.thumbnail(max_size, Image.ANTIALIAS)
image.save(self.image.path)
and I got the views.py function it is for delete the image in class Upload(models.Model) of models.py,
views.py
.....
#login_required
def delete_upload(request, id):
# grab the image
upload = Upload.objects.get(id=id)
upload.thing.useredit = request.user.username
upload.save()
# security check
# if upload.thing.user != request.user:
# raise Http404
# delete the image
upload.delete()
# refresh the edit page
return redirect('edit_thing_uploads', slug=upload.thing.slug)
what I have to do is when I delete the image I have to write the "user" into the
"useredit".
however,,when never I delete the image the "user" won't write into "useredit"
,,in contrast,here is my
edit_thing_uploads.html
{% extends 'base.html' %}
{% block title %}
Edit {{ thing.name }}'s Images - {{ block.super }} {% endblock %}
{% block content %}
<h1>Edit {{ thing.name }}'s Images</h1>
<h2>Uploaded images</h2>
{% for upload in uploads %}
<img src="{{ upload.image.url }}" alt="" />
Delete
{% endfor %}
<h2>Upload a new image</h2>
<form role="form" action="" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock %}
when I upload an image it will write "user" into "useredit" successfully ,,the function for upload image in
views.py
#login_required
def edit_thing_uploads(request, slug):
# grab the object...
thing = ProductsTbl.objects.get(slug=slug)
# double checking just for security
# if thing.user != request.user:
# raise Http404
form_class = ProductsTblUploadForm
# if we're coming to this view from a submitted form,
if request.method == 'POST':
# grab the data from the submitted form, # note the new "files" part
form = form_class(data=request.POST,files=request.FILES, instance=thing)
if form.is_valid():
thing = form.save(commit=False)
thing.useredit = request.user.username
thing.save()
# create a new object from the submitted form
Upload.objects.create(
image=form.cleaned_data['image'],
thing=thing,
)
return redirect('edit_thing_uploads', slug=thing.slug)
# otherwise just create the form
else:
form = form_class(instance=thing)
# grab all the object's images
uploads = thing.uploads.all()
# and render the template
return render(request, 'things/edit_thing_uploads.html', {
'thing': thing,
'form': form,
'uploads': uploads,
})
however,,I have to let the "user" into "useredit" when I delete also,,,how can I do it? thank you!

I solve the problem
views.py
#login_required
def delete_upload(request, id):
# grab the image
upload = Upload.objects.get(id=id)
upload.thing.useredit = request.user.username
upload.thing.save()
# security check
# if upload.thing.user != request.user:
# raise Http404
# delete the image
upload.delete()
# refresh the edit page
return redirect('edit_thing_uploads', slug=upload.thing.slug)

Related

Routablepage of the BlogPage/category

I fail to display the routable index page for categories/given category.
My code uses:
-BlogCategory(model)
-BlogPageBlogCategory (page) an intemediary structure that links to:
-PostPage(page)
I can pass the code to the post_page template, but when I click on a specific category link I get:
Reverse for 'post_by_category' with arguments '('',)' not found. 1 pattern(s) tried: ['category/(?P<category>[-\\w]+)/$']
In the following post #gasman wrote: "the routablepageurl tag has received an empty string". I couldn't find the 'empty' string/missing link.
I assume it's related to the route of my 'def post_by_category'. Any input that would help me deepen my learning woulg be great.
NB - in case it helps, when I run this procedure without the intemeiary page all's fine. I can display the BlogPage/given_category once I click on the category in the PostPage.
Here's my code:
Models
class BlogPage(RoutablePageMixin, Page):
...
def get_context(self, request, *args, **kwargs):
context = super().get_context(request, *args, **kwargs)
context["posts"] = posts
return context
def get_posts(self):
return PostPage.objects.descendant_of(self).live().order_by("-post_date")
#route(r'^category/(?P<category>[-\w]+)/$')
def post_by_category(self, request, category, *args, **kwargs):
self.posts = self.get_posts().filter(categories__blog_category__slug=category)
context["categories"] = BlogCategory.objects.all()
return self.render(request)
class PostPage(MetadataPageMixin, Page):
...
content_panels = Page.content_panels + [
...
InlinePanel("categories", label="category"),
...
def get_context(self, request, *args, **kwargs):
context = super().get_context(request, *args, **kwargs)
return context
class PostPageBlogCategory(models.Model):
page = ParentalKey(
"blog.PostPage", on_delete=models.CASCADE, related_name="categories"
)
blog_category = models.ForeignKey(
"blog.BlogCategory", on_delete=models.CASCADE, related_name="post_pages"
)
panels = [
SnippetChooserPanel("blog_category"),
]
class Meta:
unique_together = ("page", "blog_category")
#register_snippet
class BlogCategory(models.Model):
name = models.CharField(max_length=255)
slug = models.SlugField(unique=True, max_length=80)
panels = [
FieldPanel('name'),
FieldPanel("slug"),
]
def __str__(self):
return self.name
class Meta:
verbose_name_plural = 'categories'
The post_page.html:
{% extends "base.html" %}
{% load wagtailroutablepage_tags %}
...
{% for category in page.categories.all %}
<li>
<a href="{% routablepageurl blog_page "post_by_category" category.slug %}">
{{ blog_category.name }}
</a>
</li>
{% empty %}
No categories yet'
{% endfor %}
...
After debugging and testing, I didn't find any blank categories, (which doesn't mean there were none, but that I didn't find or deleted them Unintentionally).
I case it could help, what worked for me was adding the category_type at the beginning of my varaiable:
{{ category.blog_category.name }} rather than {{ blog_category.name }}
{% for category in page.categories.all %}
<a href="{% routablepageurl article_index_page "post_by_category" category.blog_category.slug %}" class="link-primary text-decoration-none">
{{ category.blog_category.name }}
</a>
{% empty %}
No categories yet'
{% endfor %}

How to display certain Wagtail page on the homepage?

I'm making a website where there should be a links to specific pages on the homepage. I'm using PageChooserPanel to do this, but cannot display certain page.
This is my code:
models.py
class HomePage(Page):
FeaturedPageTitle = models.CharField(
null=True,
blank=True,
max_length=255,
)
FeaturedPage = models.ForeignKey(
'wagtailcore.Page',
null=True,
blank=True,
on_delete=models.SET_NULL,
)
content_panels = Page.content_panels + [
MultiFieldPanel([
MultiFieldPanel([
FieldPanel('FeaturedPageTitle'),
PageChooserPanel('FeaturedPage'),
]),
],
]
def pages(self):
pages = StandardPage.objects.all()
return pages
class StandardPage(Page)
home_page.html
{% if page.featured_page %}
{{ page.featured_page_title }}
{% for page in page.pages %}
{% image page.image %}
{{page.title}}
{% endfor %}
{% endif %}
You have called your featured page fields FeaturedPageTitle / FeaturedPage, but used featured_page_title / featured_page on the template.
In Python, capitalisation / punctuation in variable names is significant - the normal convention is to use capitals (CamelCase) only for class names, and underscore_case for other variables.

Form submission error with request.user using a Class Based View and a custom ModelForm

I am trying to create a record through a form and it will not submit or pass the information to the database. I am sure that the user is showing up in the HTML but it is not being sent with the request.
I am able to successfully create a record using the interactive shell with no problem and the test that I wrote passes. Following the documentation (https://docs.djangoproject.com/en/2.2/topics/class-based-views/generic-editing/) and the link to add request.user (https://docs.djangoproject.com/en/2.2/topics/forms/modelforms/#django.forms.ModelForm)
Object/Model
class Event(models.Model, Activity):
id = models.UUIDField(
primary_key=True, default=uuid.uuid4, editable=False, unique=True)
name = models.CharField(max_length=500)
start_date = models.DateField(blank=True, null=True)
end_date = models.DateField(blank=True, null=True)
completion_date = models.DateField(blank=True, null=True)
description = models.TextField(blank=True, null=True)
private = models.BooleanField(default=True)
owner_id = models.ForeignKey(User, on_delete=models.CASCADE)
creation_date = models.DateField(auto_now_add=True)
last_modified = models.DateTimeField(auto_now=True)
created_at = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.id, self.description or ''
views.py
class EventCreate(LoginRequiredMixin, CreateView):
form_class = EventForm
template_name = 'app/event_form.html'
success_url = reverse_lazy('event_list')
def form_valid(self, form):
form.instance.owner_id = self.request.user
return super().form_valid(form)
forms.py
class EventForm(ModelForm):
class Meta:
model = Event
fields = ['name', 'start_date', 'end_date',
'completion_date', 'description']
def __init__(self, *args, **kwargs):
self.owner_id = kwargs.pop('user')
return super(EventForm, self).__init__(*args, **kwargs)
Hi apowell656 if you are using class-based in view you need specific the model class, your example like this:
class EventCreate(LoginRequiredMixin, CreateView):
form_class = EventForm
model = Event
template_name = 'app/event_form.html'
success_url = reverse_lazy('event_list')
def form_valid(self, form):
form.instance.owner_id = self.request.user
return super().form_valid(form)
Make the minimal working view and now the ModelForm is not needed.
#views.py
class EventCreate(CreateView):
model = EventForm
fields = ('name','start_date','end_date','completion_date','description')
success_url = reverse_lazy('event_list')
def form_valid(self, form):
form.instance.owner_id = self.request.user
return super().form_valid(form)
Sent the request to a barebones HTML document
<!doctype html>
<html lang="en">
<head>
<meta charset="utf-8">
<title>Simple HTML</title>
<meta name="description" content="Test Form">
</head>
<body>
<form method="POST" action="">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit!">
</form>
</body>
</html>
Result: the form submits.
Problem: a line of javascript was not playing nice. It has since been removed.

Adding tags with Django-Taggit

I have tried different tutorials for Django-taggit, but for some reason they all show how to add tags through Admin. I was wondering can I add tags using View and template while creating an instance of Model? or should I add tags to existing items only? Is there any recent tutorials for Django-Taggit or my be better app for Tags?
Their documentation is pretty swell. Once you have your model set up, you can use the tag field just like any other field in a form. It will automatically be set up to parse the tags.
Here is a very basic working example.
views.py
from django.shortcuts import render
from .models import NewspaperIndex
from .forms import NewIndexForm
def overview(request):
if request.method == "POST":
form = NewIndexForm(request.POST)
if form.is_valid():
form.save()
else:
form = NewIndexForm()
indexes = NewspaperIndex.objects.all()
context = {'form': form,
'indexes': indexes
}
return render(request, 'newsindex/overview.html', context)
models.py
from django.db import models
from taggit.managers import TaggableManager
class NewspaperIndex(models.Model):
title = models.CharField(max_length=200)
date = models.DateField()
abstract = models.TextField()
tags = TaggableManager()
def __str__(self):
return self.title
forms.py
import datetime
from django import forms
from django.forms import ModelForm
from .models import NewspaperIndex
class NewIndexForm(forms.ModelForm):
class Meta:
model = NewspaperIndex
fields = ['title', 'date', 'abstract', 'tags']
templates/newsindex/overview.html
<form class="" action="./" method="post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" name="submit" value="Submit">
</form>
If you would like to add a tag from a shell, try:
tag='tag to add'
post=NewspaperIndex.objects.all()[0] #pick an object, to add tag to
post.tags.add(tag)

Configuring MIME type

Hi I want to configure my mime type:
The MIME type for KML files is
* application/vnd.google-earth.kml+xml
How can I do this with google app engine? I generate KML on a template that looks like this:
<?xml version="1.0" encoding="UTF-8"?><kml xmlns="http://www.opengis.net/kml/2.2" xmlns:gx="http://www.google.com/kml/ext/2.2" xmlns:kml="http://www.opengis.net/kml/2.2" xmlns:atom="http://www.w3.org/2005/Atom">
<Document>{% for article in articles %}{% if article.geopt %}
<Placemark><name></name>
<description>
<![CDATA[{% if article.kmluri2view %}<img src="http://{{host}}/images/{{ article.kmluri2view.key.id }}.jpg">{% endif %} {{ article.title }} <br/>{{article.text}}]]></description><Point><coordinates>{{article.geopt.lon|floatformat:2}},{{article.geopt.lat|floatformat:2}}</coordinates></Point>
</Placemark>{% endif %}{% endfor %}
</Document>
</kml>
Updated the code I try set the MIME type like below. How can I verify it works?
class KMLHandler(webapp.RequestHandler):
def get(self):
start=datetime.datetime.now()-timedelta(days=10)#vary
host = os.environ.get("HTTP_HOST", os.environ["SERVER_NAME"])
logging.debug('host '+host)
count = int(self.request.get('count')) if not self.request.get('count')=='' else 1000
from google.appengine.api import memcache
memcache.flush_all()
memcache_key = "ads"
data = memcache.get(memcache_key)
if data is None:
a= Ad.all().filter("modified >", start).filter("url IN", ['www.koolbusiness.com']).filter("published =", True).order("-modified").fetch(count)
memcache.set("ads", a)
else:
a = data
dispatch='templates/kml.html'
template_values = {'a': a , 'request':self.request, 'host':host}
path = os.path.join(os.path.dirname(__file__), dispatch)
self.response.headers['Content-Type'] = 'application/vnd.google-earth.kml+xml'
self.response.out.write(template.render(path, template_values))
Simply set the Content-Type header in the response to the mimetype you want. If you're using webapp, for instance, you do it like this:
self.response.headers['Content-Type'] = 'application/vnd.google-earth.kml+xml'

Resources