So i want to make models form to upload file mp3. I was copy the code from website, but suddenly it goes error. Here's error message on the website :
Forbidden (403) CSRF verification failed. Request aborted.
Help Reason given for failure:
CSRF token missing or incorrect.
In general, this can occur when there is a genuine Cross Site Request Forgery, or when Django's CSRF mechanism has not been used
correctly. For POST forms, you need to ensure:
Your browser is accepting cookies. The view function passes a request
to the template's render method. In the template, there is a {%
csrf_token %} template tag inside each POST form that targets an
internal URL. If you are not using CsrfViewMiddleware, then you must
use csrf_protect on any views that use the csrf_token template tag, as
well as those that accept the POST data. The form has a valid CSRF
token. After logging in in another browser tab or hitting the back
button after a login, you may need to reload the page with the form,
because the token is rotated after a login. You're seeing the help
section of this page because you have DEBUG = True in your Django
settings file. Change that to False, and only the initial error
message will be displayed.
You can customize this page using the CSRF_FAILURE_VIEW setting.
and at my terminal there's error message :
[12/May/2022 14:19:43] "GET / HTTP/1.1" 200 8824 Forbidden (CSRF token
missing or incorrect.): / [12/May/2022 14:19:46] "POST / HTTP/1.1" 403
2513
please help me to fix it. i will give my code :
views.py:
from django.shortcuts import render, redirect
from django.views.decorators.csrf import ensure_csrf_cookie
from .forms import AudioForm
from .models import Audio_store
from MusicLockApp.forms import AudioForm
#ensure_csrf_cookie
def homepage(request):
# return HttpResponse('homepage')
return render(request, 'homepage.html')
def decode(request):
# return HttpResponse('about')
return render(request, 'decode.html')
def upload(request):
if request.method == "POST":
form = AudioForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return redirect("main:upload")
form = AudioForm()
audio = Audio_store.objects.all()
return render(request=request, template_name="homepage.html", context={'form':form, 'audio':audio})
urls.py :
from django.contrib import admin
from django.conf.urls import url
from . import views
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.urls import path, re_path
from django.conf import settings
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^decode/$', views.decode),
url(r'^$', views.homepage),
path('audio', views.Audio_store),
]
urlpatterns += staticfiles_urlpatterns()
models.py:
from django.db import models
class Audio_store(models.Model):
record=models.FileField(upload_to='media/mp3')
forms.py:
from django import forms
from .models import Audio_store
class AudioForm(forms.ModelForm):
class Meta:
model = Audio_store
fields=['record']
add settings.py:
INSTALLED_APPS = [
'MusicLockApp',
'django.contrib.admin',
'django.contrib.auth',
'django.contrib.contenttypes',
'django.contrib.sessions',
'django.contrib.messages',
'django.contrib.staticfiles',
'crispy_forms',
]
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',
]
STATIC_URL = '/static/'
STATICFILES_DIRS = (
os.path.join(BASE_DIR, 'assets'),
)
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
{% block content %}
{% load crispy_forms_tags %}
<div class="container">
<div class="row">
<div class="col-md-6">
<div class="row" style="margin-top: 20px; margin-right: 10px;">
<button type="button" class="dsnupload">
<i class="large material-icons" style="font-size: 50pt; margin-top: 10px;">file_upload</i>
<p style="font-weight: bold; color: white;">Insert file password</p>
</button>
</div>
<br>
<div class="row" style="margin-right: 10px;">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %^}
{{form|crispy}}
<button type="submit" class="dsnupload">
<i class="large material-icons" style="font-size: 50pt; margin-top: 10px;">audiotrack</i>
<p style="font-weight: bold; color: white;">Insert file audio (mp3)</p>
</button>
<p id="message"></p>
</form>
</div>
<br>
<div class="row" style="margin-right: 10px;">
<div class="col-1">
<label class="labels" style="color: white;">Key:</label>
<button type="submit" class="dsnupload"></button>
</div>
<div class="col-11">
<input type="text" class="form-control" placeholder="insert your key here">
</div>
<br> <br>
<a class="dsnhide" type="button" href="#" role="button">Hide it!</a>
</div>
</div>
<div class="col-md-6">
<div class="row" style="margin-top: 20px;">
<div class="card" style="height: 13rem;">
<div class="card-body">
<h5 class="card-title" style="text-align: center;">
Progressing now
</h5>
<br>
<div class="progress">
<div class="progress-bar progress-bar-striped progress-bar-animated" role="progressbar" aria-valuenow="75" aria-valuemin="0" aria-valuemax="100" style="width: 75%">75%</div>
</div>
<br> <br>
<div class="text-center">
<button id="obfuscate-button" onclick="obfuscate()">Play song</button>
<a class="dsnbtn" type="button" href="#" role="button">Download</a>
</div>
</div>
</div>
</div>
<br>
<div class="row">
<div class="card">
<div class="card-body">
<h5 class="card-title">Information Music</h5>
<p class="card-text">Song :</p>
<p class="card-text">Artist :</p>
<p class="card-text">Album :</p>
<p class="card-text">Year :</p>
<p class="card-text">Genre :</p>
<p class="card-text">Duration :</p>
</div>
</div>
</div>
</div>
</div>
</div>
{% endblock %}
what i want is = when i click button insert audio file, we can choose file from local and when clicked button hide it, it will upload it to local folder.
website
Easiest way
Try to change this url url(r'^$', views.homepage), in your urls.py file to this url(r'^$', views.upload),
Effective way
Or instead of that, delete your " homepage " view and rename your " upload " view to " homepage ".
Then check if it work. You'll normally see a form appear in your webpage to select your file.
Related
I am only trying to test the default user profile update through UserChangeForm. Just the email field. So below are the code snippet.
views.py
#login_required(login_url="/login/")
def editUserProfile(request):
if request.method == "POST":
form = UserProfileUpdateForm(request.POST, instance=request.user)
if form.is_valid():
form = UserProfileUpdateForm(request.POST)
form.save()
return redirect('thank_you')
else:
messages.error(request, f'Please correct the error below.')
else:
form = UserProfileUpdateForm(instance=request.user)
return render(request, "authenticate\\editProfilePage.html", {'form': form})
forms.py
class UserProfileUpdateForm(UserChangeForm):
email = forms.EmailField()
class Meta:
model = User
fields = ('email', )
HTML
<div class="container h-100">
<div class="d-flex justify-content-center h-100">
<div class="user_card">
<div class="d-flex justify-content-center">
<h3 id="form-title">Update Profile</h3>
</div>
<div class="d-flex justify-content-center form_container">
<form method="POST" action="{% url 'editUserProfile' %}">
{% csrf_token %}
<div class="input-group mb-2">
<div class="input-group-append">
<span class="input-group-text"><i class="fas fa-envelope-square"></i></span>
</div>
{{form.email}}
</div>
<div class="d-flex justify-content-center mt-3 login_container">
<input class="btn login_btn" type="update" value="update">
</div>
</form>
</div>
{{form.errors}}
<script>
/* Because i didnt set placeholder values in forms.py they will be set here using vanilla Javascript
//We start indexing at one because CSRF_token is considered and input field
*/
//Query All input fields
var form_fields = document.getElementsByTagName('input')
form_fields[4].placeholder='email';
for (var field in form_fields){
form_fields[field].className += ' form-control'
}
</script>
</body>
In the user profile page, I could see the update button, and when I click on it I am redirected to the edit profile page, and I am also able to see the old email address mentioed in the email field. So far so good.
However, when I replace the old email with new one and click on the "update" button nothing happens. No error, no redirection. Nothing. The page remains there.
There were sytax errors in my HTML code, so I re-wrote the entire HTML again. That resolved the issue. Thank you
I am working in a project in Django where someone tries to fill the info of some patients and after hitting the submit button i would like o redirect it into a page with the list of all the existing patients, i am trying using a action tag in the html but it seems not to work, i would like to know what i am doing wrong.
html
{%extends 'base.html'%}
{%load staticfiles%}
{%block body_block%}
<link rel="stylesheet" href="{%static 'patients/css/patientform.css'%}">
<form action="{% url 'patients'%}" method="POST">
<div class="wrapper">
{%csrf_token%}
<div class="Patient">
<h3>Informacion del Paciente</h3>
{{patientinfo.as_p}}
</div>
<div class="Medical">
<h3>Informacion Medica</h3>
{{medicalinfo.as_p}}
</div>
<div class="Insurance">
<h3>Informacion de Seguro</h3>
{{insuranceinfo.as_p}}
</div>
<div class="FirstRelative">
<h3>Antecedentes Familiares</h3>
<h5>Primer Caso</h5>
{{first_relative.as_p}}
<h5>Segundo Caso</h5>
{{second_relative.as_p}}
</div>
</div>
<input id="submit" type="submit" value="Agregar">
</form>
{%endblock%}
Url patterns
from django.urls import path
from .views import *
urlpatterns = [
path('',PatientsList.as_view(),name='patients'),
path('addpatient',PatientFormView,name='addpatient'),
]
Redirection should be made after Post request retrieval in your views.py
# AT POST REQUEST END
return redirect("patients")
Django Docs:
https://docs.djangoproject.com/en/3.0/topics/http/shortcuts/#redirect
In the end of your PatientFormView you should redirect with use of:
return redirect("patients")
For more details check Django documentation: docs.djangoproject.com/en/3.0/topics/http/shortcuts/#redirect
I'm trying to set up a raw html form where a user can make a suggestion and then save it on a database with a POST method, but I keep getting a Forbidden (403) CSRF verification failed. Request aborted. even after following the steps in the Help section.
I have found that I don't get the error if I add csrf_exempt on top of my view like this:
from django.views.decorators.csrf import csrf_exempt
#csrf_exempt
def suggest_ptags(request):
context = {}
print("Form is submitted.")
return render(request, "partials/search_form.html", context)
But I was made aware that It removes completly the CSRF protection and I don't want that.
So what should I do?
Here's my search_form.html form in a partials folder in templates:
<!-- Suggestion Form in popup -->
<div class="prop-modal">
<div class="prop-content">
<a class="btn-close-prop">×</a>
<img src="{% static 'images/pyramids.svg' %}">
<form action="/suggest_ptags/" class="feedback-form" method="POST" enctype="text/plain">
{% csrf_token %}
<h5 class="title-prop">Suggestion</h5>
<input class="input-prop" name="suggest" rows="3" cols="37" placeholder="suggest something..."></input>
<input class="button-prop" type="submit" value="Envoyez"></input>
</form>
</div>
</div>
My current Views.py:
from django.views.decorators.csrf import ensure_csrf_cookie
#ensure_csrf_cookie
def suggest_ptags(request):
context = {}
print("Form is submitted.")
return render(request, "partials/search_form.html", context)
And in my Urls:
from django.conf.urls import url
from django.contrib import admin
from search.views import HomeView, ProductView, FacetedSearchView, autocomplete, suggest_ptags
from .settings import MEDIA_ROOT, MEDIA_URL
from django.conf.urls.static import static
urlpatterns = [
url(r'^$', HomeView.as_view(), name='home'),
url(r'^admin/', admin.site.urls),
url(r'^suggest_ptags/$', suggest_ptags, name='suggest_ptags'), #Suggestions
url(r'^product/(?P<slug>[\w-]+)/$', ProductView.as_view(), name='product'),
url(r'^search/autocomplete/$', autocomplete),
url(r'^search/', FacetedSearchView.as_view(), name='haystack_search'),
] + static(MEDIA_URL, document_root=MEDIA_ROOT)
Any solutions?
You shouldn't use enctype="text/plain". You can remove it (which is the same as enctype="multipart/form-data"), or use enctype="multipart/form-data" if you are uploading files.
Hi i'm currently new to Django and i'm trying to populate a product page.
I'm having problem with the img to show the image(which uses an image url online instead of a file) for example an img src="media3.scdn.vn/img2/2018/6_2/ZIBLXA_simg_b5529c_250x250_maxb.jpg"
The url already in my database with the text media3.scdn.vn/img2/2018/6_2/ZIBLXA_simg_b5529c_250x250_maxb.jpg
But when i tried to render it in template the image doesn't show
I tried to used the but it still not work
Any help would be appreciate!
My template
{% for discount in discounts|slice:":8" %}
<div class="col-md-3 product-men women_two">
<div class="product-googles-info googles">
<div class="men-pro-item">
<div class="men-thumb-item">
<img src="{{STATIC_URL}}{{discount.product_image}}" alt="" />
<div class="men-cart-pro">
<div class="inner-men-cart-pro">
Quick View
</div>
</div>
<span class="product-new-top">New</span>
</div>
<div class="item-info-product">
<div class="info-product-price">
<div class="grid_meta">
<div class="product_price">
<h4>
{{discount.product_name}}
</h4>
<div class="grid-price mt-2">
<span class="money">{{discount.product_old_price}}</span>
</div>
</div>
<div>
<h3>{{discount.product_sit}}</h3>
</div>
<div><h2 style="color: red;">Only {{discount.product_price}}!</h2></div>
</div>
</div>
<div class="clearfix"></div>
</div>
</div>
</div>
</div>
{% endfor %}
EDIT
Seems like the image src trying to get is "http://127.0.0.1:8000/media3.scdn.vn/img2/2018/6_2/ZIBLXA_simg_b5529c_250x250_maxb.jpg" which i don't want "http://127.0.0.1:8000/" in the link. Is there a way to remove this when using {{discount.product_image}} tag ?
Main project urls.py:
from django.contrib import admin
from django.urls import path, include
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('frontend.urls')),
]
frontend app urls.py:
from django.urls import path
from .import views
from django.conf import settings
from django.conf.urls.static import static
app_name = 'frontend'
urlpatterns = [
#index
path('',views.index, name='index')
]
Try using .url like this.
<img src="{{ discount.product_image.url }}" alt=""/>
Also add the MEDIA and STATIC url to your project url patterns.
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
# ... the rest of your URL pattern goes here ...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) \
+ static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
EDIT:
From the discussion in chat, I understood that I had misunderstood your problem first. The images are external and not in your db, you are just storing the URL to the images. And you are using a TextField not ImageField. I assumed ImageField previously. So, all you have to do is to replace {{STATIC_URL}} from in front of the actual URL and put http:// there. The reason behind this is, as the src is missing http:// it's assumed the image to be in the same host domain. So it goes to http://127.0.0.1/your_url.
<img src="http://{{ discount.product_image }}" alt=""/>
I am trying to create a webpage where you can upload questions to the Questions database. I was wondering is there any easy way to do this in Django? Can I upload it so it will be accessible from the Django admin? Here is what I have.
#Models
class Question(models.Model):
question = models.CharField(max_length=400)
answer = models.CharField(max_length=400)
def __unicode__(self):
return self.question + "?"
class QuestionForm(ModelForm):
class Meta:
model = Question
fields = ['question', 'answer']
#Question Template
<div class="container" align="center">
<div class="hero-unit3" align="center">
<h3>
Feel free to post some questions, and a DarKnight representative will answer them for you.
</h3>
</div>
</div>
</div>
<div class="row">
<div class="span6">
<h4>
<form action="<!-- NO IDEA WHAT TO DO -->" method="post">
<input type="text" name="question" />
</div>
</div>
</div>
#views.py
class question(generic.ListView):
template_name = 'users/question.html'
context_object_name = 'Question_list'
def get_queryset(self):
return Question.objects.order_by('question')
The easiest way to achieve what you need is to use CreateView.
In views.py:
from django.views.generic.edit import CreateView
from yourapp.models import Question
class QuestionCreate(CreateView):
model = Question
fields = ['question', 'answer']
Create a new template name question_form.html:
<form action="" method="post">{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Create" />
</form>
Hope it helps!
To make a model available to django admin you have to register the model to admin by
from django.contrib import admin
class Question(models.Model):
...
admin.site.register(Question)
Also for doing this from custom template you can use a model form
The form can be displayed in the template as a table or as a paragraph.
Suppose you render the form to the template as f, use it in template as follows
<form action='..' method='post'>
{{ f.as_t }} //or f.as_p for paragraph
</form>