In my Django project, I am trying to register a student. When I submit the registration form on the live server I got a Page not found (404) error. But it working perfectly on my local server. I think I got this problem for upload image because when I try to submit another form without any image it saves on the database perfectly.
This is the exact error I got.
Page not found (404)
Request Method: POST
Request URL: https://xxxxx.com/accounts/registration/student/
Raised by: accounts.views.register_student
Using the URLconf defined in coaching.urls, Django tried these URL patterns, in this order:
ad/
accounts/
students/
teachers/
admin/
vedios/
[name='landingpage']
error [name='error_page']
^media\/(?P<path>.*)$
The current path, registration/student/, didn't match any of these.
This is the URL patterns related to this problem
from django.urls import path,include
from accounts import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('registration/student/', views.register_student, name='student_registration'),
path('registration/teacher/', views.register_teacher, name='teacher_registration'),
path('login/', views.login_view, name='login'),
path('logout/',views.logout_view,name="logout")
]
And this the view's method for that I got this error.
def register_student(request):
context={}
if request.POST:
form = RegistrationForm(request.POST,request.FILES)
if form.is_valid():
user = form.save(commit=False)
user.is_student = True
user.save()
# login(self.request, user)
return redirect('login')
else:
context['form'] = form
else:
form = RegistrationForm()
context['form'] = form
return render(request, 'accounts/student_register.html',context)
And finally, this is the RegistrationForm() method
class RegistrationForm(UserCreationForm):
"""docstring for ."""
image = forms.ImageField(label="Upload Your Image",widget = forms.FileInput(attrs={'class':'form-control','placeholder':"Your Image"}))
name = forms.CharField(label="Full Name",widget= forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Your Full Name'}))
email = forms.EmailField(label="Email Address",help_text="We'll never share your email with anyone else.", widget= forms.EmailInput(attrs={'class': 'form-control','aria-describedby':'emailHelp','placeholder':'Enter email'}))
phone_number = forms.CharField(label="Phone Number",widget= forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Your Phone Number'}))
address = forms.CharField(label="Current Address",widget= forms.TextInput(attrs={'class': 'form-control','placeholder':'Enter Your Current Address'}))
password1 = forms.CharField(label="Password",help_text="Don't share your password with others",widget= forms.PasswordInput(attrs={'class': 'form-control','placeholder':'Enter Password'}))
password2 = forms.CharField(label="Confirm Password",help_text="",widget= forms.PasswordInput(attrs={'class': 'form-control','placeholder':'Re-Enter Password'}))
class Meta:
"""docstring for ."""
model = get_user_model()
fields = ('image','name','email','phone_number','address','password1','password2')
This is the html form page I used
<form method="post" enctype="multipart/form-data" action="{%url 'student_registration' %}">
{% csrf_token %}
{% for field in form %}
<div class="form-group">
{{ field.errors }}
{{ field.label_tag }}
{{ field }}
{% if field.help_text %}
<small id="{{field.id_for_label}}" class="form-text text-muted">{{ field.help_text|safe }}</small>
{% endif %}
</div>
{% endfor %}
<div class="text-center">
<input type="submit" class="btn btn-success" value="Register as student"><a class="btn btn-secondary ml-1" href="{% url 'teacher_registration' %}">Register as teacher</a>
</div>
</form>
This is my settings.py file if you need this.
"""
Django settings for coaching project.
Generated by 'django-admin startproject' using Django 3.1.2.
For more information on this file, see
https://docs.djangoproject.com/en/3.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/3.1/ref/settings/
"""
from pathlib import Path
import os
# Build paths inside the project like this: BASE_DIR / 'subdir'.
BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_DIR = os.path.join(BASE_DIR, "templates")
STATIC_DIR = os.path.join(BASE_DIR, "static")
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/3.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'og3h%0!(#zaxic7ap%o5)#pc8%-2a4(+wq0n!8it^0dssbst+('
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['xxx.com']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'django.contrib.humanize',
'mainadmin',
'student',
'teacher',
'accounts',
'vedios',
'classlinks',
'frontend',
'notices',
'notification'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'coaching.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [TEMPLATE_DIR,],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'coaching.wsgi.application'
# Database
# https://docs.djangoproject.com/en/3.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.mysql',
'NAME': 'accejakr_coaching',
'USER': 'accejakr_coaching',
'PASSWORD': 'a3w~$Zk%H_TP',
'HOST': 'localhost',
'PORT': 3306
}
}
# Password validation
# https://docs.djangoproject.com/en/3.1/ref/settings/#auth-password-validators
AUTH_USER_MODEL = 'accounts.User'
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/3.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/3.1/howto/static-files/
STATIC_URL = '/static/'
STATIC_ROOT = os.path.join(BASE_DIR, 'assets')
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
MEDIA_URL = 'media/'
MEDIA_ROOT=os.path.join(BASE_DIR, 'media')
This is the global URLs patterns of my project
from django.contrib import admin
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('ad/', admin.site.urls),
path('accounts/', include('accounts.urls')),
path('students/', include('student.urls')),
path('teachers/', include('teacher.urls')),
path('admin/', include('mainadmin.urls')),
# path('class/', include('classlinks.urls')),
path('vedios/', include('vedios.urls')),
path('', include('frontend.urls')),
# path('notifications/', include('notify.urls', 'notifications')),
]
urlpatterns = urlpatterns + static(settings.MEDIA_URL,document_root =settings.MEDIA_ROOT)
The problem is in the settings.py.
You have to change this code
MEDIA_URL = 'media/'
MEDIA_ROOT= os.path.join(BASE_DIR, 'media')
to this code
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
MEDIA_URL = '/media/'
This should work OK now.
Related
When I run my Django application (via python manage.py runserver) I get the login screen, however when I try to login it redirect me to the page that says:
Forbidden (403)
CSRF verification failed. Request aborted.
Here is my settings.py
"""
Django settings for my_app project.
Generated by 'django-admin startproject' using Django 2.1.5.
For more information on this file, see
https://docs.djangoproject.com/en/2.1/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/2.1/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = '...'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['*']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'cooking_book'
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'my_app.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.static',
'django.template.context_processors.media',
],
},
},
]
WSGI_APPLICATION = 'my_app.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATICFILES_DIRS = (
os.path.join(BASE_DIR, "static"),
)
STATIC_URL = '/static/'
There are questions similar to mine here on stackoverflow but unfortunately the answers are not helpful to me...
Additional notes on what I tried:
I am allowing cookies in my browser.
My view functions pass a request to the template's render method.
In the template I am adding {% csrf_token %} inside each POST form.
I also tried setting the CSRF_COOKIE_DOMAIN = None and CSRF_COOKIE_SECURE = False but it made no difference.
It would be great if anyone could help me with this, I am really stuck...
EDIT:
If you give me thumbs down, can you please just let me know what I did wrong? I am new here, still adapting... and if this is too easy for you and that is the reason for the thumbs down, please leave an answer I will appreciate it. Thank you!
2nd EDIT: Adding the relevant parts of the template and views.py file, where the csrf token is used. It is also worth mentioning that when the user logs in he/she is supposed to go to the homepage (that contains no POST forms and consequently no csrf tokens), and chose where to go next.
views.py (relevant part)
#login_required(login_url='/login/')
def dining(request):
#request is POST when user filters the city
if request.method == 'POST':
filter_city = FilterCityForm(request.POST)
if filter_city.is_valid():
filter_city = filter_city.save(commit=False)
city = str(filter_city.name)
#...
# here I'm doing some calculations and querying depending on the chosen city
#...
filter_city = FilterCityForm(initial={'name':city})
else:
filter_city = FilterCityForm(initial={'name':'Toronto'})
return render(request, 'dining.html', {'filter_city':filter_city})
dining.html (relevant part):
<div name='dropdown'>
<form action="" method="POST">
{% csrf_token %}
City: {% for widget in filter_city %}
{% if widget.errors %}
{% for error in widget.errors %}
<span style="color: red">{{ error }}</span><br>
{% endfor %}
{% endif %}
{{ widget }}
{% endfor %}
<input type="submit" value="OK">
</form>
<br>
</div>
There is Problem
Hello I'm creating a project, I created a register form, but I tried to create an email authentication submit button in the form near EmailInput, but I could not find it
I'm currently using {% bootstrap_form form%} to render automatically in a register form
What I want
I would like to have the Submit Email Authentication button appear on the form near EmailInput,
When the user clicks the Send Email Authentication button, it sends an authentication email to the user's email
Then, when the user clicks the link attached to the mail, the user is informed that the confirmation has been made on the register window
and When the user clicks the sign up button, the registration is completed
What I've tried
I created a register form using UserCreationForm supported by django,
I tested using gmail smtp to send email from django. It works well
The Code in /django-blog/blog/settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'y$a)3faq3*h#r0g5b^cxsw^lgdxbbu&#lsqek!_0ju+d*c!ups'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = ['localhost']
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
# 내가 만든 앱
'my_blog',
#USER APP
'users',
# Apps created by others
'bootstrap3',
# Restful api Framework
'rest_framework',
# Social
'social_django',
"social_core",
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'social_django.middleware.SocialAuthExceptionMiddleware',
]
ROOT_URLCONF = 'blog.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'blog/templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'social_django.context_processors.backends',
'social_django.context_processors.login_redirect',
],
},
},
]
WSGI_APPLICATION = 'blog.wsgi.application'
# Database
# https://docs.djangoproject.com/en/2.1/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/2.1/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/2.1/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/2.1/howto/static-files/
STATIC_URL = '/static/'
# 내 설정
LOGIN_URL = '/users/login/'
# django-bootstrap3 settings
BOOTSTRAP3 = {
'include_jquery' : True,
}
# Heroku settings
cwd = os.getcwd()
if cwd == '/app' or cwd[:4] == '/tmp':
import dj_database_url
DATABASES = {
'default': dj_database_url.config(default='postgres://localhost')
}
# request.is_secure()에 대해 'X-Forwarded-Proto'를 우선적으로 사용한다.
SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https')
# 모든 호스트 헤더를 허용한다.
ALLOWED_HOSTS = ['choco-blog.herokuapp.com']
DEBUG = False
# Static asset configuration
BASE_DIR = os.path.dirname(os.path.abspath(__file__))
STATIC_ROOT = 'staticfiles'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'static'),
)
# AUTHENTICATION_BACKENDS settings
AUTHENTICATION_BACKENDS = [
'social_core.backends.open_id.OpenIdAuth', # for Google authentication
'social_core.backends.google.GoogleOpenId', # for Google authentication
'social_core.backends.google.GoogleOAuth2', # for Google authentication
'social_core.backends.github.GithubOAuth2', # for Github authentication
'social_core.backends.kakao.KakaoOAuth2', # for Kakaotlak authentication
'django.contrib.auth.backends.ModelBackend', # Django 기본 유저모델
]
SOCIAL_AUTH_URL_NAMESPACE = 'social'
LOGIN_REDIRECT_URL='/'
# Google login
SOCIAL_AUTH_GOOGLE_OAUTH2_KEY ='843562355161-3atsmmageh4j0758g4am6e4ncefckupf.apps.googleusercontent.com'
SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET ='ZVKObQDFPhTdz1GXWfaYuulq'
# Github Login
SOCIAL_AUTH_GITHUB_KEY = 'e2fc4a9cf1f213b0a10f'
SOCIAL_AUTH_GITHUB_SECRET = 'c4d1efe407175230a47d7fa547db0667b4f08721'
# Kakaotalk login
SOCIAL_AUTH_KAKAO_KEY = '490c43bc63dd3351e6068f6bbf4e0bfd'
# Verification Email settings
EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend'
EMAIL_USE_TLS = 'True'
EMAIL_PORT = 587
EMAIL_HOST = 'smtp.gmail.com'
EMAIL_HOST_USER = 'user#gmail.com'
EMAIL_HOST_PASSWORD = os.environ.get('KBOARD_PASSWORD')
SERVER_EMAIL = 'user#gmail.com'
DEFAULT_FROM_MAIL = 'my_blog'
/django-blog/user/forms.py
from django import forms
from django.contrib.auth.forms import UserCreationForm, AuthenticationForm
from django.contrib.auth.models import User
class UserCreationForm(UserCreationForm):
"""유저 가입양식 정의"""
first_name = forms.CharField(widget = forms.TextInput(
attrs={'class': 'form-control', 'placeholder': 'First Name'}),
max_length=32, help_text='First name', label='이름')
last_name = forms.CharField(widget =
forms.TextInput(attrs={'class':'form-control', 'placeholder':'Last Name'}),
max_length=32, help_text='Last name', label='성')
email = forms.EmailField(widget = forms.EmailInput(attrs=
{'class':'form-control', 'placeholder': 'Email',}),
max_length=64, help_text='유효한 이메일 주소를 입력하세요',
error_messages={'invalid': ("Email 이 비어있습니다")},)
terms = forms.BooleanField(
label =('My blog of service'),
widget=forms.CheckboxInput(
attrs={
'required': 'True',
}
),
error_messages={
'required':('당신의 My blog of service 에 대한 동의가 필요합니다. ')
}
)
privacy = forms.BooleanField(
label=('Privacy policy'),
widget=forms.CheckboxInput(
attrs={
'required':'True',
}
),
error_messages={
'required=':('당신의 Privacy policy 동의가 필요합니다.')
}
)
class Meta(UserCreationForm.Meta):
model = User
fields = UserCreationForm.Meta.fields + ('first_name',
'last_name', 'email')
/django-blog/user/urls.py
"""users 앱의 URL 패턴을 정의하는 파일"""
from django.urls import re_path
from django.contrib.auth import views as auth_views
from . import views
app_name = 'users'
urlpatterns = [
# 로그인 페이지
re_path(r'^login/$',
auth_views.LoginView.as_view(template_name='users/login.html'),
name = 'login'),
# 로그아웃 페이지
re_path(r'^logout/$',views.logout_view, name='logout'),
# 유저 등록 페이지
re_path(r'^register/$', views.register, name='register'),
]
/django-blog/user/templates/user/register.html
{% extends "my_blog/base.html" %}
{% load bootstrap3 %}
{% block header %}
<h2>회원가입</h2>
{% endblock %}
{% block content %}
<form method='post' action="{% url 'users:register' %}" class="form">
{% csrf_token %}
{% bootstrap_form form %}
{% buttons %}
<button name="submit" class="btn btn-success">유저 등록하기</button>
{% endbuttons %}
<input type="hidden" name="text" value="{% url 'my_blog:index' %}">
</form>
{% endblock %}
/django-blog/user/views.py
from django.shortcuts import render
from django.urls import reverse
from django.contrib.auth import login, logout, authenticate
from django.http import HttpResponseRedirect
from .forms import UserCreationForm
def logout_view(request):
"""사용자 로그아웃"""
logout(request)
return HttpResponseRedirect(reverse('my_blog:index'))
def register(request):
"""새 사용자를 등록한다."""
if request.method != 'POST':
# 빈 폼을 보여준다.
form = UserCreationForm()
else:
# 전송받은 폼을 처리한다.
form =UserCreationForm(data = request.POST)
if form.is_valid():
new_user = form.save()
# 사용자를 로그인시키고 홈페이지로 리다이렉트한다.
authenticated_user = authenticate(username=new_user.username,
password=request.POST['password1'])
login(request, authenticated_user)
return HttpResponseRedirect(reverse('my_blog:index'))
context = {'form' : form}
return render(request, 'users/register.html', context)
I have attached a register screen photo
enter image description here
If you need information to solve this problem, please ask me :)
You can use Widget Tweaks. With help of this you can add classes to your input and edit other attribute also. Here is good tutorial.
I think you can customize it in a bootstrap field:
https://django-bootstrap3.readthedocs.io/en/latest/templatetags.html?highlight=layout#bootstrap-field
Like this with new css w3-css
{% bootstrap_form form layout='inline' form_group_class='w3-input w3-border-0 w3-large'%}
I project is supposed to be able to upload an image with a name then display the uploaded image and name. I have tried looking online for an answer to my problem but have found none. The problem basically is my django webapp is not saving a name(CharField)an and image(ImageField) to the database. I tried to do everything necessary for it to work but it's still not working. The following is my project. Thanks for your time.
My projectl directories:
Image shows project structure
views.py
from django.shortcuts import render
from ImgApp.forms import ImageForm
from ImgApp.models import ImageModel
from django.http import HttpResponseRedirect
def upload(request):
if request.method == "POST":
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('ImgApp:home')
else:
form = ImageForm()
con = {"var_form": form}
return render(request, 'upload.html', con)
models.py
from django.db import models
class ImageModel(models.Model):
name = models.CharField(max_length=44)
image = models.ImageField(upload_to='media/',null=True)
def __str__(self):
return self.name
forms.py
from django import forms
from ImgApp.models import ImageModel
class ImageForm(forms.ModelForm):
class Meta:
model = ImageModel
fields = "__all__"
settings.py
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = 'e3d)3&+&3!xkh_zz_l#uc9ly8uh#wio1g+zh59_mt&v-0xyubp'
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'debug_toolbar',
'ImgApp',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
'debug_toolbar.middleware.DebugToolbarMiddleware',
]
ROOT_URLCONF = 'ImgProject.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR,'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
'django.template.context_processors.media',
],
},
},
]
WSGI_APPLICATION = 'ImgProject.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
STATIC_DIR = os.path.join(BASE_DIR,'static')
STATICFILES_DIR = [
os.path.join(BASE_DIR,'static')
]
MEDIA_ROOT = os.path.join(BASE_DIR,'media')
MEDIA_URL = "/media/"
INTERNAL_IPS = ['127.0.0.1']
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
from ImgApp import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^app/',include('ImgApp.urls')),
url(r'^$',views.home),
url(r'^upload/$',views.upload),
]
if settings.DEBUG:
import debug_toolbar
urlpatterns = [
url(r'^__debug__/', include(debug_toolbar.urls)),
] + urlpatterns
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
upload.html
<form method="post" enctype="multipart/form-data" action="{% url 'ImgApp:index' %}">
{% csrf_token %}
{{var_form.as_p}}
<input type="submit" value="upload" class="btn btn-primary">
</form>
index.html
<!DOCTYPE html>
{% load static %}
........
{% if var_db %}
{% for img in var_db %}
<b>Name:</b>{{img.name}}
<br>
<img src="{{MEDIA_URL}}/{{img.image}}" alt="Image here" height="200" width="300">
{% endfor %}
{% else %}
<p>No Images uploaded yet</p>
<p>Fill this lonely area with happiness</p>
{% endif %}
It looks as if you are posting the form to the index. You should post it to the upload view.
<form method="post" enctype="multipart/form-data" action="{% url 'ImgApp:upload' %}">
You need to add a name to the URL pattern for this to work.
url(r'^upload/$',views.upload, name='upload'),
In your view, you need to move the context line out of the else block so that it runs for GET and POST request. That means that if the form is invalid, you'll see the errors on the template.
def upload(request):
if request.method == "POST":
form = ImageForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect('ImgApp:home')
else:
form = ImageForm()
context = {"form": form}
return render(request, 'upload.html', context)
I've renamed a couple of variables to match the usual Django style (con to context, var_form to form). If you rename var_form, remember to update your template as well.
I am making a simple app(Django version 1.11+python3.5+). I want to show images on my homepage(web app) from Django models. I can upload successfully from Django admin panel. But image cant renders properly. The image does not show in the homepage. This is my HTML file.
{% extends "shop/base.html" %}
{% block content_area %}
{% for name in products %}
<div class="col-lg-3 col-md-3">
<div class="main_content_sidebar">
<div class="content_title">
<h2>{{name.product_name}}</h2>
</div>
<div class="image_space">
<img src="{{name.product_image.url}}" class="img-thumbnail" alt="">
</div>
<div class="content_p">
<p>Retail Price:{{name.product_retail_price}}</p>
<p>Quantity: {{name.product_quantity}}</p>
<p>Date: {{name.product_sell_date}}</p>
</div>
</div>
</div>
{% endfor %}
{% endblock %}
this is mysite(project)>>urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf.urls.static import static
from django.conf import settings
urlpatterns = [
url(r'^shop/',include('shop.urls')),
url(r'^admin/', admin.site.urls),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL,
document_root=settings.MEDIA_ROOT)
This is my models.py file.
class ProductsName(models.Model):
product_name=models.CharField('name', max_length=50)
product_retail_price=models.IntegerField('retail price TAKA')
product_quantity = models.IntegerField('quantity')
product_sell_date=models.DateTimeField('buy date', auto_now_add=True)
product_image = models.ImageField(upload_to='upload/', blank=True, null=True)
def __str__(self):
return self.product_name
setting.py file
"""
Django settings for mysite project.
Generated by 'django-admin startproject' using Django 1.11.5.
For more information on this file, see
https://docs.djangoproject.com/en/1.11/topics/settings/
For the full list of settings and their values, see
https://docs.djangoproject.com/en/1.11/ref/settings/
"""
import os
# Build paths inside the project like this: os.path.join(BASE_DIR, ...)
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
# Quick-start development settings - unsuitable for production
# See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/
# SECURITY WARNING: keep the secret key used in production secret!
SECRET_KEY = ''
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'shop.apps.ShopConfig',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
]
MIDDLEWARE = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'mysite.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'mysite.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.11/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.11/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.11/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'Asia/Dhaka'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.11/howto/static-files/
STATIC_URL = '/static/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'shop/images/')
MEDIA_URL = '/media/'
When I visit my homepage, I can't see any image. But I see image link If I open my browser dev tools.
chrome dev tool
if I click that image link from chrome dev tool. I got andjango doesn/t found that image url error.
Also my folder structure is:
mysite
shop
manage.py
path_to
db.sqlite3
The issue is that the your MEDIA_ROOT is not being served and Django cannot append the correct url. In your project urls.py add the following at the end:
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
And in the setttings.py add the correct paths for:
MEDIA_ROOT = os.path.join(BASE_DIR,'path_to_/media_folder')
MEDIA_URL = '/media/'
I just installed Django AllAuth to my project, but cant find default login or signup page.
1) I logged out from admin panel, but still didn't find it.
2) Added signup.html template, but nothing
Picture of error in localhost/accounts http://prntscr.com/9oyu00
Here's my code:
settings.py
# SECURITY WARNING: don't run with debug turned on in production!
DEBUG = True
ALLOWED_HOSTS = []
# Application definition
INSTALLED_APPS = [
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'profiles',
'contact',
'crispy_forms',
'django.contrib.sites',
'allauth',
'allauth.account',
'allauth.socialaccount',
]
MIDDLEWARE_CLASSES = [
'django.middleware.security.SecurityMiddleware',
'django.contrib.sessions.middleware.SessionMiddleware',
'django.middleware.common.CommonMiddleware',
'django.middleware.csrf.CsrfViewMiddleware',
'django.contrib.auth.middleware.AuthenticationMiddleware',
'django.contrib.auth.middleware.SessionAuthenticationMiddleware',
'django.contrib.messages.middleware.MessageMiddleware',
'django.middleware.clickjacking.XFrameOptionsMiddleware',
]
ROOT_URLCONF = 'src.urls'
TEMPLATES = [
{
'BACKEND': 'django.template.backends.django.DjangoTemplates',
'DIRS': [os.path.join(BASE_DIR, 'templates')],
'APP_DIRS': True,
'OPTIONS': {
'context_processors': [
'django.template.context_processors.debug',
'django.template.context_processors.request',
'django.contrib.auth.context_processors.auth',
'django.contrib.messages.context_processors.messages',
],
},
},
]
WSGI_APPLICATION = 'src.wsgi.application'
# Database
# https://docs.djangoproject.com/en/1.9/ref/settings/#databases
DATABASES = {
'default': {
'ENGINE': 'django.db.backends.sqlite3',
'NAME': os.path.join(BASE_DIR, 'db.sqlite3'),
}
}
# Password validation
# https://docs.djangoproject.com/en/1.9/ref/settings/#auth-password-validators
AUTH_PASSWORD_VALIDATORS = [
{
'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator',
},
{
'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator',
},
]
# Internationalization
# https://docs.djangoproject.com/en/1.9/topics/i18n/
LANGUAGE_CODE = 'en-us'
TIME_ZONE = 'UTC'
USE_I18N = True
USE_L10N = True
USE_TZ = True
# Static files (CSS, JavaScript, Images)
# https://docs.djangoproject.com/en/1.9/howto/static-files/
STATIC_URL = '/static/'
if DEBUG:
MEDIA_URL = '/media/'
STATIC_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "static-only")
MEDIA_ROOT = os.path.join(os.path.dirname(BASE_DIR), "static", "media")
STATICFILES_DIRS = (os.path.join(os.path.dirname(BASE_DIR), "static", "static"),
)
# Location of templates
CRISPY_TEMPLATE_PACK = 'bootstrap3'
AUTHENTICATION_BACKENDS = (
'django.contrib.auth.backends.ModelBackend',
'allauth.account.auth_backends.AuthenticationBackend',
)
SITE_ID = 1
LOGIN_URL = '/accounts/login'
LOGIN_REDIRECT = '/'
ACCOUNT_AUTHENTICATION_METHOD = "username_email"
ACCOUNT_CONFIRM_EMAIL_ON_GET = False
ACCOUNT_EMAIL_CONFIRMATION_ANONYMOUS_REDIRECT_URL = LOGIN_URL
ACCOUNT_EMAIL_CONFIRMATION_AUTHENTICATED_REDIRECT_URL = None
ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 3
ACCOUNT_EMAIL_REQUIRED = False
ACCOUNT_EMAIL_VERIFICATION = None
ACCOUNT_EMAIL_SUBJECT_PREFIX = "My subject: "
ACCOUNT_DEFAULT_HTTP_PROTOCOL = "http"
ACCOUNT_LOGOUT_ON_GET = False
ACCOUNT_LOGOUT_REDIRECT_URL = "/"
ACCOUNT_SIGNUP_FORM_CLASS = None
ACCOUNT_SIGNUP_PASSWORD_VERIFICATION = True
ACCOUNT_UNIQUE_EMAIL = True
ACCOUNT_USER_MODEL_USERNAME_FIELD = "username"
ACCOUNT_USER_MODEL_EMAIL_FIELD = "email"
ACCOUNT_USERNAME_MIN_LENGTH = 5
ACCOUNT_USERNAME_BLACKLIST = []
ACCOUNT_USERNAME_REQUIRED = True
ACCOUNT_PASSWORD_INPUT_RENDER_VALUE = False
ACCOUNT_PASSWORD_MIN_LENGTH = 6
ACCOUNT_LOGIN_ON_EMAIL_CONFIRMATION = True
urls.py
from django.conf.urls import url, include
from django.contrib import admin
from django.conf import settings
from django.conf.urls.static import static
from contact import views
urlpatterns = [
url(r'^$', 'profiles.views.home', name='home'),
url(r'^contact/$', views.contact, name='contact'),
url(r'^accounts/', include('allauth.urls')),
url(r'^admin/', admin.site.urls),
]
if settings.DEBUG:
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
signup.html
{% extends "account/base.html" %}
{% load crispy_forms_tags %}
{% load i18n %}
{% block head_title %}{% trans "Signup" %}{% endblock %}
{% block content %}
<h1>{% trans "Sign Up" %}</h1>
<p>{% blocktrans %}Already have an account? Then please sign in.{% endblocktrans %}</p>
<form class="signup" id="signup_form" method="post" action="{% url 'account_signup' %}">
{% csrf_token %}
{{ form|crispy }}
{% if redirect_field_value %}
<input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" />
{% endif %}
<button class='btn btn-default' type="submit">{% trans "Sign Up" %} »</button>
</form>
{% endblock %}
I had the same problem. The source of it all was that I had already defined a base.html file without a 'block content' block. You need the following structure inside the body of your base.html file:
<body>
{% block body %}
{% block content %}
{% endblock content %}
{% endblock body %}
</body>
I used this source to find a suitable example, but it's not very helpful other than that. This other page was a bit better though.
Because you are requesting only the /accounts/ and if you see closely to your debugger (the screen) there is no URL for this (pattern ^accounts/ ^ ^$).
Your login & sing up page is located on /accounts/login/ and /accounts/singup/.
About editing default templates I am not able to help you with it (never used the AllAuth package) so hope someone skilled will help you.