can not upload the images - python
why I can not upload the images??
The urls.py:
see the
url(r'^things,,,
from django.conf.urls import include, url
from django.contrib import admin
from collection import views
from django.views.generic import TemplateView
from django.views.generic import (TemplateView,RedirectView,)
from collection.backends import MyRegistrationView
from django.contrib.sitemaps.views import sitemap
from collection.sitemap import (
ThingSitemap,
StaticSitemap,
HomepageSitemap,
)
sitemaps = {
'things': ThingSitemap,
'static': StaticSitemap,
'homepage': HomepageSitemap,
}
from django.contrib.auth.views import (
password_reset,
password_reset_done,
password_reset_confirm,
password_reset_complete,
)
urlpatterns = [
url(r'^$', views.index, name='home'),
url(r'^about/$',TemplateView.as_view(template_name='about.html'),name='about'),
url(r'^contact/$',views.contact, name='contact'),
url(r'^things/$', RedirectView.as_view(pattern_name='browse', permanent=True)),
url(r'^things/(?P<slug>[-\w]+)/$', views.thing_detail,name='thing_detail'),
url(r'^things/(?P<slug>[-\w]+)/edit/$', views.edit_thing,name='edit_thing'),
url(r'^things/(?P<slug>[-\w]+)/edit/images/$', views.edit_thing_uploads,name='edit_thing_uploads'),
url(r'^browse/$', RedirectView.as_view(pattern_name='browse', permanent=True)),
url(r'^browse/name/$',views.browse_by_name, name='browse'),
url(r'^browse/name/(?P<initial>[-\w]+)/$',views.browse_by_name, name='browse_by_name'),
url(r'^accounts/password/reset/$', password_reset,{'template_name':'registration/password_reset_form.html'},name="password_reset"),
url(r'^accounts/password/reset/done/$', password_reset_done,{'template_name':'registration/password_reset_done.html'},name="password_reset_done"),
url(r'^accounts/password/reset/(?P<uidb64>[0-9A-Za-z]+)-(?P<token>.+)/$', password_reset_confirm,{'template_name':'registration/password_reset_confirm.html'},name="password_reset_confirm"),
url(r'^accounts/password/done/$', password_reset_complete,{'template_name':'registration/password_reset_complete.html'},name="password_reset_complete"),
url(r'^accounts/register/$',MyRegistrationView.as_view(),name='registration_register'),
url(r'^accounts/create_thing/$',views.create_thing,name='registration_register'),
url(r'^accounts/', include('registration.backends.simple.urls')),
url(r'^sitemap\.xml$', sitemap, {'sitemaps':sitemaps},name='django.contrib.sitemaps.views.sitemap'),
url(r'^admin/', include(admin.site.urls)),
]
from django.conf import settings
if settings.DEBUG:
urlpatterns += [
url(r'^media/(?P<path>.*)$','django.views.static.serve',{'document_root': settings.MEDIA_ROOT,}),
]
the views.py:
See the def edit_thing_uploads
from django.shortcuts import render,redirect
from django.contrib.auth.decorators import login_required
from django.http import Http404
from collection.forms import ThingForm,ContactForm,ThingUploadForm
from collection.models import Thing,Upload
from django.template.loader import get_template
from django.core.mail import EmailMessage
from django.template import Context
def index(request):
things = Thing.objects.all()
return render(request, 'index.html', {
'things':things,
})
def thing_detail(request, slug):
thing = Thing.objects.get(slug=slug)
social_accounts = thing.social_accounts.all()
uploads = thing.uploads.all()
return render(request, 'things/thing_detail.html',{
'thing':thing,
'social_accounts': social_accounts,
'uploads': uploads,
})
#login_required
def edit_thing(request, slug):
thing = Thing.objects.get(slug=slug)
if thing.user != request.user:
raise Http404
form_class = ThingForm
if request.method == 'POST':
form = form_class(data=request.POST, instance=thing)
if form.is_valid():
form.save()
return redirect('thing_detail', slug=thing.slug)
else:
form = form_class(instance=thing)
return render(request, 'things/edit_thing.html',{'thing':thing,'form':form,})
#login_required
def edit_thing_uploads(request, slug):
thing = Thing.objects.get(slug=slug)
if thing.user != request.user:
raise Http404
form_class = ThingUploadForm
if request.method == 'POST':
form = form_class(data=request.POST,files=request.FILES, instance=thing)
if form.is_valid():
Upload.objects.create(
image=form.cleaned_data['image'],
thing=thing,
)
return redirect('edit_thing_uploads', slug=thing.slug)
else:
form = form_class(instance=thing)
uploads = thing.uploads.all()
return render(request, 'things/edit_thing_uploads.html', {
'thing': thing,
'form': form,
'uploads': uploads,
})
def create_thing(request):
form_class = ThingForm
if request.method == 'POST':
form = form_class(request.POST)
if form.is_valid():
thing = form.save(commit=False)
thing.user = request.user
thing.slug = slugify(thing.name)
thing.save()
return redirect('thing_detail', slug=thing.slug)
else:
form = form_class()
return render(request, 'things/create_thing.html', {'form':form,})
def browse_by_name(request, initial=None):
if initial:
things = Thing.objects.filter(name__istartswith=initial)
things = things.order_by('name')
else:
things = Thing.objects.all().order_by('name')
return render(request, 'search/search.html', {'things':things,'initial':initial,})
def contact(request):
form_class = ContactForm
if request.method == 'POST':
form = form_class(data=request.POST)
if form.is_valid():
contact_name = form.cleaned_data['contact_name']
contact_email = form.cleaned_data['contact_email']
form_content = form.cleaned_data['content']
template = get_template('contact_template.txt')
context = Context({
'contact_name':contact_name,
'contact_email':contact_email,
'form_content':form_content,
})
content = template.render(context)
email = EmailMessage(
'New contact form submission',content,
'Your website <hi#weddinglovely.com>',['fnt437#gmail.com'],
headers = {'Reply-To':contact_email }
)
email.send()
return redirect('contact')
return render(request, 'contact.html', {'form': form_class, })
The forms.py:
from django import forms
class ThingForm(ModelForm):
class Meta:
model = Thing
fields = ('name','description',)
class ContactForm(forms.Form):
contact_name = forms.CharField(required=True)
contact_email = forms.EmailField(required=True)
content = forms.CharField(
required=True,
widget=forms.Textarea
)
def __init__(self, *args, **kwargs):
super(ContactForm, self).__init__(*args, **kwargs)
self.fields['contact_name'].label = "Your name:"
self.fields['contact_email'].label = "Your email:"
self.fields['content'].label = "What do you want to say?"
class ThingUploadForm(ModelForm):
class Meta:
model = Upload
fields = ('image',)
the edit_thing.html:
{% extends 'layouts/base.html' %}
{% block title %}
Edit {{ thing.name }} - {{ block.super }}
{% endblock %}
{% block content %}
<h1>Edit "{{ thing.name }}"</h1>
Edit images
<form role="form" action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
{% endblock %}
the edit_thing_uploads.html:
{% extends 'layouts/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="{{ uploads.image.url }}" alt="" />
{% endfor %}
<h2>Uploads 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 %}
the diirectory tree:
when I click in http://127.0.0.1:8000/things/another-things/edit/ is ok
however when I click the Edit images link to submit upload images it said no file has been choice?? I can not upload the images
You have to check the file permissions of
edit_thing_uploads.html
, make sure the file is accessible. because the path has been correct. and Django can't see it.
I got to know why ,,because I typos <form role="form" action="" method="post" enctype="multipart/form-data"> ---> <form role="form" action="" method="post" enctype="multipart/form\-data"> in edit_thing_uploads.html
Related
The view budget.views.budget didn't return an HttpResponse object. It returned None instead
I recently added second form to my project and im struggling to make it work. The form is named AddIncome and when i fill the form and submit nothing happen, i don't see the new income. When i fill the income from admin panel on model page everthing works. Don't know how to make it work from main page. Here is my view (second form that i added is b_form, a_form is working): from django.contrib import messages from django.contrib.auth.decorators import login_required from django.core.paginator import Paginator from django.db.models import Sum from django.http import HttpResponseRedirect from django.shortcuts import get_object_or_404, redirect, render from django.urls import reverse from django.utils import timezone from .forms import AddIncome, AddItem from .models import BudgetData #login_required def budget(request): expense_items = BudgetData.objects.filter(user_expense=request.user).order_by( "-date_added" ) # Setting up pagination per expense_items paginator = Paginator(expense_items, 10, 3) # Show 10 items per page. page_number = request.GET.get("page") page_obj = paginator.get_page(page_number) total_cost = BudgetData.objects.filter(user_expense=request.user).aggregate( Sum("cost") ) total_income = BudgetData.objects.filter(user_expense=request.user).aggregate( Sum("income") ) # AddItem{category, cost} form a_form = AddItem() b_form = AddIncome() # form = AddItem(use_required_attribute=False) # ignores the field required text if request.method == "POST" and "expense" in request.POST: a_form = AddItem(request.POST) if a_form.is_valid(): a_form = a_form.save(commit=False) a_form.user_expense = request.user a_form.date_added = timezone.now() a_form.save() return HttpResponseRedirect(reverse("budget")) if request.method == "POST" and "income" in request.POST: b_form = AddIncome(request.POST) if b_form.is_valid(): b_form = b_form.save(commit=False) b_form.user_expense = request.user b_form.date_added = timezone.now() b_form.save() return HttpResponseRedirect(reverse("budget")) return render( request, "budget/budget.html", context={ "user": request.user, "expense_items": expense_items, "total_cost": total_cost, "total_income": total_income, "a_form": a_form, "b_form": b_form, "page_obj": page_obj, }, ) The template section: <section> <div class="form-group"> <form method="post"> {% csrf_token %} {{ b_form|crispy }} <input name="income" type="submit" value="Add income"> </form> </div> <div class="form-group"> <form method="post"> {% csrf_token %} {{ a_form|crispy }} <input name="expense" type="submit" value="Add item"> </form> </div> {% for key, value in total_cost.items %} <h1>Total expenses: {{value|floatformat:2}} zł</h1> {% endfor %} {% for key, value in total_income.items %} <h1>Total income: {{value|floatformat:2}} zł</h1> {% endfor %} <h1>Diff: 500 zł</h1> </section>
Django change password link is not active?
I am learning an authentication in Django. Today I am stuck with this problem and I am not able to figure out how can I solve it. I want to make a form for password change. but the change form link is not active and I don't know how to fix it. here is my views.py #login_required def user_change(request): current_user = request.user form = UserProfileChange(instance = current_user) if request.method == 'POST': form = UserProfileChange(request.POST,instance = current_user) if form.is_valid(): form.save() form = UserProfileChange(instance = current_user) form = UserProfileChange(instance = current_user) return render(request, 'App_Login/change_profile.html', context={'form':form}) #login_required def pass_change(request): current_user = request.user form = PasswordChangeForm(current_user) if request.method == 'POST': form = PasswordChangeForm(current_user, data = request.POST) if form.is_valid(): form.save() return render(request, 'App_login/pass_change.html', context = {'form':form}) here is urls.py file from django.urls import path from . import views app_name = 'App_Login' urlpatterns = [ path('signup/', views.signup, name = "signup"), path('signin/', views.login_page, name = 'signin'), path('logout/' , views.logout_user, name = "logout" ), path('profile/' , views.profile, name = "profile" ), path('change-profile/' , views.user_change, name = "user_change" ), path('password/' , views.pass_change, name = "pass_change" ), ] here is change_profile.html {% extends 'base.html' %} {% load crispy_forms_tags %} {% block title %} change User profile {% endblock %} {% block body_block %} <h2>Change Profile</h2> <form method="post"> {% csrf_token %} {{form|crispy}} <input type="submit" value="Change" class = "btn btn-primary btn-sm"> </form> {% endblock %} here is forms.py file from django import forms from django.contrib.auth.forms import UserCreationForm, UserChangeForm from django.contrib.auth.models import User class SignupForm(UserCreationForm): email = forms.EmailField(label = "Email Address", required=True) class Meta: model = User fields = ('username','email', 'password1', 'password2') class UserProfileChange(UserChangeForm): class Meta: model = User fields = ('username','email','first_name', 'last_name', 'password')
Django has an inbuilt functionality to do that in your urls file modify it to according your needs from django.contrib.auth import views as auth_views urlpatterns = [ # # Rest Of Your Code # path('password/',auth_views.PasswordChangeView.as_view( template_name='template to render here', success_url = 'page to redirect after password is changed'),name='password') ]
Django showing percentage of task completed/total task
I'm trying to make a simple django app which is like a todo app, I want to add the percentage of task completed. Here's my model.py from django.db import models from django.urls import reverse class Task(models.Model): title = models.CharField(max_length=200) create_time = models.DateTimeField(auto_now_add=True) complete_time = models.DateTimeField(blank=True, null=True) status = models.BooleanField(default=False) def __str__(self): return self.title and here's the template file <form method="POST" action="/"> {% csrf_token %} {{form}} <input class="btn submit" type="submit" name="save"> </form> {% for task in tasks %} {% if task.status == True %} <strike>{{task}}, {{task.complete_time}}</strike> {% else %} {% endif %} {% endfor %} and this is views.py file def list(request): queryset = Task.objects.order_by('complete_time','complete_time') if request.method =='POST': form = TaskForm(request.POST) if form.is_valid(): form.save() return redirect('/') context = { 'tasks':queryset, 'form':form, } return render(request, 'tasklist.html', context)
use a class-based view in views.py from django.views.generic.list import ListView class list(ListView): model = Task template_name = 'tasl_list.html' def get_context_data(self, *args, **kwargs): context = super().get_context_data(**kwargs) context['get_percentage_done'] = Task.objects.filter(status = True).count() * 100 / Task.objects.all().count() return context in your template {{get_percentage_done}}
Django edit comment
So i want to do a edit existing comment, but it gives me this error ValueError at /episode/Dragon-Ball-Super/edit/11 The view home.views.edit_comment didn't return an HttpResponse object. It returned None instead. edit_comment def edit_comment(request, slug, id): anime = get_object_or_404(Anime, slug=slug) comment = get_object_or_404(Comment, id=id) form = CommentForm(request.POST, instance=comment.user) if request.method == 'POST' or 'NONE': if form.is_valid(): form.save() return redirect('anime_title', slug=slug) else: form = CommentForm() context = {'form': form} return render(request, 'home/edit-comment.html', context) urls.py urlpatterns = [ path('', views.index, name='index'), re_path(r'^episode/(?P<slug>[\w-]+)/$', views.anime_title, name='anime_title'), re_path(r'^episode/(?P<slug>[\w-]+)/comment/$', views.add_comment, name='add_comment'), re_path(r'^episode/(?P<slug>[\w-]+)/edit/(?P<id>\d+)/?', views.edit_comment, name='edit_comment'), ] link under existing comment {% if comment.user == request.user.userprofile %} <h6 class="small comment-meta"> Edit Delete</h6> {% endif %} models.py class Comment(models.Model): anime = models.ForeignKey(Anime, on_delete=models.CASCADE) user = models.ForeignKey(UserProfile, on_delete=models.CASCADE) body = models.TextField() created = models.DateTimeField(auto_now_add=True) edit-comment.html {% extends 'base/base.html' %} {% block head %} <title>Edit Comment</title> {% endblock %} {% block content %} <h2>Edit Comment</h2> <form method="POST"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> {% endblock %}
You are handling only the POST request. GET request will be placed the first time when you load the form. def edit_comment(request, slug, id): anime = get_object_or_404(Anime, slug=slug) comment = get_object_or_404(Comment, id=id) form = CommentForm() if request.method == 'POST': form = CommentForm(request.POST, instance=comment.user) if form.is_valid(): form.save() return redirect('anime_title', slug=slug) return render(request, 'home/edit-comment.html', {'form':form})
Take In Input from User and Display the same input on the same page
Hi i am trying to create a post form in django where the user creates a post and the post is displayed back to them on the same page so far i have been unsuccessful. My articles display on the page but the form to post articles doesnt only the submit button shows. views.py def articles(request): args = {} args.update(csrf(request)) args ['posts'] = post.objects.filter(user = request.user) args ['full_name'] = User.objects.get(username = request.user.username) return render_to_response('articles.html', args) def article(request, post_id=1): return render(request, 'article.html', {'post': post.objects.get(id=post_id) }) def create(request): if request.POST: form = PostForm(request.POST, request.FILES) if form.is_valid(): a = form.save(commit=False) a.user = User.objects.get(username = request.user.username) a.save() messages.add_message(request, messages.SUCCESS, "You Article was added") return HttpResponseRedirect('/posts/all') else: form = PostForm() args = {} args.update(csrf(request)) args['form'] = form return render_to_response('articles.html', args) articles.html <form action="/posts/create/" method="post" enctype="multipart/form-data">{% csrf_token %} <ul> {{form.as_ul}} </ul> <input type="submit" name="submit" value="Create Article"> </form> {% if posts.count > 0 %} {% for post in posts %} <div> <h2>{{full_name}}</h2> <p>{{ post.body|lower|truncatewords:50 }}</p> <p>{{post.likes}} people liked this article</a></p> </div> {% endfor %} {% else %} <p>None to show!</p> {% endif %} {% endblock %} urls.py from django.conf.urls import patterns, include, url urlpatterns = patterns('', url(r'^create/$', 'posts.views.articles'), url(r'^get/(?P<post_id>\d+)/$', 'posts.views.article'), url(r'^create/$', 'posts.views.create'), url(r'^like/(?P<post_id>\d+)/$', 'posts.views.like_article'), url(r'^article/(?P<post_id>\d+)/$', 'posts.views.add_comment'), )
First off you aren't passing the form to the template in articles(). You need to have something along the lines of: args['form'] = YourForm() In your first view function. Also, in your create view you do this: a.user = User.objects.get(username = request.user.username) Which does an unnecessary database lookup of the user again, you can just do this to be clearer and faster: a.user = request.user