I'm receiving no errors and everything seems fine but the fields to my form will not show up.
My form:
from django import forms
class ContactForm(forms.Form):
name = forms.CharField(required=False, max_length=100, help_text='100 characters max')
email = forms.EmailField(required=True)
comment = forms.CharField(required=True, widget=forms.Textarea)
My view:
from .forms import ContactForm
def contact(request):
form = ContactForm(request.POST or None)
if form.is_valid():
print(request.POST)
context = {'form': form}
return render(request, 'contact.html', context)
contact.html template:
<form method="POST" action=""> {% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" class="btn btn-default" />
</form>
base.html template:
{% block content %}
{% endblock content %}
{% include "contact.html" %}
</div>
What am I missing? The template housing the form is not surrounded by any block tags because the template is being {% include[d] %} into my base.html.
Additional details: The form and view are in their own separate 'contact' app, and I haven't configured any urls for the contact app as I planned on simply including the template into base.html
Edit--adding urls config:
main urls.py for the project:
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^', include("projects.urls", namespace='projects')),
]
urls.py for my 'project' app:
urlpatterns = [
url(r'^$', projects_home, name='home'),
url(r'^(?P<slug>[\w-]+)/$', project_detail, name='detail'),
]
As for the 'contact' app, I have not configured any urls--would this be wrong? I thought I'd be able to simply make the views/form(as displayed in original post) for the 'contact' app and bring the form into my templates.
Related
I am having trouble working with models and forms in Django. A little clarification and help will be highly appreciated!
I am really confused because I do not see the form in my html url page. I see everything else but not the form. I assume, I'm missing something.
This is my forms.py
from django import forms
from .models import TwitterContainer
class TwitterUpdateForm(forms.ModelForm):
class Meta:
model = TwitterContainer
fields = ["Twitter_API_key", "Twitter_API_key_secret", "Twitter_API_token", "Twitter_API_token_secret"]
This is my models.py
from django.db import models
from django.contrib.auth.models import User
class TwitterContainer(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
Twitter_API_key = models.fields.CharField(max_length=100)
Twitter_API_key_secret = models.fields.CharField(max_length=100)
Twitter_API_token = models.fields.CharField(max_length=100)
Twitter_API_token_secret = models.fields.CharField(max_length=100)
def __str__(self):
return f'{self.user.username} Twitter Container'
This is my views.py
from django.shortcuts import render, redirect
from django.contrib import messages
from django.contrib.auth.decorators import login_required
from .forms import TwitterUpdateForm
#login_required
def twitter(request):
tw = TwitterUpdateForm(request.POST, instance=request.user)
if tw.is_valid():
tw.save()
messages.success(request, f'NICE!')
return redirect ('home')
else:
tw = TwitterUpdateForm(request.POST, instance=request.user)
context = {'tw': tw}
return render(request, 'twitter_container/twitter_container.html', context=context)
And last but not least, this is my html file.
{% extends 'home/base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="content-section">
</div>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<fieldset="form-group">
<legend class="border-bottom mb-4">Profile Information</legend>
{{ u_form|crispy }}
{{ p_form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Update</button>
</div>
</form>
</div>
{% endblock content %}
Oh, and my urls.py as well.
urlpatterns = [
path('admin/', admin.site.urls),
path('', include('home.urls')),
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('profile/', user_views.profile, name='profile'),
path('twitter/', twitter_views.twitter, name='twitter'),
]
The issue, I'm facing is that I'm unable to display the form fields from the model to the html. I want to be able to import information into the fields and update it to the database.
Please, do not judge me hard, I am completely newbie.
Thanks in advance.
First of all, you need to add action attribute in your form tag to call the view function when form gets submitted.
It should be like this:
<form method="POST" action ="{% url 'twitter' %}" enctype="multipart/form-data">
Second thing that i found wrong in your html code is, why did you use u_form and p_form as a context variable? it should be 'tw' as per your view.
Try it out with above changes, it might help you out with your requirements.
I am trying to build a user login/signup page using Django. Everything works fine except when I try to register new users by clicking on the register button, the newly registered users are not being reflected in the database in 'Django Administration' page after I login as an admin. Please help.
Here's my code:
urls.py-login
from django.contrib import admin
from django.urls import path,include
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/', include('accounts.urls'))
]
urls.py-accounts
from django.urls import path
from . import views
urlpatterns = [
path('', views.indexView, name = "home"),
path('dashboard/', views.dashboardView, name = "dashboard"),
# path('login/',),
path('register/',views.registerView, name = "register_url"),
# path('logout,'),
]
views.py
from django.shortcuts import render, redirect
from django.contrib.auth.forms import UserCreationForm
# Create your views here.
def indexView(request):
return render(request, 'index.html')
def dashboardView(request):
return render(request, 'dashboard.html')
def registerView(request):
if request.method == "POST":
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
return redirect('login_url')
else:
form = UserCreationForm()
return render(request, 'registration/register.html', {'form':form})
index.html
<!DOCTYPE html>
<html>
<head>
<title>Petrol Pump Management System</title>
</head>
<body>
{% block content %}
<h1>User Authentication</h1>
{% endblock %}
</body>
</html>
register.html
{% extends 'index.html'%}
{% block content %}
<h1>Create new account</h1>
<form method = "POST">
{% csrf_token %}
{{form.as_p}}
<button type="submit">Register</button>
</form>
{% endblock %}
I'm using Django 3.0.8
in Python version 3.8.2
I'm getting an FieldError at /post/new/
Exception Type: FieldError
Exception Value: Unknown field(s) (content) specified for Post
PostCreateView is a class-based view in my views.py of under the blog app of my current project
My blog/views.py is here:-
from django.shortcuts import render
from .models import Post
from django.views.generic import (
ListView,
DetailView,
CreateView,
)
# Create your views here.
def home(request):
context = {
'posts': Post.objects.all()
}
return render(request, 'blog/home.htm', context)
def about(request):
return render(request, 'blog/about.htm', {'title': 'About'})
# return HttpResponse('<h1> Blog - About page that we want you to see </h1>')
def order(request):
return render(request, 'blog/order.htm')
class PostListView(ListView):
model = Post
template_name = 'blog/home.htm' # <app>/<model>_<viewtype>.html
context_object_name = 'posts'
ordering = ['-date_posted']
class PostDetailView(DetailView):
model = Post
class PostCreateView(CreateView):
model = Post
fields = ['title', 'content']
My blog/urls.py is here:
from django.urls import path
from . import views
from .views import (
PostListView,
PostDetailView,
PostCreateView
)
urlpatterns = [
path('about/', views.about, name='blog-about'),
path('order/', views.order, name='blog-order'),
path('', PostListView.as_view(), name='blog-home' ),
path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail' ),
path('post/new/', PostCreateView.as_view(), name='post-create' ),
]
My blog/templates/blog/post_form.html is here:-
{% extends "blog/base.htm" %}
{% load crispy_forms_tags %}
{% block content %}
<div class="context-section">
<form method="POST">
{% csrf_token %} <!-- for security perpose -->
<fieldset class="form-group">
<legend class="boder-bottom mb-4">Blog Post</legend>
{{ form|crispy }}
</fieldset>
<div class="form-group">
<button class="btn btn-outline-info" type="submit">Post</button>
</div>
</form>
</div>
{% endblock content %}
What wrong is with the code, Please help!!!
I am new to Django and I am completely lost-in here?
I will be very much thankful for your suggestions!!
Thanks and Wellcome
I am using a modelformset_factory method with forms containing only an ImageField. The Model the forms are based on contains a user field that has a many-to-one relationship with a User Model that extends AbstractUser(See Extending User Model with Abstract User). Currently, each instance of a user has a correlating User Profile, but I would also like to allow the user to upload a gallery of images to their profile.
models.py
class Gallery(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=True)
image = models.ImageField(upload_to='user_gallery', blank=True, null=True)
def create_gallery(sender, **kwargs):
if kwargs['created']:
user_gallery = Gallery.objects.create(user=kwargs['instance'])
user_gallery.save();
post_save.connect(create_gallery, sender=User)
forms.py
class GalleryForm(forms.ModelForm):
image = forms.ImageField(label='FormImage')
class Meta:
model = Gallery
fields = ['image']
views.py
def EditProfile(request):
GalleryFormSet = modelformset_factory(Gallery, form=GalleryForm, extra=3, max_num=3)
if request.method == "POST":
formset = GalleryFormSet(request.POST, request.FILES)
if formset.is_valid():
for form in formset.cleaned_data:
my_image = form['image']
photo = Gallery(user=request.user, image=my_image)
photo.save()
return render(request, 'user_handler/editprofile.html', {'formset': formset})
else:
formset = GalleryFormSet()
return render(request, 'user_handler/editprofile.html', {'formset': formset})
Template
<form id="post_form" method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{{form.image}}
<img src="{{form.image.url}}"/>
{% endfor %}
<input type="submit" name="submit" value="Submit" />
</form>
The problem I'm have is that using {{ form.image }} produces this result:
... and using {{ form.image.url }} within an image's source tag produces absolute nothing at all. When I inspect the element I contain it in, it states the source is unknown. Obviously, the images are being saved in the DB as I'd like, but I can't get the .url functionality to work. And YES, I do have the media root an all defined:
settings.py
BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__)))
STATIC_URL = '/static/'
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'HighlightPage_Project/media')
urls.py
urlpatterns = [
url(r'^$', views.Login_Redirect),
url(r'^account/', include('user_handler_app.urls')),
url(r'^admin/', admin.site.urls),
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
Try to replace your code with the following code:
<img src="{{form.image.url}}"/>
with:
<img src="{{form.instance.image.url}}"/>
Try to replace your code with the following code:
views.py
def EditProfile(request):
GalleryFormSet = modelformset_factory(Gallery, form=GalleryForm, extra=3, max_num=3)
if request.method == "POST":
formset = GalleryFormSet(request.POST, request.FILES)
if formset.is_valid():
for form in formset.cleaned_data:
my_image = form['image']
photo = Gallery(user=request.user, image=my_image)
photo.save()
return render(request, 'user_handler/editprofile.html', {'formset': formset})
else:
user_images = Gallery.objects.filter(user=request.user)
initial_images = [{'image': i.image, 'image_url': i.image.url} for i in user_images if i.image]
formset = GalleryFormSet(initial=initial_images)
return render(request, 'user_handler/editprofile.html', {'formset': formset})
Template
<form id="post_form" method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
{{ formset.management_form }}
{% for form in formset %}
{{form.image}}
<img src="{{form.initial.image_url}}"/>
{% endfor %}
<input type="submit" name="submit" value="Submit" />
I am trying to create a very basic form that allows the user to upload a txt file. the function form.is_valid() always fails and I don't know what to do. This is my code: (very similar to the example in the django documentation):
views.py
from django import forms
from django.http import HttpResponse
from django.shortcuts import render
class UploadFileForm(forms.Form):
# title = forms.CharField(max_length=50)
file = forms.FileField()
def handle_uploaded_file(f):
with open('some/file/name.txt', 'wb+') as destination:
for chunk in f.chunks():
destination.write(chunk)
def home(request):
if request.method == 'POST':
print(1)
form = UploadFileForm(request.POST, request.FILES)
print(form.errors)
print(2)
if form.is_valid():
print(3)
handle_uploaded_file(request.FILES['file'])
return HttpResponse('thanks')
else:
form = UploadFileForm()
return render(request, 'home.html', {'form': form})
home.html
{% extends "base.html" %}
{% block content %}
<div>
<div class="'chooseFile'">
<h3>Choose file to attach</h3>
</div>
<form action="" method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.file }}
<button type="submit" class="save btn btn-default" value="Submit"></button>
</form>
</div>
{% endblock %}
url.py
from django.urls import path
from django.contrib import admin
from django.conf.urls import url
from adoptions import views
urlpatterns = [
path('admin/', admin.site.urls),
url(r'^$', views.home, name='home'),
url(r'^$', views.home, name='/success/url/'),
]