"This field is required" when field is populated on Django modelForm - python

After clicking the upload button on a form I get a bullet point beneath the 'Job ID' field stating "This field is required." even though I have values enterred into the field. Here is my code:
forms.py:
class UploadFileForm(forms.ModelForm):
class Meta:
model = Job
fields = ['jobID',
'original_file']
labels = { 'jobID': _('Job ID'),
'original_file': _('File'),}
error_messages = {
'jobID': {'max_length': _("Job ID is limited to 50 characters."),
},
NON_FIELD_ERRORS: {
'unique_together': "%(model_name)s's %(field_labels)s are not unique.",
}
}
models.py:
from __future__ import unicode_literals
from django.db import models
from django.utils import timezone
class Job(models.Model):
user = models.ForeignKey('auth.User')
original_file = models.FileField()
jobID = models.CharField(max_length=50)
rev = models.IntegerField()
create_date = models.DateTimeField(default = timezone.now)
def save(self):
"Get last value of rev considering jobID and User and increment"
"see https://stackoverflow.com/questions/1065089/auto-increment-a-value-in-django-with-respect-to-the-previous-one"
last_rev = Job.objects.filter(user=self.user).filter(jobID=self.jobID).order_by('-rev')
if last_rev:
rev = last_rev[0].rev + 1
else:
rev = 1
super(Job,self).save()
def __unicode__(self):
return self.jobID + " rev " + str(self.rev)
class Meta:
indexes = [
models.Index(fields=['user','jobID']),
]
unique_together = ("user","jobID","rev")
ordering = ['-create_date']
views.py
from __future__ import unicode_literals
from django.shortcuts import render
from django.http import HttpResponseRedirect
from .forms import UploadFileForm
from .models import Job
# Create your views here.
def upload(request):
if request.method == 'POST':
form = UploadFileForm(request.POST, request.FILES)
if form.is_valid():
form.save()
return render(request,'precheck/prestage.html')
else:
form = UploadFileForm()
return render(request, 'precheck/upload.html',{'form': form})
def success(request):
return render(request, 'precheck/prestage.html')
upload.html
{% extends 'base.html' %}
{% block content %}
<h2>Upload File</h2>
{% if error %}
{{ error }}
<br />
<br />
{% endif %}
<form method = "POST" action="{% url 'precheck:upload' %}">
{% csrf_token %}
{{ form.as_p }}
<br />
<input type="submit" class="btn btn-primary" value="Upload">
</form>
{% endblock %}
I tried manually building the form (ie not using a modelform) with the same results. Thanks for the help.
EDIT:
Changing the form to include enctype="multipart/form-data" did the trick:
<form method = "POST" action="{% url 'precheck:upload' %}" enctype="multipart/form-data">

The error is not for jobID, but for original_file. This is because you are not using the enctype="multipart/form-data" attribute on the form element.

Related

ModelForm with multiple values not responsive

so I encountered this problem with Django and ModelForms. Everything loads as expected but when I'm trying to send data by hitting Enter nothing happens.
models.py
class Drinks(models.Model):
name = models.CharField(max_length=50)
number = models.DecimalField(decimal_places=2, max_digits=2000)
def __str__(self):
return self.name
forms.py ( I tried with list and tuple as well )
class DrinksForm(forms.ModelForm):
class Meta:
model = Drinks
fields = [
'name',
'number'
]
views.py
def DrinksView(request):
form = DrinksForm(request.POST or None)
if form.is_valid():
print("VALIDATION COMPLETE")
form.save()
form = DrinksForm()
return render (request, 'form2.html', { 'form' : form })
template.html
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
</form>
admin.py
from django.contrib import admin
from .models import Drinks
admin.site.register(Drinks)
I did all necessary migrations.
Any Ideas what im doing wrong?
Your form doesn't have a submit button:
<form method="POST">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" />
</form>
For your view, consider this instead:
def new_drink_view(request):
if request.method == "POST":
form = DrinksForm(request.POST)
# check if valid
# ...
else:
form = DrinksForm()
return render (request, 'form2.html', { 'form' : form })
Be sure to import the DrinksForm form.

Uploading and retrieving files from django frontend to postgresql backend

This is my table in postgres:
How would I bring this into the frontend so that users can upload their documents without having to access the DB. Right now I can only upload docs into the filesystem instead of the DB:
views.py:
def upload(request):
if request.user.is_authenticated:
username = request.user.username
if request.method == 'POST' and request.FILES['myfile']:
myfile = request.FILES['myfile']
fs = FileSystemStorage()
filename = fs.save(myfile.name, myfile)
uploaded_file_url = fs.url(filename)
return render(request, 'app/upload.html', {
"uploaded_file_url": uploaded_file_url,
"username": username,
})
return render(request, 'app/upload.html', {
"username": username,
})
upload.html:
{% if form.errors %}
<p>You did not select a file to upload!</p>
{% endif %}
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
<input type="file" name="myfile">
<button type="submit">Upload</button>
</form>
{% if uploaded_file_url %}
<p>File uploaded at: {{ uploaded_file_url }}</p>
{% endif %}
models.py:
class Document(models.Model):
Document_name = models.CharField(max_length=255, default='Document_name')
Date = models.DateField()
Client_id = models.ForeignKey(ClientDetail, on_delete=models.CASCADE)
def __str__(self):
return self.Document_name
Schema:
Also how would I retrieve the uploaded documents.
An example for you:
settings.py
MEDIA_URL = '/media/'
MEDIA_ROOT = os.path.join(BASE_DIR, 'media')
urls.py
from django.conf.urls.static import static
urlpatterns = [
...
] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT)
models.py
from django.core.validators import FileExtensionValidator
class Document(models.Model):
name = models.CharField(max_length=255, default='Document_name')
date = models.DateField()
client = models.ForeignKey(ClientDetail, on_delete=models.CASCADE)
myfile = models.FileField(validators=[
FileExtensionValidator(allowed_extensions=['pdf', 'doc', 'ppt', 'xlsx'])
])
def __str__(self):
return self.name
forms.py
from django import forms
from .models import Document
class DocumentForm(forms.ModelForm):
class Meta:
model = Document
fields = '__all__'
upload.html:
<form method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="ok">
</form>
{% if uploaded_file_url %}
<p>File uploaded at: {{ uploaded_file_url }}</p>
{% endif %}
views.py
def upload(request):
if request.user.is_authenticated:
# Is it better to use #login_required ?
username = request.user.username
else:
username = ''
if request.method == 'POST':
form = DocumentForm(request.POST, request.FILES)
if form.is_valid():
doc = form.save()
return render(request, 'app/upload.html', {
"form": DocumentForm(),
"uploaded_file_url": doc.myfile.url,
"username": username,
})
else:
form = DocumentForm()
return render(request, 'app/upload.html', {"form": form})

Django Form Not Posting to SQL

I have a page where an item from a list nested within my form can be favorited, it redirects back to the same page following what should be an update to the database, then it shows a star next to the item. While this should work fine my form doesn't change the DB at all. I am confident it is not the html rendering since when I manually change the field in the admin panel it renders fine. What is causing this to not post?
view.py:
from django.shortcuts import render, get_object_or_404
from django.http import HttpResponse
from django.template import loader
from .models import Album, Song
# Create your views here.
def index(request):
all_albums = Album.objects.all()
template = loader.get_template('music/index.html')
context = {'all_albums' : all_albums,}
return render(request, 'music/index.html', context)
def detail(request, album_id):
album = get_object_or_404(Album, pk=album_id)
return render(request, 'music/detail.html', {'album' : album})
def favorite(request, album_id):
album = get_object_or_404(Album, pk=album_id)
print("favorite stuff happens here")
try:
selected_song = album.song_set.get(pk=int(request.POST['song']))
except (KeyError, Song.DoesNotExist):
return render(request, 'music/detail.html', {
'album' : album,
'error_message': 'Did not select a valid song'
})
else:
selected_song.favorite = True
selected_song.save()
return render(request, 'music/detail.html', {'album' : album})
<img src="{{album.album_logo}}">
<h1>{{album.album_title}} </h1>
<h2>{{album.artist}} </h2>
{% if error_message %}
<p><strong> {{error_message}} </strong></p>
{% endif %}
<form action="{% url 'music:favorite' album.id %}" method="post">
{% csrf_token %}
{% for song in album.song_set.all %}
<input type="radio" id="song{{forloop.counter}}" name="song" value="{{song.id}}" />
<label for="song{{forloop.counter}}">
<span>{{song.song_title}}
{% if song.is_favorite %}
<img src="http://i.imgur.com/b9b13Rd.png" />
{% endif %}
</span>
</label><br>
{% endfor %}
<input type="submit" value="Favorite">
</form>
model.py:
from django.db import models
# Create your models here.
class Album(models.Model):
artist = models.CharField(max_length=255)
album_title = models.CharField(max_length=255)
genre = models.CharField(max_length=255)
album_logo = models.CharField(max_length=255)
def __str__(self):
return self.album_title + ' -- ' + self.artist
class Song(models.Model):
# on delete this deletes this entry
album = models.ForeignKey(Album, on_delete=models.CASCADE)
file_type = models.CharField(max_length=4)
song_title = models.CharField(max_length=255)
is_favorite = models.BooleanField(default=False)
def __str__(self):
return self.song_title
urls.py:
from django.conf.urls import url
from . import views
app_name = 'music'
urlpatterns = [
# /music/
url(r'^$', views.index, name='index'),
# /music/<album_id>/
url(r'^(\d+)/$', views.detail, name='detail'),
# logic for favoriting adjusts model and redirects to same place
# /music/<album_id>/favorite
url(r'^(\d+)/favorite/$', views.favorite, name='favorite'),
]

Comment form in django didn't save the new comments

I've created a new form for comments the articles on a website. When I add the new comment from django admin everything works ok, but when I try to add the new comment directly from detail page nothings happen and I'am redirecting to the page with list of articles.
here are my files
models.py:
class Komentarz(models.Model):
post = models.ForeignKey(Wpisy, related_name="komentarze", verbose_name="Komentarze do artykułu", on_delete=models.CASCADE)
name = models.CharField(max_length=80, verbose_name="Imię")
email = models.EmailField(verbose_name="Email")
content = models.TextField(verbose_name="Treść komentarza")
created_date = models.DateTimeField(verbose_name="Utworzono", auto_now_add=True)
active = models.BooleanField(verbose_name="Aktywny?", default=True)
class Meta:
ordering = ('created_date',)
verbose_name="Komentarz"
verbose_name_plural="Komentarze"
def __str__(self):
return 'Komentarz dodany przez {} dla strony {}'.format(self.name, self.post)
vies.py with the function of details
from django.shortcuts import render, get_object_or_404
from .models import Wpisy, Komentarz
from .forms import KomentarzeForma
....
def detale_bajki(request, slug, ):
detale_bajki = get_object_or_404(Wpisy, slug=slug)
komentarze = detale_bajki.komentarze.filter(active=True)
if request.method == 'POST':
formularz_komentarza = KomentarzeForma(data=request.POST)
if formularz_komentarza.is_valid():
nowy_komentarz = formularz_komentarza.save(commit=False)
nowy_komentarz.detale_bajki = detale_bajki
nowy_komentarz.save()
else:
formularz_komentarza = KomentarzeForma()
return render(request, 'bajki/detale_bajki.html', {'detale_bajki': detale_bajki, 'komentarze': komentarze, 'formularz_komentarza': formularz_komentarza})
forms.py
from .models import Komentarz
from django import forms
class KomentarzeForma(forms.ModelForm):
class Meta:
model = Komentarz
fields = ('name', 'email', 'content')
and detail.html
...
{% with komentarze.count as total_komentarze %}
<h2>
{{ total_komentarze }} komentarz{{ total_komentarze|pluralize:"y" }}
</h2>
{% endwith %}
{% for komentarz in komentarze %}
Komentarz dodany przez <strong>{{komentarz.name}}</strong>
{{komentarz.created_date}}
<p>
{{ komentarz.content|linebreaks }}<br>
{% empty %}
<p>Nie dodano jeszcze żadnych komentarzy</p>
{% endfor %}
{% if nowy_komentarz %}
<h2>Twój komentarz został dodany</h2>
{% else %}
<h2>Dodaj nowy komentarz</h2>
<form action="." method="post">
{{formularz_komentarza.as_p}}
{% csrf_token %}
<p><input type="submit" value="Dodaj komentarz"></p>
</form>
{% endif %}
clas Wpisy in models.py
class Wpisy(models.Model):
title = models.CharField(max_length=400, verbose_name="Tytuł")
slug = models.SlugField(unique=True, max_length=400,verbose_name="Przyjazny adres url")
content = models.TextField()
status_audio = models.BooleanField(default=False, verbose_name="Czy dostępny będzie plik audio?")
audio_file = models.FileField(upload_to='uploads/',verbose_name="Plik audio")
created_date = models.DateTimeField(blank=True, null=True, verbose_name="Data utworzenia")
category = models.ForeignKey(Kategorie, verbose_name="Kategoria", on_delete=models.CASCADE)
class Meta:
verbose_name="Wpis"
verbose_name_plural="Wpisy"
def __str__(self):
return self.title
Your url pattern is
path('bajki/<slug>', views.detale_bajki, name='detale_bajki')
Note that it doesn't have a trailing slash. Your form's action is "."
<form action="." method="post">
That means you are submitting to /bajki/, which is the wrong URL.
You could fix this by adding a trailing slash to the url (which is common in Django URLs)
path('bajki/<slug>/', views.detale_bajki, name='detale_bajki')
Or you could change the form action to "" instead of ".". In the comments it looks like you fixed the issue by changing the form action to {{ detale_bajki.slug }}.
However these changes to the form action are fragile, and could break if you change your URL patterns again. The best approach is to use the {% url %} tag to reverse the correct URL.
<form action="{% url 'detale_bajki' detale_bajki.slug %}" method="post">
Try out:
nowy_komentarz.post = detale_bajki
...
return render(request, 'html page', {'key': 'what you want to return to your context'}) # don't fornget to add some return to your view.

Django Managment_form

I need to create a comment form on my site. When I try to display comment_form in HTML instead of the browser, I receive this error:
[u'ManagementForm data is missing or has been tampered with'].
Why is this? How can I fix it?
Here is models.py:
class Category(models.Model):
category_name = models.CharField(max_length=255)
def __unicode__(self):
return u'{0}'.format(self.category_name)
class Category_Form(forms.Form):
category_name = forms.CharField(label='Category_name', max_length=255)
class Comments(models.Model):
comment = models.CharField(max_length=512)
article = models.ForeignKey('Article')
class Comments_Form(forms.Form):
comment = forms.CharField(label='Comment', max_length=512)
article_id = forms.CharField()
class Article(models.Model):
author = models.CharField(max_length=100)
title = models.CharField(max_length=255)
short_text = models.CharField(max_length=1024)
full_text = models.CharField(max_length=5024)
date = models.DateTimeField(default=datetime.now())
category = models.ForeignKey('Category')
class Article_Form(forms.Form):
author = forms.CharField(label='author_article', max_length=100)
title = forms.CharField(label='title_article', max_length=255)
short_text = forms.CharField(label='short_text_article', max_length=1024, widget=CKEditorWidget())
full_text = forms.CharField(label='full_text_article', max_length=5024, widget=CKEditorWidget())
date = forms.DateTimeField()
category = forms.ModelChoiceField(queryset=Category.objects.order_by('category_name'))
My views.py:
from django.http import HttpResponse, HttpResponseRedirect
from django.shortcuts import render
from django import forms
from django.template import RequestContext
from sghome.models import News_Form, News, Article_Form, Article, Category, Category_Form, User, User_Form, \
Comments_Form, Comments
from django.forms.formsets import formset_factory
from django.shortcuts import render_to_response
from django.core.urlresolvers import reverse
def Show_Article_Site(request, num):
article = list(Article.objects.filter(id=num))
CommentFormSet = formset_factory(Comments_Form)
formset = CommentFormSet(request.POST, request.FILES)
# formset = CommentFormSet()
return render_to_response('Show_Article_Site.html', {'article': article, 'formset': formset, },
context_instance=RequestContext(request))
def Create_Comment(request):
if request.method == 'POST':
# formset = CommentFormSet(request.POST, request.FILES)
Comment = Comments()
Comment.comment = request.POST['form-0-comment']
else:
Show_Article_Site.formset = Show_Article_Site.CommentFormSet()
return HttpResponseRedirect(reverse(Show_Article_Site))
And my template:
{% extends "base_site.html" %}
{% block center_site %}
{% csrf_token %}
<div class="create_news">
{% for artic in article %}
<br><p>Автор: </p> {{ artic.author }}
<br><p>Дата: </p> {{ artic.date }}
<br><p>Заголовок: </p>{{ artic.title }}
<br><p>Текст: </p>{{ artic.full_text }}
{% endfor %}
<form method="post" action="/Create_Comment/">
{% for form in formset %}
{{ form.comment }}
<input type="submit" value="Add">
{% endfor%}
</form>
</div>
{% endblock %}
Use
formset = CommentFormSet()
Instead of
formset = CommentFormSet(request.POST, request.FILES)
Cause your request.POST and request.FILES are not initiated in that place

Categories