Entry gets into the DB even if an exception is thrown - python

So I have a form which takes some input and a file field. I'm using a validator on the file filed to check for the size of the file. It is working well because I get the error on the page saying that the file is too large, but the entry still gets into the DB.
I don't know why this happens. I supposed that raising an exception would do the trick in my case, but it does not.
models.py
from django.db import models
from django.contrib.auth.models import User
from .validators import validate_file_size
# Create your models here.
class CV(models.Model):
solicitant = models.ForeignKey(User, on_delete=models.CASCADE)
dataUploadCV = models.DateField(auto_now_add=True)
nume = models.CharField(max_length=12)
prenume = models.CharField(max_length=12)
telefon = models.CharField(max_length=12)
emailContact = models.EmailField(max_length=40)
CV = models.FileField(upload_to='documents/%d/%m/%Y', validators=[validate_file_size])
rezolvata = models.BooleanField(default=False)
def __str__(self):
return self.nume + " " + self.prenume + ": " + str(self.CV)
validators.py
from django.core.exceptions import ValidationError
def validate_file_size(value):
filesize=value.size
if filesize > 1:
raise ValidationError("Fisierul poate avea maxim 5MB.")
else:
return value
views.py
from django.shortcuts import render, get_object_or_404
from .models import Oferta, CV
from django.contrib import messages
from django.core.paginator import Paginator
# Create your views here
def incarcarecv(req):
context = {
'title': "Incarcare CV | Best DAVNIC73"
}
if req.method == 'POST':
try:
nume = req.POST['nume']
prenume = req.POST['prenume']
telefon = req.POST['telefon']
email = req.POST['email']
cv = req.FILES['CV']
try:
if(req.user.is_authenticated):
cv_upload = CV(
solicitant=req.user,
nume=nume,
prenume=prenume,
telefon=telefon,
emailContact=email
)
cv_upload.CV.save(cv.name, cv)
cv_upload.full_clean()
cv_upload.save()
req.user.profile.cvuri.append(cv_upload.id)
req.user.profile.save()
messages.success(req, 'CV depus cu succes!')
else:
messages.error(req, 'Trebuie sa fii logat pentru a depune CV-ul!')
except (ValueError):
messages.error(req, 'Formularul nu a fost incarcat!')
messages.info(req, 'Verifica daca esti logat!')
except:
messages.error(req, 'Nu ai completat corect campurile sau unul din ele este liber!')
messages.info(req, 'Ai grija ca toate campurile sa fie completate si ca fisierul sa nu depaseasca 5MB!')
return render(req, "../templates/pagini/incarcare-cv.html", context)
html file
{% extends 'base.html' %}
{% load static %}
{% block content %}
<div class="container container-centru">
<h1 class="heading-contact">Incarca CV</h1>
{% include 'partials/_alerts.html' %}
<form action="{% url 'incarcarecv' %}" method="POST" class="form-contact" enctype="multipart/form-data">
{% csrf_token %}
<div class="form-group">
<label for="inputnume" class="email-contact">Nume</label>
<input type="text" name="nume" class="form-control" id="inputnume" aria-describedby="numeHelp" placeholder="Introdu nume">
</div>
<div class="form-group">
<label for="inputprenume" class="email-contact">Prenume</label>
<input type="text" name="prenume" class="form-control" id="inputprenume" aria-describedby="prenumeHelp" placeholder="Introdu prenume">
</div>
<div class="form-group">
<label for="inputtelefon" class="email-contact">Telefon</label>
<input type="text" name="telefon" class="form-control" id="inputtelefon" aria-describedby="telefonHelp" placeholder="Introdu telefon">
</div>
<div class="form-group">
<label for="inputemail" class="email-contact">Email</label>
<input type="email" name="email" class="form-control" id="inputemail" aria-describedby="emailHelp" placeholder="Introdu email">
</div>
<div class="form-group">
<label for="inputcv" class="email-contact">CV</label>
<input type="file" name="CV" accept=".docx,.doc,.pdf,application/msword" class="form-control" id="inputemail" aria-describedby="CVHelp">
</div>
<div class="form-group form-group-custom">
<input type="submit" value="Trimite" class="btn btn-secondary btn-block btn-login-custom">
<input type="submit" value="Resetează câmpurile" class="btn btn-secondary btn-block btn-reset-custom">
</div>
</form>
</div>
<script src="{% static 'javascript/clearMessage.js' %}"></script>
{% endblock %}
So how can I make the post not enter the DB if the exception is thrown? Right now I get the error, but it is still entering the DB. (I can see it in the administration zone of django)
////edit: I deleted everything that was not about my problem from the code.
////edit2: added the HTML file

In Django, the typical workflow is to first run validators to verify that the data you are trying to commit into the database is "clean" and only then should one call save(). But due to some quirks calling save does not automatically clean the data.
so the workflow should be something along the lines of:
...
cv_upload = CV(solicitant=req.user, nume=nume, prenume=prenume,
telefon=telefon, emailContact=email)
# call clean before saving as we only want CLEAN data in the DB
cv_upload.full_clean()
# now that it is relatively clean with Django's validators and our custom validators
# go ahead and save it
cv_upload.save()
...

Related

I'm a newbie to python/Django and getting a value error and no http response error. Also when added with return statement, form is not updating [duplicate]

This question already has answers here:
The view didn't return an HttpResponse object. It returned None instead
(7 answers)
Closed last month.
ValueError at /update_department/14
The view management.views.update_department didn't return an HttpResponse object. It returned None instead.Also when added with return statement data is not updating.
Request information
USER
admin
GET
No GET data
POST
Variable Value
csrfmiddlewaretoken
'XLqZBPhMKImvlfgWsNLeN1Ei8nz5u1HJ15IvAQV4JNwVMeG31rhDOD1q9PJuwXmz'
department_code
'15'
department_name_e
'Finance'
department_name_l
'Finance'
parent_code
''
submit
''
These are the details.I don't know why is there error here while all the posted data is right.also the form is not updating.
Models:
class Departments(models.Model):
department_code = models.CharField(db_column='Department_Code', primary_key= True, max_length=20, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
department_name_e = models.CharField(db_column='Department_Name_E', max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
department_name_l = models.CharField(db_column='Department_Name_L', max_length=50, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
parent_code = models.CharField(db_column='Parent_Code', max_length=20, db_collation='SQL_Latin1_General_CP1_CI_AS') # Field name made lowercase.
is_active = models.BooleanField(db_column='Is_Active') # Field name made lowercase.
created_by = models.IntegerField(db_column='Created_By') # Field name made lowercase.
created_date = models.DateTimeField(db_column='Created_date') # Field name made lowercase.
modified_by = models.IntegerField(db_column='Modified_By') # Field name made lowercase.
modified_date = models.DateTimeField(db_column='Modified_date') # Field name made lowercase.
class Meta:
db_table = 'Departments'
unique_together = (('department_code'),)
def __str__(self):
return str("self.department_name_e") or ''
View:
#login_required
def update_department(request, department_code):
dep_up = Departments.objects.get(department_code=department_code)
if request.method == "POST":
form = DepartmentsForm(request.POST, instance = dep_up)
if form.is_valid():
department_code = form.cleaned_data['department_code']
department_name_e = form.cleaned_data['department_name_e']
department_name_l = form.cleaned_data['department_name_l']
parent_code = form.cleaned_data['parent_code']
obj = form.save(commit = False)
obj.is_active = True
obj.created_by = request.user.id
obj.created_date = datetime.today()
obj.modified_by = request.user.id
obj.modified_date = datetime.today()
obj.save()
return HttpResponseRedirect('department_list')
forms:
class DepartmentsForm(forms.ModelForm):
class Meta:
model = Departments
fields = ['department_code','department_name_e','department_name_l','parent_code']
HTML:
{% extends 'base.html' %}
{% block title %}Update Company{% endblock title %}
{% block body %}
<div style="margin-left:22%" class=" top-marg">
<h2 ><strong>Company:</strong></h2><br><br>
<form class="" action="{%url 'update_company' comp_up.company_code %}" method="post">
{% csrf_token %}
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="text" value="{{comp_up.company_code}}" class="form-control" id="company_code" name="company_code" placeholder="Company Code" required>
<label style="margin-left:15px" for="company_code">Company Code</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="text" value="{{comp_up.company_name_e}}" class="form-control" id = "company_name_e" name="company_name_e" placeholder="Enter Company" required>
<label style="margin-left:15px" for="company_name_e">Company Name English</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="text" value="{{comp_up.company_name_l}}" class="form-control" id = "company_name_l" name="company_name_l" placeholder="Enter Company" required>
<label style="margin-left:15px" for="company_name_e">Company Name Local</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="tel" value="{{comp_up.tel}}" class="form-control" id = "tel" name="tel" placeholder="Telephone Number" required>
<label style="margin-left:15px" for="tel">Telephone Number</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<input type="tel" value="{{comp_up.fax}}" class="form-control" id = "fax" name="fax" placeholder="Enter Fax"required>
<label style="margin-left:15px" for="fax"> Fax Number</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<textarea name="address" class="form-control" rows="4" cols="100" placeholder="Address" required>{{comp_up.address}}</textarea>
<label style="margin-left:15px" for="address">Address</label>
</div>
<br>
<div style="margin-left:20%;margin-right:20%" class="form-floating ">
<select class="form-control" name="country_id" required>
<option value="{{comp_up.country_id.id}}" >{{comp_up.country_id.country_name_e}}</option>
{% for con in country %}
<option value="{{con.id}}" >{{con.country_name_e}}</option>
{% endfor %}
</select>
</div>
<br>
<label style = "margin-left:21%; " for="logo">Logo</label>
<div class="form-floating" >
<input value="{{comp_up.}}" style = "margin-left:21%;" accept="image/*" type="file" name="logo" onchange="loadFile(event)" required> <br>
<img style = "margin-left:21%;" id="output" >
<script>
var loadFile = function(event) {
var output = document.getElementById('output');
output.src = URL.createObjectURL(event.target.files[0]);
output.onload = function() {
URL.revokeObjectURL(output.src) // free memory
}
};
</script>
</div>
<br><br>
<center>
<button type="submit" class="btn btn-success" name="submit">Update</button>
<button type="button" class="btn btn-primary" onclick="window.location.href = '{%url 'company_list'%}'" name="cancel">Cancel</button>
</center>
</form>
</div>
{% endblock body %}
You have provided HttpReponse only for POST and valid form. You should give the standard response (with empty form) for fresh entries or posting with errors. Like this:
#login_required
def update_department(request, department_code):
dep_up = Departments.objects.get(department_code=department_code)
if request.method == "POST":
form = DepartmentsForm(request.POST, instance = dep_up)
if form.is_valid():
...
return HttpResponseRedirect('department_list')
form = DepartmentsForm()
return render(request, 'template.html', context={'form': form})

2023 Everybody! We made it. I want to update my form, but my details are not pulling through to the form

I want to Update/Edit my details on my form. I want to pull the existing details from the database and have them populate on the form, without having the user start from the beginning.
Views.py
def Client_Update(request, Client_id):
ClientUpdate = TestModel.objects.get(pk=Client_id)
ClientUpdates = TestForm(request.POST or None, instance=ClientUpdate)
if request.method == 'POST':
if ClientUpdates.is_valid():
ClientUpdates.save()
return redirect('/Client_Details')
return render(request, 'GymApp/ClientUpdate.html',
{'ClientUpdate':ClientUpdate,
'ClientUpdates':ClientUpdates})
urls.py
from django.urls import path
from . import views
urlpatterns = [
path('', views.Home, name='Home'),
path('ClientList/', views.Client_list, name='Client_list'),
path('ClientDetails/<int:Client_id>', views.Client_Details, name='Client_Details'),
path('ClientUpdate/<int:Client_id>', views.Client_Update, name='Client_Update'),
path('ClientDelete/<int:Client_id>', views.Client_Delete, name='Client_Delete'),
path('DownloadingCSV/', views.DownloadingCSV, name='DownloadingCSV'),
path('Search/', views.Search, name='Search'),
]
HTML Page
{% extends 'GymApp/Layout.html' %}
{% block content %}
<h1>Updating status</h1>
<form action="" method="POST">
{% csrf_token %}
<div class="mb-3">
<input type="text" class="form-control"
name="Name" placeholder="Client's Name"><br>
<input type="text" class="form-control"
name="Surname"placeholder="Client's Surname"><br>
<select name="Gender" class="form-control">
<option selected disabled>
Open this select menu
</option>
<option value="Male">Male</option><br>
<option value="Female">Female</option>
</select>
</div>
<div class="mb-3">
<input type="text" class="form-control" name="Weight" id="Weight" placeholder="Client's Weight"><br><br>
<input type="text" class="form-control" name="Height" id="Height" placeholder="Client's Height"><br><br>
<button type="button" onclick="calculation()">Calculation update</button>
<br>
</div>
<br>
<div class="mb-3">
<input type="text" class="form-control" name="Outcome" id="Outcome" placeholder="BMI Outcome"><br>
<select name="Activity_log" class="form-control"><br>
<option selected disabled>Open this select menu</option>
<option value="Not Active">Not Active</option><br>
<option value="Active">Active</option>
</select>
<br>
<button type="submit">Finalising update!</button>
</div>
</form>
<script>
function calculation(){
W = document.getElementById('Weight').value;
H = document.getElementById('Height').value;
O = W * H;
document.getElementById('Outcome').value = O;
}
</script>
{% endblock %}
And the outcome when i press the Update button is the following:
As you can the form is empty
How to i pull the existing details on my form? Please help.
from django.db import models
# Create your models here.
class TestModel(models.Model):
Name = models.CharField(max_length=30, blank=True)
Surname = models.CharField(max_length=30, blank=True)
Weight = models.CharField(max_length=30, blank=True)
Height = models.CharField(max_length=30,blank=True)
Gender = models.CharField(max_length=6, blank=True, null=True)
Outcome = models.CharField(max_length=30,blank=True)
Activity = models.CharField(max_length=30, blank=True)
def __str__(self):
return self.Name
And this is my updated HTML
<form action="" method="POST">
{% csrf_token %}
<div class="mb-3">
<input type="text" class="form-control" name="Name" value={{Name}}><br>
<input type="text" class="form-control" name="Surname" value={{Surname}}><br>
<select name="Gender" class="form-control">
<option selected disabled>
Open this select menu
</option>
<option value="Male" value={{Gender}}>Male</option><br>
<option value="Female" value={{Gender}}>Female</option>
</select>
</div>
<div class="mb-3">
<input type="text" class="form-control" id="Weight" value={{Weight}} ><br><br>
<input type="text" class="form-control" id="Height" value={{Height}} ><br><br>
<button type="button" onclick="calculation()">Calculation update</button>
<br>
</div>
<br>
<div class="mb-3">
<input type="text" class="form-control" name="Outcome" id="Outcome" placeholder="BMI Outcome"><br>
<select name="Activity_log" class="form-control"><br>
<option selected disabled>Open this select menu</option>
<option value="Not Active">Not Active</option><br>
<option value="Active">Active</option>
</select>
<br>
<button type="submit">Finalising update!</button>
</div>
</form>
All my views.py
from django.shortcuts import render, redirect
from . models import TestModel
from . forms import TestForm
from django.http import HttpResponse
import csv
# Create your views here.
def Search(request):
if request.method == "POST":
Searching = request.POST['Searching']
Results_query = TestModel.objects.filter(Name__contains=Searching)
{'Searching':Searching,
'Results_query':Results_query}
return render(request, 'GymApp/Searching.html',
{'Searching':Searching,
'Results_query':Results_query})
def DownloadingCSV(request):
response = HttpResponse(content_type='text/csv')
response['content-disposition'] = 'attachment; filename=Client_list.csv'
writer = csv.writer(response)
Downloading_all = TestModel.objects.all()
writer.writerow(['Name','Surname',
'Weight','Height',
'Outcome','Gender',
'Activity'])
for download in Downloading_all:
writer.writerow([download.Name,
download.Surname,
download.Weight,
download.Height,
download.Outcome,
download.Gender,
download.Activity])
return response
def Client_Delete(request, Client_id):
ClientUpdate = TestModel.objects.get(pk=Client_id)
ClientUpdate.delete()
return redirect('Home')
def Client_Update(request, Client_id):
ClientUpdate = TestModel.objects.get(pk=Client_id)
ClientUpdates = TestForm(request.POST or None, instance=ClientUpdate)
if request.method == 'POST':
if ClientUpdates.is_valid():
ClientUpdates.save()
return redirect('/Client_Details')
return render(request, 'GymApp/ClientUpdate.html',
{'ClientUpdate':ClientUpdate,
'ClientUpdates':ClientUpdates})
def Client_list(request):
Clients = TestModel.objects.all()
return render(request, 'GymApp/ClientList.html',
{'Clients':Clients})
def Client_Details(request, Client_id):
ClientDetails = TestModel.objects.get(pk=Client_id)
return render(request, 'GymApp/ClientDetails.html',
{'ClientDetails':ClientDetails})
def Home(request):
Forms = TestForm
if request.method == 'POST':
Forms = TestForm(request.POST or None)
if Forms.is_valid():
Forms.save()
return redirect('Client_list')
return render(request, 'GymApp/Home.html',{})
### You have not given value
<input type="text" class="form-control"
name="Name" value={{ClientUpdates.Name}} placeholder="Client's Name"><br>
###{{Name}} --> your model field name

How do you fix this: IntegrityError at /restaurants/create? - NOT NULL constraint failed: restaurants_restaurantlocation.name

I'm trying to make a django developed website which is called MuyPicky. It is a website which allows you to find restaurants and other things based on your pickiness. I am currently making a page for forms which adds Restaurants to the database. As I am doing this I get this error:
IntegrityError at /restaurants/create.
NOT NULL constraint failed: restaurants_restaurantlocation.name
Is this why I get the error
Here is the forms.py:
class RestaurantCreateForm(forms.Form):
title = forms.CharField()
location = forms.CharField(required = False)
category = forms.CharField(required = False)
The form.html:
{% extends "base.html" %}
{% block title %}Add Restaurant || {{block.super}} {% endblock %}
{% block content %}
<div class="container-fluid">
<div class="container">
<div class="row">
<div class="col-md-offset-4 col-md-4 col-md-offset-4">
<h1>Add Restaurant</h1>
<form method="POST">{% csrf_token %}
<input title="Title" class="form-control" type="text" name="Title" placeholder="Title">
<br>
<input title="Location" class="form-control" type="text" name="Location" placeholder="Location"><br>
<input title="Category" class="form-control" type="text" name="Category" placeholder="Category"><br>
<!--<input title="Save" class="form-control btn btn-info " type="submit" value="Save" >--><br>
<button class="btn btn-success form-control btn-md center-block" type="submit">Save</button>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
The view from views.py:
def restaurant_createview(request):
#if request.method == "GET":
# print("get data")
if request.method == "POST":
title = request.POST.get("title") #(request.POST["title"])
location = request.POST.get("location")
category = request.POST.get("category")
obj = RestaurantLocation.objects.create(
name = title,
location = location,
category = category
)
return HttpResponseRedirect("/restaurants/")
template_name = "restaurants/form.html"
context = {}
return render(request, template_name, context)
Lastly the urls.py:
urlpatterns = [
url(r'^admin/', admin.site.urls),
url(r'^/$', TemplateView.as_view(template_name="home.html")),
url(r'^restaurants/$', RestaurantListView.as_view()),
url(r'^restaurants/create/$', restaurant_createview),
url(r'^restaurants/(?P<slug>[\w-]+)/$', RestaurantDetailView.as_view()),
url(r'^contact/$', TemplateView.as_view(template_name="contact.html")),
url(r'^about/$',TemplateView.as_view(template_name="about.html"))]
Your fields have name Title, Location, Category but your Django code is looking for title, location and category. These need to be the same.

Django User Form don't save on database

I've create a Model, Form, View and register.html but my form doesn't save on database and doesn't create a new user. What's wrong?
Follow the codes...
models.py
from __future__ import unicode_literals
from django.db import models
from django.contrib.auth.models import User
class Cliente(models.Model):
SEXO_CHOICES = (
(u'Masculino', u'Masculino'),
(u'Feminino', u'Feminino'),
)
nome = models.CharField(max_length=50, null=False, default='*')
telefone = models.CharField(max_length=20, null=True)
cpf = models.CharField(max_length=255, null=False)
data_de_nascimento = models.DateField(null=False)
sexo = models.CharField(max_length=9, null=False, choices=SEXO_CHOICES)
usuario = models.OneToOneField(User, related_name="cliente")
#property
def email(self):
return self.usuario.email
def __unicode__(self):
return self.nome
forms.py
from django import forms
from django.contrib.auth.models import User
from datetimewidget.widgets import DateTimeWidget, DateWidget, TimeWidget
from clientes.models import Cliente
class RegistraClienteForm(forms.Form):
SEXO_CHOICES = (
(u'Masculino', u'Masculino'),
(u'Feminino', u'Feminino'),
)
nome = forms.CharField(required=True)
telefone = forms.CharField(required=True)
cpf = forms.CharField(required=True)
data_de_nascimento = forms.DateField(
widget=DateWidget(usel10n=True, bootstrap_version=3)
)
sexo = forms.ChoiceField(required=True, choices=SEXO_CHOICES)
username = forms.CharField(required=True)
email = forms.EmailField(required=True)
senha = forms.CharField(required=True)
def is_valid(self):
valid = True
if not super(RegistraClienteForm, self).is_valid():
self.adiciona_erro('Por favor, verifique os dados informados')
valid = False
return valid
username_form_data = self.data['username']
user_exists = User.objects.filter(username=username_form_data).exists()
if user_exists:
self.adiciona_erro('User already exists!')
valid = False
return valid
def adiciona_erro(self, message):
errors = self._errors.setdefault(
forms.forms.NON_FIELD_ERRORS,
forms.utils.ErrorList()
)
errors.append(message)
And the register.html
{% extends "new_client_base.html" %}
{% block body %}
<form class="form-signin" action="{% url 'registrar' %}" method="post">
{% csrf_token %}
<h2 class="form-signin-heading">Crie seu usuário</h2>
<label for="id_nome"> Nome: </label> <input name="nome" type="text" id="id_nome" class="form-control" placeholder="Nome *" required autofocus/>
<label for="id_telefone">Telefone: </label> <input type="text" name="telefone" id="id_telefone" class="form-control" placeholder="Telefone *" required/>
<label for="id_cpf"> CPF: </label> <input type="text" name="cpf" id="id_cpf" class="form-control" placeholder="CPF *" required/>
<label for="id_data"> Data de Nascimento:</label> <input type="date" name="data_de_nascimento" id="id_data" class="form-control" required />
<label for="id_sexo" class="required">
Sexo:
</label> <select id="id_sexo" name="sexo">
<option selected="selected" value=""> ------- </option>
<option value="Masculino"> Masculino </option>
<option value="Feminino"> Feminino </option>
</select>
<label for="id_username"> Nome de usuário: </label> <input type="text" name="username" class="form-control" id="id_username" required/>
<label for="id_email"> Email: </label> <input type="text" name="email" id="id_email" class="form-control" required />
<label for="id_pass"> Senha: </label> <input type="password" name="senha" id="id_pass" class="form-control" required>
<button
type="submit"
class="btn btn-lg btn-primary btn-block"
value="login"
>
Registrar
</button>
{% if form.errors %}
<div class="alert alert-danger">
<button type="button" class="close" data-dismiss="alert" aria-hidden="true" name="button">×</button>
{{form.non_field_errors}}
</div>
{% endif %}
</form>
{% endblock %}
I want to know how to save this data, why save() method does not work and how can I format date in DD-MM-YYYY and show a minicalendar.
Thanks.

Django: FILES Form Not Validating

I have a basic Form that accepts a file / image from a template. For some reason it won't validate and I can't see the error.
views.py
# Flag a Job as complete
#login_required()
#user_passes_test(lambda u: u.groups.filter(name='Developer').exists(), login_url='/login/', redirect_field_name='not allowed')
#require_http_methods(['POST'])
def job_complete(request, jobid, userid):
# Get the Job
job = Jobs.objects.get(id=jobid)
jobsubmit = JobSubmitForm(request.FILES)
if jobsubmit.is_valid():
js = jobsubmit.save(commit=False)
js.user_id = userid
js.job_id = jobid
js.save()
job.status = 'IR'
job.save()
return redirect('view_job', jobid=jobid, slug=job.slug)
else:
messages.error(request, "There are form errors!")
return redirect('view_job', jobid=jobid, slug=job.slug)
forms.py
class JobSubmitForm(forms.ModelForm):
class Meta:
model = JobSubmit
fields = ('file', 'image', 'comment', 'gitHubLink')
def save(self, commit=True):
jobsubmit = super(JobSubmitForm, self).save(commit=False)
jobsubmit.user_id = self.cleaned_data['user_id']
jobsubmit.job_id = self.cleaned_data['job_id']
if commit:
jobsubmit.save()
return jobsubmit
view.html
<form method="post" action="/job/job_complete/j{{ job.id }}/u{{ request.user.id }}/" class="form-inline btn-group" enctype="multipart/form-data">
{% csrf_token %}
<div class="span6 inline">
<label class="control-label">Attach Files: </label>{{ job_submit.file }}
<p class="help-block">Attach files that go with this Job.</p>
</div>
<div class="span6 inline">
<label class="control-label">Attach Images: </label>{{ job_submit.image }}
<p class="help-block">Attach images that go with this Job.</p>
</div>
<div class="span6 inline">
<label class="control-label">GitHub URL: </label>{{ job_submit.gitHubLink|add_class:"form-control"|attr:"placeholder:Example: https://www.github.com/path/to/code/repo/or/commit" }}
<p class="help-block">If hosting work on GitHub.</p>
</div>
<div class="span6 inline"><label class="control-label">Job Comments(Required): </label>{{ job_submit.comment|add_class:"form-control"|attr:"placeholder:Example: Fun Job! Please keep me in mind for future work!" }} </div>
<div class="modal-footer">
<button type="submit" class="btn btn-success btn-med pull-left"><i class="fa fa-check-circle"></i> Job Complete</button>
<button type="button" class="btn btn-default" data-dismiss="modal">Close</button>
</div>
</form>
models.py
# Store data related to a Job (files, comments, etc.)
class JobSubmit(models.Model):
job = models.ForeignKey(Jobs)
user = models.ForeignKey(User)
file = models.FileField(upload_to="uploads/jobs/files", blank=True, null=True)
image = models.ImageField(upload_to="uploads/jobs/images", blank=True, null=True)
comment = models.TextField()
gitHubLink = models.URLField(blank=True)
Hopefully it's not something silly... it's been a long day and sleepy programming isn't the best idea. :/
Appreciate the help if anyone sees what's wrong. Pointers welcomed, as well. Cheers,
This line:
jobsubmit = JobSubmitForm(request.FILES)
should be as:
jobsubmit = JobSubmitForm(request.POST, request.FILES)
try it?

Categories

Resources