Django do not render ModelForm - python

I am working on a little project on Django, I have had some issues on rendering ModelForm. In main.html tag {{form.ad_p}} doesn't seem working. I only see "Save" button and don't see any ModelForm fields.
If I put below code to shell
form = AddPath()
form.as_p()
I see:
form.as_p()
u'<p><label for="id_name">Name:</label> <input id="id_name" maxlength="200" name="name" type="text" /></p>\n<p><label for="id_route_data">Route data:</label> <textarea cols="40" id="id_route_data" name="route_data" rows="10">\r\n</textarea></p>'
Can you explain, what am I doing wrong?
I already searched on stackoverflow, but same problem hasn't been resolved. I hope, I'll be more lucky
models.py:
from django.db import models
from django.contrib.auth.models import User
class Path(models.Model):
user = models.ForeignKey(User)
name = models.CharField(max_length='200')
route_data = models.TextField()
def __unicode__(self):
return self.name
views.py:
from django.shortcuts import render_to_response
from django.http import HttpResponse
from django.core.context_processors import csrf
from google_maps.forms import AddPath
def index(request):
args = {}
args.update(csrf(request))
form = AddPath()
return render_to_response('main.html', args)
def add_path(request):
#me = request.user
me = 'test'
if request.method == 'POST':
form = AddPath(request.POST)
if form.is_valid():
tmpForm = form.save(commit=False)
tmpForm.user = me
tmpForm.save()
return HttpResponse('Saved')
else:
return HttpResponse(form.errors)
main.html
{% extends 'basis.html' %}
{% block leftbar %}
<form action={% url 'add_path' %} method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="hidden", id="coordinate" name="coordinate"/>
<input type="submit" name="submit" value="Save"/>
</form>
{% endblock %}

Related

User provided email over the landing page is not showing in the database in Django

I am trying to put a subscribe email form on my landing page, however, I am not able to see the input email addresses on my admin(backend). Why it's not writing user-provided email input to my database?
base.html
<form method="post" > {% csrf_token %}
<label >Your Email: </label>
<input
type="text">
<input type="submit" value="Submit">
</form>
models.py
from django.db import models
from django.urls import reverse
# Create your models here.
class EmailSubmit(models.Model):
email_name=models.EmailField(max_length=30)
forms.py
from django import forms
from .models import EmailSubmit
class EmailForm(forms.ModelForm):
class Meta:
model=EmailSubmit
fields=[
'email_name',
]
views.py
from django.shortcuts import render
from .forms import EmailForm
def index(request):
return render(request, 'base.html')
def email_post(request):
form = EmialForm(request.POST or None)
if form.is_valid():
form.save()
context={
'form':form
}
return render(request, 'base.html', {'form': form})
so when the user puts the email and submit, the page refreshes but nothing shows up on the backend. What is wrong with my code here?
Input field should have a name parameter
<input name="email_name">
or
<form method="post">
{% csrf_token %}
{{ form.email_name.errors }}
{{ form.email_name.label_tag }}
{{ form.email_name }}
<input type="submit" value="Submit">
</form>

Upload multi img to 1 post on Django ? How do that?

I want to upload multi img to 1 post on Django. I used ImageField in models.py. But it's just can upload 1 image to 1 post. How can i upload multi image to 1 post with Django or someways to solved that problem. Thank you so much.
Sorry for the past answer.
I think this is the best way.
models.py
from django.db import models
from django.template.defaultfilters import slugify
class Post(models.Model):
title = models.CharField(max_length=128)
body = models.CharField(max_length=400)
def get_image_filename(instance, filename):
title = instance.post.title
slug = slugify(title)
return "post_images/%s-%s" % (slug, filename)
class Files(models.Model):
post = models.ForeignKey(Post, default=None, on_delete=models.CASCADE)
files = models.FileField(upload_to=get_image_filename, verbose_name='File')
I did not create a form for the files because we will write it manually in the template.
forms.py
from django import forms
from .models import Post, Images
class PostForm(forms.ModelForm):
title = forms.CharField(max_length=128)
body = forms.CharField(max_length=245, label="Item Description.")
class Meta:
model = Post
fields = ('title', 'body', )
views.py
from django.shortcuts import render
from django.contrib import messages
from django.http import HttpResponseRedirect
from .forms import PostForm
from .models import Post, Files
def post(request):
if request.method == 'POST':
print(request.FILES.getlist('files'))
postForm = PostForm(request.POST)
if postForm.is_valid():
post_form = postForm.save(commit=False)
post_form.save()
if request.FILES.getlist('files'):
for file in request.FILES.getlist('files'):
obj = Files(post=post_form, files=file)
obj.save()
messages.success(request, "Yeeew, check it out on the home page!")
return HttpResponseRedirect("/")
else:
print(postForm.errors)
else:
postForm = PostForm()
return render(request, 'index.html', {'postForm' : postForm})
index.html
<html>
<form id="post_form" method="post" action="" enctype="multipart/form-data">
{% csrf_token %}
{% for hidden in postForm.hidden_fields %}
{{ hidden }}
{% endfor %}
{% for field in postForm %}
{{ field }} <br />
{% endfor %}
<input type="file" id="files" name="files" multiple><br>
<input type="submit" name="submit" value="Submit" />
</form>
</html>
We make such a field for the model of files that we do not form.
<input type="file" id="files" name="files" multiple><br>
You can select multiple files and upload them by holding down CTRL or Shift.
i think you are asking inline models,
https://docs.djangoproject.com/en/2.2/ref/contrib/admin/#inlinemodeladmin-objects

Form validation error not being raised in django

I cannot get my Django form to raise a ValidationError when I try to create a custom field validation. I can see the new hidden input field, but when I try to enter a value it doesn't seem to detect an error.
I also tried def clean(self) instead of clean_honeypot() and that didn't work either.
What am I doing wrong?
forms.py:
from django import forms
class SuggestionForm(forms.Form):
name = forms.CharField()
email = forms.EmailField()
suggestion = forms.CharField(widget=forms.Textarea)
honeypot = forms.CharField(required=False, widget=forms.HiddenInput, label="Leave Empty")
def clean_honeypot(self):
honeypot = self.cleaned_data['honeypot']
if len(honeypot) > 0:
raise forms.ValidationError(
'Honeypot should be left empty. Bad bot!'
)
return cleaned_data
views.py:
from django.contrib import messages
from django.core.mail import send_mail
from django.urls import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import render
from . import forms
def hello_world(request):
return render(request, 'home.html')
def suggestion_view(request):
form = forms.SuggestionForm()
if request.method == 'POST':
form = forms.SuggestionForm(request.POST)
if form.is_valid():
send_mail(
'Suggestion from {}'.format(form.cleaned_data['name']),
form.cleaned_data['suggestion'],
'{name} <{email}>'.format(**form.cleaned_data),
['leigh.christopher2#gmail.com'])
messages.add_message(request, messages.SUCCESS,
"Thanks for your suggestion")
return HttpResponseRedirect(reverse('suggestion'))
return render(request, 'suggestion_form.html', {'form': form})
template:
{% extends "layout.html" %}
{% load static %}
{% block title %}Suggest an idea!{% endblock %}
{% block content %}
<div class="container">
<div class="row">
<form action="" method="POST">
{{ form.as_p }}
{% csrf_token %}
<input type="submit" class="button">
</form>
</div>
</div>
{% endblock %}

Django - Comment form in an existing template. How to define it in views.py?

I have 4 models: Post, Comment, Blogger and User.
I have an post_description template, in below of that, I have placed a comment form.
But how to define it in views? My problem is - to get its username, like the user who is logged in will be stored as "posted_by" and in which blog post he post will be stored as "topic" of the blog.
How to store these information, so they get automatically added?
Form that i has described in post_desc.html
{% if user.is_authenticated %}
<form method="post">
{% csrf_token %}
<input type="text" name="comment" style="width: 800px; height: 145px;">
<button type="submit">Submit Comment</button>
</form>
{% else %}
<p>Login to comment</p>
{% endif %}
Current view of that post_desc:
def post_desc(request, pk):
post = get_object_or_404(Post, pk=pk)
return render(request, 'post_desc.html', {'post': post})
Now the user can be accessed as follows in the views:
user = request.user
And about the Topic, maybe you could add a hidden input in your form to get blog id , as you are already passing the post in the form template. :
<form method="post">
{% csrf_token %}
<input type="text" name="comment" style="width: 800px; height: 145px;">
<input type="hidden" name="topic" value="{{ post.id }}">
<button type="submit">Submit Comment</button>
And when posted in the view you can get blog by:
post_id = request.POST.get('topic')
post = get_object_or_404(Post, pk=post_id)
And then finally proceeding with your actual flow.
I think what you need here is basic model form setup.
I am hoping there is a blog entry and comments associated with it and you want a commenting functionality on each post.
This is rough quick answer.
Your models.py looks like this:
from django.db import models
from django.conf import settings
class Comments(models.Model):
posted_by = models.ForeignKey(settings.AUTH_USER_MODEL)
topic = models.ForeignKey(Blog)
comment = models.TextField()
last_modified = models.DateTimeField(auto_now=True)
created_on = models.DateTimeField(auto_now_add=True)
You setup a model form in your forms.py
from django.forms import ModelForm
from .models import Comments
class CommentForm(ModelForm):
class Meta:
model = Comments
fields = ['comment']
You setup a model form post view.
#login_required
#require_http_methods(["POST"])
def post_comments_controller(request, identifier):
from .forms import CommentForm
comment_form = CommentForm(request.POST or None)
if comment_form.is_valid():
comment_obj = comment_form.save(commit=False)
topic = Blog.objects.get(id=identifier)
comment_obj.posted_by = request.user
comment_obj.item = topic
comment_obj.save()
return HttpResponse("Done")
else:
return HttpResponseBadRequest()
You setup a entry point in your urls.py
from django.conf.urls import patterns, url
from django.conf import settings
urlpatterns = patterns('',
url(r'^/blog/(?P<identifier>[d]+)/comment$',
'views.post_comments_controller', name='post_comment')
)
And your finally the html form
{% if user.is_authenticated %}
<form method="POST" action="{% url 'post_comment' blog.id %}">
{% csrf_token %}
<input type="text" name="comment" style="width: 800px; height: 145px;">
<button type="submit">Submit Comment</button>
</form>
{% else %}
<p>Login to comment</p>
{% endif %}
This is not tested overall. Let me know.
From Django docs you can use FormMixin with DetailView like this:
class AuthorInterestForm(forms.Form):
message = forms.CharField()
class AuthorDetail(FormMixin, DetailView):
model = Author
form_class = AuthorInterestForm
def get_success_url(self):
return reverse('author-detail', kwargs={'pk': self.object.pk})
def post(self, request, *args, **kwargs):
if not request.user.is_authenticated:
return HttpResponseForbidden()
self.object = self.get_object()
form = self.get_form()
if form.is_valid():
return self.form_valid(form)
else:
return self.form_invalid(form)
def form_valid(self, form):
# Here, we would record the user's interest using the message
# passed in form.cleaned_data['message']
return super().form_valid(form)

Image field didn't get saved, raises error 'This field is required'

models.py:
from django.db import models
from django.contrib.auth.models import User
class Electronics(models.Model):
ELEC_CHOICES = (
('LAP', 'Laptops'),
('MOB', 'Mobiles'),
('WAT', 'Watches'),
('CAM', 'Camera'),
)
elec_name = models.CharField(max_length=3, choices=ELEC_CHOICES)
elec_image = models.ImageField('Label', upload_to='C:/Users/User/Desktop/')
elec_price = models.IntegerField('Price')
elec_stock = models.BooleanField(default=False)
forms.py:
from django import forms
from django.forms import ModelForm
from .models import Electronics
class ElectronicsForm(ModelForm):
class Meta:
model = Electronics
fields = '__all__'
views.py:
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .models import Electronics
from .forms import ElectronicsForm
# Create your views here.
def eleclist(request):
elec = Electronics.objects.order_by('elec_name')
return render(request, 'index.html', {'elec': elec})
def elecadd(request):
if request.method == 'POST':
form = ElectronicsForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return HttpResponseRedirect(reverse('shopp:eleclist'))
else:
print(form.errors)
else:
form = ElectronicsForm()
return render(request, 'add.html', {'form': form})
my add.html:
<html>
<head><title>Electronics</title></head>
<body>
<form method = "post">
{% csrf_token %}
{{form.as_p}}
<input type="submit" name="submit" value="create">
</form>
</body>
</html>
I'am first time trying to upload an image using django model forms. But when I clicked submit, the image didn't get saved. It raises error 'this field is required'.
I've looked in some django docs also, but it has very concise material.
You need to add enctype="multipart/form-data" to your form tag, otherwise your file won't be uploaded to server. So update your form template to:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" name="submit" value="create">
</form>

Categories

Resources