not able to upload and display django form - python

1.views.py
from django.shortcuts import render
from . models import User
from .forms import Userform
def Home(request):
if request.method == "POST":
form = Userform(request.POST or None,request.FILES or None)
if form.is_valid():
form.save()
else:
form = Userform()
return render(request,"home.html",{"form":form})
def read(request):
read = User.objects.all()
return render(request,"read.html",{"read":read})
2.models.py
from django.db import models
class User(models.Model):
name = models.CharField(max_length=12)
rollno = models.IntegerField()
# files = models.FileField()
3.form.py
from django import forms
from .models import User
class Userform(forms.ModelForm):
class Meta:
model = User
fields = ('name','rollno')
urls.py
from django.contrib import admin
from django.urls import path
from app import views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path("",views.Home,name="Home"),
path("read/",views.read, name="read"),
]
urlpatterns+=static(settings.MEDIA_URL,document_root=settings.MEDIA_ROOT)
4.home.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
<form method="POST" action="read/" enctype="multipart/form-data">
{%csrf_token%}
{{form}}
<button type=submit>click to submit</button>
</form>
</body>
</html>
read.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<title>Document</title>
</head>
<body>
{%block containt%}
{%for i in read%}
{{i.name}}
{{i.rollno}}
{%endfor%}
{%endblock%}
</body>
</html>
i want to add data to django admin using a form but data is not uploading at django admin
Not able to upload data into django admin hence cant read it
please help
i want to add data to django admin using a form but data is not uploading at django admin
Not able to upload data into django admin hence cant read it
please help

Problem is in the action of your form, you have entered the wrong URL in the action
You have to put home URL instead of read/, because you are handling your form submission in your home function so replace your form action by this
<form method="POST" action="{% url 'Home' %}" enctype="multipart/form-data">
{%csrf_token%}
{{form}}
<button type=submit>click to submit</button>
</form>

Related

Django stops updating data to mysql after page refresh

I'm fairly new to using the django framework and recently I made a system with it where it submits data to mysql db through a html form. I got it working eventually and everything seemed quite fine, though I noticed a bug where if I refresh the page django stops sending data to mysql, has this ever happened to anyone?
Stuff for reference:
views.py
from django.shortcuts import render
from websiteDB.models import dbInsert
from django.contrib import messages
def insertToDB(request):
if request.method == "POST":
if request.POST.get('uname') and request.POST.get('email') and request.POST.get('message'):
post = dbInsert()
post.uname = request.POST.get('uname')
post.email = request.POST.get('email')
post.message = request.POST.get('message')
post.save()
messages.success(request, "Message sent successfully.")
return render(request, "contact.html")
else:
return render(request, "contact.html")
models.py
from django.db import models
class dbInsert(models.Model):
uname = models.CharField(max_length=100)
email = models.EmailField()
message = models.TextField()
class Meta:
db_table = "contactrequest"
urls.py
"""
websiteDB URL Configuration
The `urlpatterns` list routes URLs to views. For more information please see:
https://docs.djangoproject.com/en/4.0/topics/http/urls/
Examples:
Function views
1. Add an import: from my_app import views
2. Add a URL to urlpatterns: path('', views.home, name='home')
Class-based views
1. Add an import: from other_app.views import Home
2. Add a URL to urlpatterns: path('', Home.as_view(), name='home')
Including another URLconf
1. Import the include() function: from django.urls import include, path
2. Add a URL to urlpatterns: path('blog/', include('blog.urls'))
"""
from django.contrib import admin
from django.urls import path
from django.views.generic import TemplateView
from . import views
from . import index
urlpatterns = [
#path('admin/', admin.site.urls),
path('homepage', index.page_home, name= 'hpage'),
path('', views.insertToDB),
path('contactpage', index.contact_page, name= 'cpage')
]
contact.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta http-equiv="X-UA-Compatible" content="IE=edge">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="preconnect" href="https://fonts.googleapis.com">
<link rel="preconnect" href="https://fonts.gstatic.com" crossorigin>
<link href="https://fonts.googleapis.com/css2?family=Outfit:wght#200&display=swap" rel="stylesheet">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<link rel="stylesheet" href="{% static 'css/css/styles.css' %}">
<title>Document</title>
</head>
<body style="background-color: rgb(74, 36, 110);">
<script src="{% static 'js/main.js' %}"></script>
<div class="top-nav">
HOME
PRODUCTS
CONTACT
ABOUT
COMMUNITY
</div>
<div class="div-align">
<h2>Contact</h2>
<p>Reach us for questions/concerns through the form below.</p>
</div>
<form class="fontmaker" method="post">
{% csrf_token %}
<label for="Username">Username:</label><br>
<input type="text" id="Username" name="uname" required><br>
<label for="E-mail">E-mail:</label><br>
<input type="text" id="Email" name="email" required>
<label for="Reason" class="margin">Message:</label>
<textarea id="Reason" name="message" rows="10" cols="60" required>Type your reason of contact here.</textarea>
<input type="submit" value="Submit" class="rounded-corners" id="submitBtn">
{% if messages %}
{% for message in messages %}
{{message}}
{% endfor %}
{% endif %}
</form>
</body>
</html>
There are no errors in terminal, and the button click also properly sends a POST req:
Terminal output
I'm also new to posting on stackoverflow, tell me if there's something else to improve on in the future when posting.
index.py
from django.http import HttpResponse
from django.shortcuts import render
def page_home(request):
return render(request, 'index.html')
def contact_page(request):
return render(request, 'contact.html')
Thanks in advance.
If you render the contactpage/ URL, then if you submit the form, you will submit it to the contact view, but that view does not handle the data, nor does it create any entry. You must make sure that you post the form to the insertToDB view. You can do this by giving the view a name:
urlpatterns = [
# …,
path('', views.insertToDB, name='insertToDB'),
# …
]
and then specify the endpoint in the form:
<form class="fontmaker" method="post" action="{% insertToDB %}">
<!-- … -->
</form>
In case of a successful POST request, you should also redirect, for example with:
from django.shortcuts import redirect
def insertToDB(request):
if request.method == 'POST':
if request.POST.get('uname') and request.POST.get('email') and request.POST.get('message'):
post = dbInsert.objects.create(
uname = request.POST['uname'],
email = request.POST['email'],
message = request.POST['message']
)
messages.success(request, 'Message sent successfully.')
return redirect('cpage')
return render(request, 'contact.html')
else:
return render(request, 'contact.html')
I would advise to work with Django forms [Django-doc], for example a modelform [Django-doc] to validate and clean form input and remove a lot of boilerplate code.

Show multiselectfield value in Bootstrap 4 multiselect dropdown in Django template

I am following this answer for the multi-selecting dropdown. I am using django-multiselectfield to collect data in the DB model. I want to show value in bootstrap multi-selecting dropdown but getting the below result
I am seeking this result
These are my code snippet
model.py
from django.db import models
from multiselectfield import MultiSelectField
class Country(models.Model):
name = models.CharField(max_length=40)
def __str__(self):
return self.name
class Person(models.Model):
obj=Country.objects.all()
TEAM=tuple((ob,ob) for ob in obj)
name = models.CharField(max_length=124)
southasia=MultiSelectField(max_length=200, choices=TEAM)
def __str__(self):
return self.name
views.py
from django.http import JsonResponse
from django.shortcuts import render, redirect, get_object_or_404
from .forms import PersonCreationForm
from .models import Person
def person_create_view(request):
form = PersonCreationForm()
if request.method == 'POST':
form = PersonCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('person_add')
return render(request, 'miracle/index.html', {'form': form})
forms.py
from django import forms
from .models import Person
class PersonCreationForm(forms.ModelForm):
class Meta:
model = Person
fields = '__all__'
def __init__(self, *args, **kwargs):
super().__init__(*args, **kwargs)
template
{% load crispy_forms_tags %}
<!doctype html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport"
content="width=device-width, user-scalable=no, initial-scale=1.0, maximum-scale=1.0, minimum-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<link href="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/css/select2.min.css" rel="stylesheet" />
<script src="https://cdn.jsdelivr.net/npm/select2#4.1.0-rc.0/dist/js/select2.min.js"></script>
<title>Dependent Dropdown in Django</title>
<link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/css/bootstrap.min.css">
<link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/css/bootstrap-select.css" />
<script src="https://ajax.googleapis.com/ajax/libs/jquery/2.1.1/jquery.min.js"></script>
<script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.1/js/bootstrap.bundle.min.js"></script>
<script src="https://cdnjs.cloudflare.com/ajax/libs/bootstrap-select/1.13.1/js/bootstrap-select.min.js"></script>
</head>
<body>
<h2>Person Form</h2>
<form method="post">
{% csrf_token %}
{{ form.name|as_crispy_field }}
<select class="selectpicker" multiple data-live-search="true">
{{ form.southasia|as_crispy_field }}
</select>
<input type="submit" value="Submit">
</form>
<script>
$('select').selectpicker();
</script>
</body>
</html>
How can do show all values in dropdown multiselect instead of normal checkbox select?
django multiselect will give you check box view. If you want drop-down multiple list one of the work around is you can create another model for the choices and use manytomany relation . Django rendering should automatically detect it as droplist view and gives you opttion to select multiple choices.
Like this.
Class model1(model.models)
Choices = models.charfield(choice=choice)
Class person(models.model)
Choice = manytomany (model1).

POST method is not working when submitting form in django

I created feedback form using form module in django. i wrote the code for printing form data entered by user when submitting form. But when i submit the form post is not working as a result user data is not printing . I am beginner in django .I tried lots to solve this .but i couldn't. please help me if anyone know what is my wrong in code
forms.py
from django import forms
class feedbackForm(forms.Form):
Name=forms.CharField()
RollNo=forms.IntegerField()
Email=forms.EmailField()
feedback=forms.CharField(widget=forms.Textarea)
views.py
from django.shortcuts import render
from .import forms
def feedback_view(request):
form=forms.feedbackForm()
if request.method=='POST':
form=forms.feedbackForm(request.POST)
if form.is_valid():
print('form validation success and printing feeback info')
print('student name :',form.cleaned_data['Name'])
print('student RollNo:',form.cleaned_data['RollNo'])
print('student Email :',form.cleaned_data['Email'])
print('student feedback :',form.cleaned_data['feedback'])
return render(request,'testapp/feedback.html',{'form':form})
urls.py
from django.conf.urls import url
from django.contrib import admin
from testapp import views
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^feed/', views.feedback_view),
]
feedback.html
<!DOCTYPE html>
{% load staticfiles %}
<html lang="en" dir="ltr">
<head>
<meta charset="utf-8">
<link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css" integrity="sha384-BVYiiSIFeK1dGmJRAkycuHAHRg32OmUcww7on3RYdg4Va+PmSTsz/K68vbdEjh4u" crossorigin="anonymous">
<link rel="stylesheet" href="{%static "css/demo1001.css"%}">
<title></title>
</head>
<body>
<div class="container" align=center>
<h1>ShefJaz Student 2feedbackform </h1><br>
<form method="post">
{{form.as_p}}
{%csrf_token%}
<button type="button" class="btn btn-primary">sumbit feedback</button>
</form>
</div>
</body>
</html>
You are using a function as a API view so, It should be mentioned in the method decorator like shown below
from rest_framework.decorators import api_view
#api_view(['POST'])
def feedback_view(request):
.....
your code
.....
Hope it will give you the solution.
more than one HTTP methods can be used like shown here.
#api_view(['POST', 'GET'])

How do you get a string from Django PostgreSQL ArrayField?

I'm trying to get a string out of an ArrayField in my database but it only prints by characters, not the full string. For example, the ArrayField is named words and in the database it shows as {word1, word2, word3} so in the HTML I put {{ object.words.0 }} and { is rendered on the screen.
How can I get it to render word1?
I have added django.contrib.postgres to INSTALLED_APPS.
This is what it looks like in my model:
from django.db import models
from django.contrib.postgres.fields import ArrayField
class WordArr(models.Model):
words = ArrayField(models.CharField(max_length=200, null=True))
I fixed the issue and it was with my database. The ArrayField in my model was previously a CharField that I changed. I thought the migrations were correct however the database was still reading it as a CharField, so the output was the first character of a string. I migrated to a new database and everything worked fine. My code is below for further reference:
models.py
from django.db import models
from django.contrib.postgres.fields import ArrayField
# Create your models here.
class Word(models.Model):
first = models.CharField(max_length=50)
last = models.CharField(max_length=50)
words = ArrayField(models.CharField(max_length=50, null=True))
def __str__(self):
return self.first
views.py
from django.shortcuts import render
from django.views.generic.detail import DetailView
from django.views.generic import CreateView
from .models import Word
# Create your views here.
class ArrayCreateView(CreateView):
model = Word
fields = ['first', 'last']
success_url = '/'
def form_valid(self, form):
w = form.save(commit=False)
random_words = ["word1", "word2", "word3"]
w.words = random_words
return super().form_valid(form)
class ArrayDetailView(DetailView):
model = Word
word_form.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>Create Array</h1>
<div>
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<button type="submit">Submit</button>
</form>
</div>
</body>
</html>
word_detail.html
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
<h1>{{ object.words.0 }}</h1>
</body>
</html>
settings.py
INSTALLED_APPS = [
...
'django.contrib.postgres',
'arr',
]
urls.py
from django.contrib import admin
from django.urls import path
from arr.views import ArrayCreateView, ArrayDetailView
urlpatterns = [
path('admin/', admin.site.urls),
path('create/new/', ArrayCreateView.as_view(), name='create'),
path('detail/<int:pk>/', ArrayDetailView.as_view(), name='detail')
]

Displaying Audio/Video in Python Django Website

I am building a blog website where I can upload audio/video files to the database and then run a for loop to output the files in HTML audio/video tags. I have succeeded in saving the files to the database and also output them on the website but for some reason I can't get them to play.
I am still pretty new to Python/Django and I would appreciate it if anybody can help me figure this one out. Thanks in anticipation
Here is my models.py
from django.db import models
class Track(models.Model):
track_title = models.CharField(max_length=250)
track = models.FileField(upload_to='album/')
def __str__(self):
return self.track_title
Here is my index.html
{% load static %}
<!DOCTYPE html>
<html lang="en">
<head>
<meta charset="UTF-8">
<meta name="viewport" content="width=device-width, initial-scale=1.0">
<meta http-equiv="X-UA-Compatible" content="ie=edge">
<title>Document</title>
</head>
<body>
{% for track in tracks %}
<figure>
<figcaption>Audio</figcaption>
<audio controls>
<source src="{{ track.track.url }}" type="audio/mp3">
</audio>
</figure>
{% endfor %}
This is my views.py
from django.shortcuts import render
from .models import Track
def songView(request):
tracks = Track.objects.all()
context = {
'tracks':tracks
}
return render(request, 'album/index.html', context)
And my urls.py
from django.urls import path
from . import views
app_name = 'album'
urlpatterns = [
path('', views.songView, name='song'),
]

Categories

Resources