I have a problem with the image uploading from form (when i upload image from admin panel it works). Image just dont uploading, without any feedback and log. Help me pls
My view.py:
def class_article_create(request, URLcodenumber):
print(URLcodenumber)
if request.method == 'POST':
model = Article()
form = ArticleForm(
request.POST,
instance=model
)
print(request.method)
new_article = form.save(commit=False)
new_article.codenumber = Classes.objects.filter(
codenumber=URLcodenumber
)[0]
new_article.pub_date = date.today()
print(new_article.id)
if form.is_valid():
new_article.save()
return HttpResponseRedirect(f'/class/{URLcodenumber}')
return render(
request,
'blogpage\\create_article.html',
{
'clsName': f'Параллель {URLcodenumber}',
'codenumber': URLcodenumber,
'form': ArticleForm()
}
)
My models.py:
class Article(models.Model):
id = models.UUIDField(
primary_key=True,
default=uuid.uuid4,
editable=False
)
headline = models.CharField(
max_length=50,
default='Нет заголовка'
)
text = models.TextField(
max_length=600,
)
image = models.ImageField(
upload_to='images/',
blank=True
)
pub_date = models.DateField()
codenumber = models.ForeignKey(
'Classes',
on_delete=models.CASCADE
)
create_article.html
{% extends "blogpage\layout\base.html" %}
{% load static %}
{% block title %}
Добавление ответа
{% endblock title %}
{% block nav %}
<div class="classname-div">
<p class="cls-name" align="center">{{clsName}}</p>
</div>
<a href='{% url "classpage_articles_preview" URLcodenumber=codenumber %}'>
<button class="btn-to-page">Перейти к ответам</button>
</a>
{% endblock nav %}
{% block content %}
<form method="post" class="model-form" enctype="multipart/form-data">
{% csrf_token %}
{{form.headline}}
{{form.text}}
{{form.image}}
<button class="model-form-submit" type="submit">
Добавить
</button>
</form>
{% endblock content %}
early, there wasnt the enctype="multipart/form-data", and the problem was same
media root and url in settings.py:
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media/')
urls.py:
from django.contrib import admin
from django.urls import path
from django.urls import re_path
from django.conf import settings
from django.conf.urls.static import static
from help_page.helppage_views import help_page
from start_page import startpage_views
from help_page import helppage_views
from class_page import classpage_views
urlpatterns = [
path('admin/', admin.site.urls),
path(
'',
startpage_views.start_page,
name='startpage'
),
path(
'help/<numpage>/',
helppage_views.help_page,
name='helppage'
),
path(
'class/<URLcodenumber>/',
classpage_views.class_article_preview,
name='classpage_articles_preview'
),
path(
'create/<URLcodenumber>',
classpage_views.class_article_create,
name='classpage_articles_create'
),
path(
'view/<URLcodenumber>/<uuid:uuid>',
classpage_views.class_article_view,
name='classpage_article_view'
),
path(
'createclass',
classpage_views.create_class,
name='create_class'
)
] + static(
settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT
)
proj_dir => media => images is directory for the images
Thanks for any help! :)
You need to pass both request.POST and request.FILES to the form:
from django.shortcuts import get_object_or_404
def class_article_create(request, URLcodenumber):
if request.method == 'POST':
code_number = get_object_or_404(Classes, codenumber=URLcodenumber)
form = ArticleForm(request.POST, request.FILES)
if form.is_valid():
form.instance.codenumber = code_number
form.instance.pub_date = date.today()
form.save()
return HttpResponseRedirect(f'/class/{URLcodenumber}')
else:
form = ArticleForm()
return render(
request,
'blogpage/create_article.html',
{
'clsName': f'Параллель {URLcodenumber}',
'codenumber': URLcodenumber,
'form': form,
},
)
Note: Django's DateTimeField [Django-doc]
has a auto_now_add=… parameter [Django-doc]
to work with timestamps. This will automatically assign the current datetime
when creating the object, and mark it as non-editable (editable=False), such
that it does not appear in ModelForms by default.
Related
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')
]
I would like to create user specific links. I mean, when user signed up and logged in, he has redirected to create/ page. In that page user fills out the form and after pressing button, user has to redirect to list/ page, where there are user specific links to specific page, which contain schedule. Schedul appered from data, which user provided in create/ form.
So my problem is, when I filled out the form and redirect to list/ page, there are no links.
My code:
models.py
from django.db import models
from django.contrib.auth.models import User
class File(models.Model):
file = models.OneToOneField(User, on_delete=models.CASCADE, null=True)
#Further, they are fileds, which is nececary to create schedule.
#title = models.CharField('Название Графика', max_length = 50)
#x_title = models.CharField('Название Оси Х', max_length = 50)
#y_title = models.CharField('Название Оси Y', max_length = 50)
#etc...
views.py:
def create(request):
error = ''
if request.method == 'POST':
form = FileForm(request.POST)
if form.is_valid():
form.save()
return redirect('grafic:list')
else:
error = 'Форма была неверной('
form = FileForm()
data = {
'form': form,
'error': error,
}
return render(request, 'graf/create.html', data)
def list(request):
qs = File.objects.filter(file=request.user)
context = {
'user': request.user,
'qs': qs,
}
return render(request, 'graf/list.html', context)
list.html
{% extends 'base.html' %}
{% block content %}
{% if user.is_authenticated %}
<h2>{% block title %} Profile {% endblock %}</h2>
<p>Username: {{ user }}</p>
{% for b in qs %}
<article class="card">
<div class="card_wrapper">
<figure class="card_feature">
</figure>
<div class="card_box">
<a href="{% url 'grafic:index' b.id %}">
<header class="card_item card_header">
<h6 class="card__item card__item--small card__label">Твой график</h6>
<a class="card__item card__item--small card__title" href="{% url 'grafic:index' b.id %}">
{{b.graf_title}}
</a>
</header>
<hr class="card__item card__divider">
</a>
</div>
</div>
</article>
{% endfor %}
{% endif %}
{% endblock %}
urls.py
from django.urls import path
from . import views
app_name = 'grafic'
urlpatterns = [
path('', views.first, name = 'first'),
path('create/', views.main, name = 'main'),
path('list/', views.list, name = 'list'),
path('files/<int:grafics>', views.index, name = 'index'),
path('login/', views.loginpage, name = 'loginpage'),
path('register/', views.registerpage, name = 'registerpage'),
]
That's all. Sorry if my code is such inconvenient. Thank you in advance for your cooperation)
enter image description here
That is my problem. In the 'file' field there are no user.
I am following a tutorial explainig how to build an eCommerce app with django.
I have a cart section [s1] where the customer can see the resume of the products he/she has in the cart.
Here the customer can click on a "checkout" button that, according to the tutorial,
if the customer is logged in:
should lead him/her to a shipping address section [s2] where he/she can fill the shipping address form.
else:
should lead him/her to a guest authentication section [s2-b] where he/she can continue as guest (the customer is requested to submit his/her email address) or login (the customer is requested to submit user and password) and then reaches the shipping address form section [s2].
Then the app should lead the customer to a billing address form [s3] and then to a finalizing section [s4].
My problem is that I can't go past the shipping address section [s3], because as I click on the submit button, the app redirects me to the login form, (this happens even if I am already logged in) where the message "This field is required" appears for both user and password files, and as I type those in and press Submit button, the app returns me back to the home page. So I can never reach billing address form [s4].
I don't understand what is wrong, here is my code:
carts, billing and addresses are my apps
carts/views.py
from django.shortcuts import render, redirect
from products.models import Product
from .models import Cart
from orders.models import Order
from accounts.forms import LoginForm
from billing.models import BillingProfile
from accounts.forms import GuestForm
from accounts.models import GuestEmail
from addresses.forms import AddressForm
from addresses.models import Address
def cart_home(request):
cart_obj, new_obj = Cart.objects.new_or_get(request)
return render(request, "carts/home.html", {"cart":cart_obj})
def cart_update(request):
print(request.POST)
product_id = request.POST.get('product_id', 100) # il 2° arg è il default
if product_id is not None:
try:
product_obj = Product.objects.get(id=product_id)
except Product.DoesNotExist:
print("product is gone?")
return redirect("cart:home")
cart_obj, new_obj = Cart.objects.new_or_get(request)
if product_obj in cart_obj.products.all():
cart_obj.products.remove(product_obj)
else:
cart_obj.products.add(product_obj)
request.session['cart_items'] = cart_obj.products.count()
return redirect("cart:home")
def checkout_home(request):
cart_obj, cart_created = Cart.objects.new_or_get(request)
order_obj = None
if cart_created or cart_obj.products.count() == 0:
return redirect("cart:home")
login_form = LoginForm()
guest_form = GuestForm()
address_form = AddressForm()
billing_address_id = request.session.get("billing_address_id", None)
shipping_address_id = request.session.get("shipping_address_id", None)
billing_profile = BillingProfile.objects.new_or_get(request)
if billing_profile is not None:
order_obj, order_obj_created = Order.objects.new_or_get(billing_profile, cart_obj)
if shipping_address_id:
order_obj.shipping_address = Address.objects.get(id=shipping_address_id)
del request.session["shipping_address_id"]
if billing_address_id:
order_obj.billing_address = Address.objects.get(id=billing_address_id)
del request.session["billing_address_id"]
if billing_address_id or shipping_address_id:
order_obj.save()
context = {
"object": order_obj,
"billing_profile": billing_profile,
"login_form": login_form,
"guest_form" : guest_form,
"address_form" : address_form,
}
return render(request, "carts/checkout.html", context )
addresses/views.py
from django.shortcuts import render, redirect
from .forms import AddressForm
from django.utils.http import is_safe_url
from billing.models import BillingProfile
def checkout_address_create_view(request):
form = AddressForm(request.POST or None)
context = {"form":form}
next_ = request.GET.get('next')
next_post = request.POST.get('next')
redirect_path = next_ or next_post or None
if form.is_valid():
print("form is valid")
print(request.POST)
instance = form.save(commit=False)
billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request)
if billing_profile is not None:
address_type = request.POST.get('address_type', 'shipping')
instance.billing_profile = billing_profile
instance.address_type = address_type
instance.save()
request.session[address_type + "_address_id"] = instance.id
print(address_type + "_address_id")
else:
print("error here smth")
return redirect("cart:checkout")
# redirect to success page
if is_safe_url(redirect_path, request.get_host()):
return redirect(redirect_path)
else:
return redirect("cart:checkout")
print("form is not valid")
return redirect("cart:checkout")
addresses/models.py
from django.db import models
from billing.models import BillingProfile
ADDRESS_TYPES = (
('billing', "billing"),
('shipping', "shipping"),
)
class Address(models.Model):
billing_profile = models.ForeignKey(BillingProfile, on_delete=models.CASCADE)
address_type = models.CharField(max_length=120, choices=ADDRESS_TYPES)
address_line_1 = models.CharField(max_length=120)
address_line_2 = models.CharField(max_length=120, null=True, blank=True)
city = models.CharField(max_length=120)
country = models.CharField(max_length=120, default="Italy")
state = models.CharField(max_length=120)
postal_code = models.CharField(max_length=120)
def __str__(self):
return str(self.billing_profile)
billing/models.py
from django.db import models
from django.conf import settings
# from python_ecommerce.utils import unique_order_id_generator
from django.db.models.signals import pre_save, post_save
from accounts.models import GuestEmail
User = settings.AUTH_USER_MODEL
class BillingProfileManager(models.Manager):
def new_or_get(self, request):
user=request.user
guest_email_id = request.session.get('guest_email_id')
created = False
obj = None
if user.is_authenticated:
obj, created = self.model.objects.get_or_create(
user=user,
email=user.email
)
elif guest_email_id is not None:
guest_email_obj = GuestEmail.objects.get(id=guest_email_id)
obj, created = self.model.objects.get_or_create(
email=guest_email_obj.email
)
else:
print("nè guest nè user")
return obj
class BillingProfile(models.Model):
user = models.OneToOneField(User, null=True, blank=True, on_delete=models.CASCADE) #OneToOneField
email = models.EmailField()
active = models.BooleanField(default=True)
update = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
# customer is in stripe or brwwin
objects = BillingProfileManager()
def __str__(self):
return self.email
def user_created_receiver(sender, instance, created, *args, **kwargs):
if created and instance.email:
BillingProfile.objects.get_or_create(user=instance, email=instance.email)
post_save.connect(user_created_receiver, sender=User)
python_ecommerce/urls.py
from django.contrib import admin
from django.urls import path, include
from .views import home_page, about_page, contact_page
from django.conf import settings
from django.conf.urls.static import static
from django.views.generic.base import TemplateView
from carts.views import cart_home
from accounts.views import login_page, register_page
from django.contrib.auth.views import LogoutView
from accounts.views import guest_register_view
from addresses.views import checkout_address_create_view
urlpatterns = [
path('admin/', admin.site.urls),
path('', home_page, name="home"),
path('about/', about_page, name="about"),
path('contact/', contact_page, name="contact"),
path('login/', login_page, name="login"),
path('register/', register_page, name="register"),
path('bootstrap/', TemplateView.as_view(template_name='bootstrap/example.html')),
path('', include("products.urls", namespace='products')), #spostato nell altro
path('', include("search.urls", namespace='search')),
path('cart/', include("carts.urls", namespace="cart")),
path("logout/", LogoutView.as_view(), name="logout"),
path('register/guest/', guest_register_view, name="guest_register"),
path('checkout/address/create/', checkout_address_create_view, name='checkout_address_create_view'),
]
if settings.DEBUG:
urlpatterns = urlpatterns + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns = urlpatterns + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
carts/templates/carts/checkout.html
{% extends "base.html" %}
{% block content %}
{{ object.order_id }}    {{ object.cart }}
{% if not billing_profile %}
<div class="row text-center">
<div class='col-12 col-md-6'>
<p class="lead">Login</p>
{% include 'accounts/snippets/form.html' with form=login_form next_url=request.build_absolute_uri %}
</div>
<br><br><br>
<div class='col-12 col-md-6'>
continue as guest
{% url 'guest_register' as guest_register_url %}
{% include 'accounts/snippets/form.html' with form=guest_form next_url=request.build_absolute_uri action_url=guest_register_url %}
</div>
<!-- qui è obbligatorio usare la struttura alias perchè non puoi mettere url tag dentro action_url= -->
</div>
{% else %}
{% if not object.shipping_address %}
<div class=row>
<div class='col-md-6 mx-auto col-10'>
<p class='lead'>Shipping Address</p>
<hr/>
{% url 'checkout_address_create' as checkout_address_create %}
{% include 'addresses/form.html' with form=address_form next_url=request.build_absolute_uri action_url=checkout_address_create address_type='shipping' %}
</div>
</div>
{% elif not object.billing_address %}
<div class=row>
<div class='col-md-6 mx-auto col-10'>
<p class='lead'>Billing Address</p>
<hr/>
{% url 'checkout_address_create' as checkout_address_create %}
{% include 'addresses/form.html' with form=address_form next_url=request.build_absolute_uri action_url=checkout_address_create address_type='billing' %}
</div>
</div>
{% else %}
<h1>Finalize checkout</h1>
<p>Cart total: {{ object.cart.total }}</p>
<p>Shipping total: {{ object.shipping_total }}</p>
<p>Order total: {{ object.total }}</p>
<button>Checkout</button>
{% endif %}
{% endif %}
{% endblock %}
SOLVED
There was a very simple error in python_ecommerce/urls.py:
In urlspattern I named checkout_address_create_view the view checkout_address_create_view, while in the template I call it as checkout_address_create, so the template could not find the function and don't know why was bringing me back to login form.
I substituted
path('checkout/address/create/', checkout_address_create_view, name='checkout_address_create_view'),
with
path('checkout/address/create/', checkout_address_create_view, name='checkout_address_create_view'),
and this solved that error.
if i upload the image through my admin dashboard, the image will be successfully uploaded, it will appear in media folder in my project directory i specified in settings.py. but if i upload an image through form.py as a user, every other field is saved except for the image field. I've tried most of the solutions on stackoverflow, dont know why mine ain't working.
while debugging i made mainimage a required field, so it threw this error: ValueError: The view products.views.products didn't return an HttpResponse object. It returned None instead.
form.py
from django import forms
from django.utils.translation import gettext_lazy as _
from .models import Product
class ProductForm(forms.ModelForm):
class Meta:
model = Product
fields = ['name', 'mainimage', 'category', 'preview_text',
'detail_text', 'price','Quantity']
labels = {
'name': _('Product name'),
}
help_texts = {
'name': _('be specific eg Tomatoes, Rice'),
}
error_messages = {
'name': {
'max_length': _("This writer's name is too long."),
},
}
views.py
from django.shortcuts import render, redirect
from .form import ProductForm
from .models import Product
# Create your views here.
def products(request):
if request.method == 'GET':
form = ProductForm()
return render(request, 'products/add_product.html',{'forms':form})
else:
# imagefield is different from other
# fields and it needs to be handles properly
# data fetched from imagefield would be stored
# in request.FILES object.
if request.method == 'POST':
form = ProductForm(request.POST or None, request.FILES or None)
if form.is_valid():
name = form.cleaned_data.get('name')
mainimage = form.cleaned_data.get('mainimage')
category = form.cleaned_data.get('category')
preview_text = form.cleaned_data.get('preview_text')
detail_text = form.cleaned_data.get('detail_text')
price = form.cleaned_data.get('price')
Quantity = form.cleaned_data.get('Quantity')
obj = Product.objects.create(
name = name,
mainimage = mainimage,
category = category,
preview_text = preview_text,
detail_text = detail_text,
price = price,
Quantity = Quantity
)
obj.save()
# form.save()
return redirect('/products/')
else:
form = ProductForm()
return render(request, 'add_product.html', {'form': form})
add_product
{% extends "plugs/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<h4>Add a Product</h4>
<form action="#" method="post" autocomplete="off" enctype="multipart/form-data">
{% csrf_token %}
<!-- {{form_store.store_name|as_crispy_field}}-->
<div class="col-md-3">
{{ forms.name|as_crispy_field }}
</div>
<div class="row">
<div class="col-md-4" >
{{ forms.mainimage|as_crispy_field }}
</div>
<div class="col-md-3">
{{ forms.category|as_crispy_field }}
</div>
</div>
<div class="col-md-5">
{{ forms.preview_text|as_crispy_field }}
{{ forms.detail_text|as_crispy_field }}
<!-- {{ forms.price|as_crispy_field }}-->
{{ forms.Quantity|as_crispy_field }}
</div>
<button type="submit" class="btn btn-success"><i class="fas fa-database"></i>Submit</button>
</form>
{% endblock %}
settings.py
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, '/static/media/')
STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),)
MEDIA_URL = '/media/'
models.py
from django.db import models
# Create your models here.
class Category(models.Model):
title = models.CharField(max_length= 300)
primaryCategory = models.BooleanField(default=False)
def __str__(self):
return self.title
class Product(models.Model):
mainimage = models.ImageField(upload_to='products/', blank=True)
name = models.CharField(max_length=300)
slug = models.SlugField(blank = True)
category = models.ForeignKey(Category, on_delete=models.CASCADE)
preview_text = models.TextField(max_length = 200, verbose_name='Preview Text')
detail_text = models.TextField(max_length= 1000, verbose_name='Detail text')
price = models.FloatField()
Quantity = models.CharField(max_length=150, default='1 quantity')
def __str__(self):
return self.name
project/urls.py
from django.contrib import admin
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.urls import path, include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('plugs.urls')),
path('products/', include('products.urls')),
path('home/', include('cart.urls')),
# path('products/', include('products.urls')),
]
urlpatterns += staticfiles_urlpatterns()
if settings.DEBUG:
urlpatterns +=static(settings.MEDIA_URL,
document_root = settings.MEDIA_ROOT)
ok better change your view to
if request.method == 'POST':
form = ProductForm(request.POST or None, request.FILES or None)
if form.is_valid():
instance = form.save(commit=False)
instance.name = form.cleaned_data['name']
instance.mainimage = form.cleaned_data['mainimage']
instance.category = form.cleaned_data['category']
instance.preview_text = form.cleaned_data['preview_text']
instance.detail_text = form.cleaned_data.get['detail_text']
instance.price = form.cleaned_data['price']
instance.Quantity = form.cleaned_data['Quantity']
instance.save()
Is your MEDIA_DIR set in your settings.py?
MEDIA_DIR = os.path.join(BASE_DIR, '/static/media/')
ValueError: The view products.views.products didn't return an HttpResponse object. It returned None instead. Means your somewhere in your views you are not returning an Http response. Try indenting last line of your view to at same level as else. It may resolve
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