how to make custom form without database - DJANGO - python

So i want to upload file but only sent to locals storage NOT DATABASE too. But i don't know how to make custom forms.
suddenly, here's my models.py :
from django.db import models
class Audio_store(models.Model):
record=models.FileField(upload_to='mp3/')
forms.py :
from django import forms
from .models import Audio_store
class AudioForm(forms.ModelForm):
class Meta:
model = Audio_store
urls.py :
from django.contrib import admin
from django.conf.urls import url
from . import views
from django.urls import path, re_path
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^decode/$', views.decode),
url(r'^$', views.homepage),
path('audio', views.Audio_store),
]
if settings.DEBUG: #add this
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
fields= ['record']
html:
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{form}}
<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>
</form>

Django has forms.ModelForm which requires DB model and forms.Form which you can use without any model.
https://docs.djangoproject.com/en/4.0/topics/forms/#the-form-class
from django import forms
class YourForm(forms.Form):
upload_file = forms.FileField()
for the fileinput refer https://docs.djangoproject.com/en/4.0/ref/forms/fields/#django.forms.FileField

Related

Django: Page not found , Raised by:django.views.static.serve

I am trying to display a static image in django. When I select image using django admin portal then it's works fine. it is displaying image. But when I select image from my front-end page, I get:
Page not found (404)
Request Method: GET
Request URL: http://127.0.0.1:8000/media/destination-2.jpg
Raised by: django.views.static.server
Here are my codes:
urls.py
from django.urls import path,include
from django.conf import settings
from django.conf.urls.static import static
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from mainapp import views
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('mainapp.urls')),
]
admin.site.site_header = "Login to our web Portal"
admin.site.site_title = "This is Admin Portal"
admin.site.index_title = "Welcome to Amnet"
#urlpatterns += staticfiles_urlpatterns()
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT)
settings.py
STATICFILES_DIRS=[os.path.join(BASE_DIR,'static')
]
MEDIA_URL='/media/'
MEDIA_ROOT=os.path.join(BASE_DIR,'media')
models.py
from django.db import models
# Create your models here.
class Amnet(models.Model):
imagee = models.FileField(default='bg_2.jpg')
views.py
from django.shortcuts import render
from mainapp.models import Amnet
# Create your views here.
def index(request):
if(request.method == "POST"):
imagee= request.POST.get('imagee')
am = Amnet(imagee=imagee)
am.save()
return render(request,'image-main.html')
else:
return render(request,'image-main.html')
html page
<form action="" method="POST">
{% csrf_token %}
<td><input type="file" name="imagee" id="file"></td>
<td><img src="" id="profile-img-tag" width="200px" /></td>
</tr>
</table>
<input type="Submit" value="Submit" id="btn"><br>
</form>
Use enctype="multipart/form-data" to handle file uploads. Add this attribute in the form tag in HTML

AttributeError: module 'users.views' has no attribute 'register'

I am new to Python and Django. Getting this error when running the server. The problem seems to be in 'urls.py' of the project.
File "C:\Users\Desktop\myproject\django_project\django_project\urls.py", line 22, in <module>
path('register/', user_views.register , name = 'register'),
AttributeError: module 'users.views' has no attribute 'register'
This is my urls.py
from django.contrib import admin
from django.urls import path, include
from users import views as user_views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', user_views.register , name = 'register'),
path('', include('blog.urls')),
]
This is register.html under users/templates/users/register.html (users is the name of the app)
{% extends "blog/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Join Today</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Sign Up</button>
</div>
</form>
<div class="border-top pt-3">
<small class="text-muted">
Already Have An Account? <a class="ml-2" href="#">Sign In</a>
</small>
</div>
</div>
{% endblock content %}
This is my views.py
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
def register(request):
form = UserCreationForm()
return render(request, 'users/register.html', {'form':form})
I have also tried creating a separate urls.py for my 'users' app and adding the path there but I am getting the same error.
I am very new to programming so please excuse my inexperience.
Make sure you have a space after register>>> def register (request):
If it is not the issue please check the "views.py" for correct register function under the users folder.
from django.shortcuts import render
from django.contrib.auth.forms import UserCreationForm
# Create your views here.
def register (request):
form = UserCreationForm()
return render(request, 'users/register.html', {'form': form})
Your urls.py should be like this:
from django.contrib import admin
from django.urls import path, include
from .view.py import register
urlpatterns = [
path('admin/', admin.site.urls),
path('register/',register , name = 'register'),
path('', include('blog.urls')),
]
Note: if your views name is views.py
consider this arrange:
you have a users application in your base directory, this app has a users-views.py file that your register function is there.
then your urls.py must be like this:
from django.contrib import admin
from django.urls import path, include
from users import users-views as user_views
urlpatterns = [
path('admin/', admin.site.urls),
path('register/', user_views.register , name = 'register'),
path('', include('blog.urls')),
]
as you can see your users application has no views.py I recommend rename users-views.py to views.py and use your original urls.py.
Is your users/views.py file saved and up to date? Try stopping the server completely, ctrl+c on windows if it's started and double check all your files are up to date then try running the server again.

Django (Python) : Django form is not Displaying

I am making my way into Python and Django programming. However, I struggle with displaying a simple form.
The only element displayed based on the code below is the button, but not (as intended) the entire form. I have already checked the indentation of my code, but have not been able to display the form.
models.py
from django.db import models
from django.utils import timezone
from django.contrib.auth.models import User
from django.urls import reverse
class Story (models.Model):
title = models.CharField(max_length=100)
content = models.TextField()
date_posted = models.DateTimeField(default=timezone.now)
author = models.ForeignKey(User, on_delete=models.CASCADE)
audio = models.FileField(default='SOME STRING', upload_to='audio_stories')
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('story-detail', kwargs={'pk': self.pk})
forms.py
from django import forms
from .models import Story
class Story_Creation(forms.ModelForm):
class Meta:
model = Story
fields = ['title','content','audio']
views.py
from django.shortcuts import render, get_object_or_404, redirect
from django.contrib.auth.models import User
from .models import Story
from .forms import Story_Creation
from django.contrib.auth.mixins import (
LoginRequiredMixin,
UserPassesTestMixin
)
from django.views.generic import (
ListView,
DetailView,
CreateView,
UpdateView,
DeleteView
)
def Create_Audio_Story(request):
if request.method == 'POST':
s_form = Story_Creation(request.POST, request.FILES)
if s_form.is_valid():
s_form.save()
return redirect('suyuh-home')
else:
s_form = Story_Creation()
context = {
's_form': s_form,
}
return render (request, 'story/story_form.html', context)
story urls.py
from django.urls import path
from .views import (
StoryListView,
StoryDetailView,
StoryCreateView,
StoryUpdateView,
StoryDeleteView,
UserStoryListView
)
from .import views
urlpatterns = [
path('', StoryListView.as_view(), name='suyuh-home'),
path('user/<str:username>', UserStoryListView.as_view(), name='user-stories'),
path('story/<int:pk>/', StoryDetailView.as_view(), name='story-detail'), #pk pimarykey for stories
path('story/new/', StoryCreateView.as_view(), name='story-create'),
path('story/<int:pk>/update/', StoryUpdateView.as_view(), name='story-update'),
path('story/<int:pk>/delete/', StoryDeleteView.as_view(), name='story-delete'),
path('about/', views.about, name='suyuh-about'),
]
main urls.py
from django.contrib import admin
from django.urls import path, include
from django.contrib.auth import views as auth_views
from users import views as user_views
from django.conf import settings
from django.conf.urls.static import static
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('story.url')),
path('register/', user_views.register, name='register'),
path('login/', auth_views.LoginView.as_view(template_name='users/login.html'), name='login'),
path('logout/', auth_views.LogoutView.as_view(template_name='users/logout.html'), name='logout'),
path('password-reset/', auth_views.PasswordResetView.as_view(template_name='users/password_reset.html'), name='password-reset'),
path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'), name='password_reset_complete'),
path('password-reset/done/', auth_views.PasswordResetDoneView.as_view(template_name='users/password_reset_done.html'),name='password_reset_done'),
path('password-reset-confirm/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(template_name='users/password_reset_confirm.html'), name='password_reset_confirm'),
path('profile/', user_views.profile, name='profile'),
]
if settings.DEBUG:
urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
story_form.html
{% extends "story/base.html" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">New Story</legend>
{{ s_form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Create Story</button>
</div>
</form>
</div>
{% endblock content %}
I do not see my mistake at the moment and therefore do not know how to continue. Thanks a lot for your support. I really appreciate every hint!
Greetings!
A couple of things to be updated in your code:
In main/urls.py change the parameter passed to the include method, since as I see it, you file in the app story is called urls.py and not url.py
path('', include('story.urls'))
In story/urls.py you are not associating the view called Create_Audio_Story() with any path. If you want to have this view shown at /story/new, then you should update the file as follows:
from . import views
urlpatterns = [
path('story/new/', views.Create_Audio_Story, name='story-create'),
]
return render (request, 'story_form.html', context)
Try that code instead

Unable to render form in Django

I'm trying to import a simple single-field form in Django, and I have gone through plenty of Tutorial Videos on YouTube describing the same. Yet, I'm unable to render the simple form on my web-app. I'm pretty sure I'm doing something really stupid that is still oblivious to me.
I'll also post in the folder structure so you can suggest if I'm defining the class/function in the wrong views.py file.
The appropriate source codes are as follows:
earthquake/views.py File
from django.shortcuts import render
from earthquake.forms import HomeForm
from django.views.generic import TemplateView
class HomeView(TemplateView):
template_name = 'earthquake/home.html'
def get(self, request, *args, **kwargs):
form1 = HomeForm()
argf = {
'myform': form1
}
return render(request, self.template_name, argf)
forms.py
from django import forms
class HomeForm(forms.Form):
post = forms.CharField()
home.html (snippet)
<div class="container">
<div class="jumbotron">
<h1>Query Form</h1>
<p>Please Enter the parameters you want to query against the USGS Earthquake DB</p>
<div class="container">
<form class="" method="post" action="">
{% csrf_token %}
{{ myform }}
<button type="submit" class="btn btn-success">Search</button>
</form>
</div>
</div>
</div>
Django Project urls (interview.py/urls.py)
from django.contrib import admin
from django.urls import path, include
from interview.views import login_redirect
from interview import views
from django.contrib.auth.views import LoginView
from django.contrib.auth.views import LogoutView
urlpatterns = [
path('', login_redirect, name='login_redirect'),
path('admin/', admin.site.urls),
path('home/', include('earthquake.urls')),
path('login/', LoginView.as_view(template_name='earthquake/login.html'), name="login"),
path('logout/', LogoutView.as_view(template_name='earthquake/logout.html'), name="logout"),
path('register/', views.register, name='register'),
]
App URLS (interview/earthquake/urls.py)
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.home, name='home'),
]
Folder Structure
https://i.stack.imgur.com/zoehT.jpg
(In case you're unable to see the last entry in the image, it's the main views.py present in the project folder).
The following is the snapshot of the render I currently get:
https://i.stack.imgur.com/kXR7W.jpg
I see that in your home views file your class based view is called
HomeView(TemplateView)
Yet in your app urls you are including the view as view.home when it should be
view.HomeView
to add to that, this is a classed based view so your urls page for that should look like:
from django.urls import path, include
from . import views
urlpatterns = [
path('', views.home.as_view(), name='home'),
]
Since this is a class based view.

Django-CMS - Django Model Form not rendering

I'm building a new site in Django with Django-CMS that needs a form to filter JSON results and return the filtered set.
My issue is that, initially, I can't even get the Django Model Form to render yet I can get the CSRF token to work so the form is technically rendering, but the inputs/fields aren't showing up at all.
models.py:
from django.db import models
from .jobs.jobs import *
roles = get_filters()
loc = roles[0]
j_type = roles[1]
industry = roles[2]
class Filter(models.Model):
country = models.CharField(max_length=255)
job_type = models.CharField(max_length=255)
industry = models.CharField(max_length=255)
search = models.CharField(max_length=255)
jobs/jobs.py
try:
from BeautifulSoup import BeautifulSoup
except ImportError:
from bs4 import BeautifulSoup
import urllib3
import json
http = urllib3.PoolManager()
def get_filters():
response = http.request('GET', 'http://206.189.27.188/eo/api/v1.0/jobs')
jobs = json.loads(response.data.decode('UTF-8'))
job_list = []
for job, values in jobs.items():
job_list.append(values)
roles_data = []
for job in job_list[0]:
roles_data.append(job)
roles_data = sorted(roles_data, key=lambda role : role["id"], reverse=True)
loc = []
j_type = []
industry = []
for role in roles_data:
loc.append(role['location'])
j_type.append(role['type'])
industry.append(role['industry'])
return loc, j_type, industry
views.py
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import FilterForm
def index(request):
form = FilterForm()
context = {
'form': form,
}
return render(request, 'blog.html', context)
forms.py
from django.forms import ModelForm
from .models import Filter
class FilterForm(ModelForm):
class Meta:
model = Filter
fields = ['country', 'job_type', 'industry', 'search']
urls.py
from __future__ import absolute_import, print_function, unicode_literals
from cms.sitemaps import CMSSitemap
from django.conf import settings
from django.conf.urls import include, url
from django.conf.urls.i18n import i18n_patterns
from django.contrib import admin
from django.contrib.sitemaps.views import sitemap
from django.contrib.staticfiles.urls import staticfiles_urlpatterns
from django.views.static import serve
from . import views
admin.autodiscover()
urlpatterns = [
url(r'^sitemap\.xml$', sitemap,
{'sitemaps': {'cmspages': CMSSitemap}}),
url(r'^accounts/', admin.site.urls),
url(r'^services/latest-roles/', views.filter_form, name="filter_form" )
]
urlpatterns += i18n_patterns(
url(r'^admin/', include(admin.site.urls)), # NOQA
url(r'^', include('cms.urls')),
)
# This is only needed when using runserver.
if settings.DEBUG:
urlpatterns = [
url(r'^media/(?P<path>.*)$', serve,
{'document_root': settings.MEDIA_ROOT, 'show_indexes': True}),
] + staticfiles_urlpatterns() + urlpatterns
blog.html
{% extends 'includes/templates/layout.html' %}
{% load cms_tags i18n sekizai_tags zinnia %}
{% block main_content %}
{% include 'components-header-image.html' %}
<section class="module">
<div class="container">
<div class="row">
<div class="col-md-12 m-auto text-center">
<form action="POST" class="col-md-12">
{% csrf_token %}
{{ form.as_p }}
<button name="submit" class="btn btn-brand">Search</button>
</form>
{% get_all_roles%}
</div>
<div class="col-md-12">
<div class="space" data-MY="120px"></div>
</div>
<div class="col-md-12 flex-center text-center">
{% placeholder 'jobs-bottom-statement' %}
</div>
</div>
</div>
</section>
<!-- Image-->
{% include 'components-contact.html' %}
<!-- Image end-->
{% endblock %}
Sorry for the masses of information, just wanted to include anything anyone might need.
As I said, the CSRF token is displaying, nothing is throwing an error anywhere but it's just not displaying the fields at all.
Really appreciate any help or advice.
I'm 95% sure your view isn't being called.
You need to integrate your application as a CMS apphook or hard code your URLs into your root urls.py which is the easier integration test as it doesn't depend on CMS integration.
So Add your view to your URLs like this;
urlpatterns += i18n_patterns(
url(r'^admin/', include(admin.site.urls)), # NOQA
url(r'^blog/$', views.index, name='blog'),
url(r'^', include('cms.urls')),
)
Then go to localhost:8000/blog/ in your browser & you should hit your view.
To confirm you're hitting it you could make a simple amendment to your view;
def index(request):
form = FilterForm()
context = {
'form': form,
}
print "index hit"
return render(request, 'blog.html', context)
Then you'll see "index hit" in your console if your view is called.

Categories

Resources