I am trying to attach a file in django models, but when I hit submit button the selected file immediately disappears and the form submission fails . What is going wrong here?
forms.py
from django import forms
from .models import IssueNotice
class IssueNoticeForm(forms.ModelForm):
class Meta:
model = IssueNotice
fields = ('title', 'content','issuer','attachment',)
models.py
from django.db import models
from django.utils import timezone
from django import forms
class IssueNotice(models.Model):
title = models.CharField(max_length=300)
content = models.TextField()
attachment = models.FileField(upload_to='attachments')
issuer = models.CharField(max_length=100)
issuer_id = models.ForeignKey('auth.User')
issued_date = models.DateTimeField(default = timezone.now)
def publish(self):
self.issued_date = timezone.now()
self.save()
def __str__(self):
return self.title
views.py
from django.shortcuts import render
from django.utils import timezone
from django.shortcuts import redirect
from django.contrib.auth.decorators import login_required
from .models import IssueNotice
from .forms import IssueNoticeForm
def issue_notice(request):
if request.method == "POST":
form = IssueNoticeForm(request.POST, request.FILES)
if form.is_valid():
handle_uploaded_file(request.FILES['attachment'])
notice = form.save(commit = False)
notice.issuer_id = request.user
notice.issued_date = timezone.now()
notice.save()
return redirect('home_page')
else:
form = IssueNoticeForm()
return render(request, 'webadmin/issue_notice.html',{'form':form})
issue_notice.html
{% extends 'webadmin/base.html' %}
{% block content %}
<div class="col-md-8">
<form method="POST" class="post-form">{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="save btn btn-default">Issue</button>
</form>
{% endblock %}
Related
I already saw many Stack overflow posts, but cannot find any problem on my code, but this code doesn't save any piece of data.
models.py
from django.db import models
class Post(models.Model):
title = models.CharField(max_length=50, blank=True)
content = models.CharField(max_length=200, blank=True)
post_date = models.DateTimeField(default=datetime.now, blank=True)
def __str__(self):
return self.title
forms.py
from django.forms import ModelForm
from .models import Post
class PostForm(ModelForm):
class Meta:
model = Post
fields = ['title', 'content', 'post_date']
views.py
from django.shortcuts import render
from django.template import loader
from django.shortcuts import get_object_or_404, render
from django.http import HttpResponseRedirect
from django.http import Http404
from .models import Post
from .forms import PostForm
# Create your views here.
def index(request):
latest_post_list = Post.objects.order_by('-post_date')[:5]
template = loader.get_template('form/index.html')
context = {'latest_post_list':latest_post_list}
return render(request, 'form/index.html', context)
def posts(request, post_id):
post = get_object_or_404(Post, pk=post_id)
return render(request, 'form/posts.html', {'post':post})
def posting(request):
if request.method == 'POST':
form = PostForm(request.POST)
if form.is_valid():
instance = form.save(commit=False)
instance.save()
return HttpResponseRedirect('/')
else:
print(form.errors)
else:
form = PostForm()
return render(request, 'form/posting.html', {'form' : form})
posting.html
<form action="/form/" method="post">
{% csrf_token %}
{{ form }}
<input type='submit' value='Submit'>
</form>
<script src="" async defer></script>
I swear I saw many questions about it, but still I'm in trouble :/
I thought form.save in the views.py would make it work but no.
Try removing action in your 'posting.html' and instead of creating <input type='submit'>try the below code for submit button.
<form method="post">
{% csrf_token %}
{{ form }}
<button type="submit">Submit</button>
</form>
I have an issue with the below code. When I login below and try to submit the create.html template it redirects me to Home page (via home function in views and record is not saved in database). When i remove #login_required and directly navigate to /products/create , the record is saved down in database. I am confused why this is happening. Any assistance will be appreciated
I removed (#login_required) and directly navigated to /products/create and it works perfectly. However whenever I login and then use /products/create the record is not saved in database
Create.html
{%extends 'base.html'%}
{%block content%}
{%if error%}
{{error}}
{%endif%}
<h2> Create </h2>
{% csrf_token %}
<form action="create" method="POST" enctype="multipart/form-data">
{% csrf_token %}
Title:
<br/>
<input type="text" name = "title"/>
<br/><br/>
Body:
<br/>
<input type="textbox" name = "body"/>
<br/><br/>
URL:
<br/>
<input type="text" name = "url"/>
<br/><br/>
<input type="submit" class = "btn btn-primary" value = "Add Product"/>
</form>
{%endblock%}
Main url.py
from django.contrib import admin
from django.urls import path,include
from products import views
urlpatterns = [
path('admin/', admin.site.urls),
path('accounts/',include('accounts.urls')),
path('products/',include('products.urls')),
path('',views.home,name='home'),]
Sub project url.py
from django.urls import path,include
from . import views
urlpatterns = [
path('create',views.create,name='create'),]
views.py
from django.shortcuts import render, redirect, get_object_or_404
from django.contrib.auth.decorators import login_required
from django.contrib.auth.models import User
from django.urls import path
from .models import Product
from django.utils import timezone
def home(request):
return render(request, 'products/home.html')
#login_required
def create(request):
if request.method == 'POST':
if request.POST['title'] and request.POST['body'] and request.POST['url']:
product=Product()
product.title = request.POST['title']
product.body = request.POST['body']
product.url = request.POST['url']
product.pub_date = timezone.datetime.now()
product.save()
return render(request,'products/test.html',{'error':'all conditions checked'})
else:
return render(request,'products/test.html',{'error':'all conditions not checked'})
else:
return render(request, 'products/create.html',{'error':'post method not checked'})
For reference
models.py
from django.db import models
from django.contrib.auth.models import User
class Product(models.Model):
title = models.CharField(max_length=255)
pub_date = models.DateTimeField()
body = models.TextField()
url = models.TextField()
image = models.ImageField(upload_to='images/')
icon = models.ImageField(upload_to='images/')
votes_total = models.IntegerField(default=1)
def __str__(self):
return self.title
def summary(self):
return self.body[:100]
def pub_date_pretty(self):
return self.pub_date.strftime('%b %e %Y')
* Login function *
def login(request):
if request.method == 'POST':
user = auth.authenticate(username=request.POST['username'],password=request.POST['password'])
if user is not None:
auth.login(request,user)
return redirect('home')
else:
return render(request,'accounts/login.html',{'error':'incorrect username or password'})
else:
return render(request,'accounts/login.html')
every one ,,I can upload image from admin site,, but do not know how to upload image from the templates,,
models.py
from django.db import models
from django.contrib.auth.models import User
from PIL import Image
from django.utils import timezone
def get_imagep_Product(instance, filename):
return '/'.join(['products', instance.slug, filename])
class ProductsTbl(models.Model):
model_number = models.CharField(max_length=255, blank=True, null=True)
name = models.CharField(max_length=255, blank=True, null=True)
material = models.TextField(blank=True, null=True)
feature = models.TextField(blank=True, null=True)
created = models.DateTimeField(editable=False)
modified = models.DateTimeField(auto_now=True)
release = models.DateTimeField(blank=True, null=True)
submit_date = models.DateTimeField(blank=True, null=True)
slug = models.SlugField(unique=True)
user = models.ForeignKey(User, blank=True, null=True)
image = models.ImageField(upload_to=get_imagep_Product, blank=True) #image file
def __unicode__(self):
return self.name
def save(self, *args, **kwargs):
''' On save, update timestamps '''
if not self.id:
self.created = timezone.now()
return super(ProductsTbl, self).save(*args, **kwargs)
views.py
from django.shortcuts import render,redirect
from .forms import ProductsTblForm
from .models import ProductsTbl
from django.template.defaultfilters import slugify
from django.contrib.auth.decorators import login_required
from django.http import Http404,HttpResponse
import datetime
def create_thing(request):
form_class = ProductsTblForm
if request.method == 'POST':
form = form_class(request.POST)
if form.is_valid():
thing = form.save(commit=False)
thing.user = request.user
thing.slug = slugify(thing.model_number)
thing.save()
return redirect('thing_detail', slug=thing.slug)
else:
form = form_class()
return render(request, 'things/create_thing.html', { 'form': form,})
urls.py
from django.conf.urls import patterns, url,include
from django.contrib import admin
from django.views.generic import TemplateView
from designer import views
from designer.backends import MyRegistrationView
from django.conf import settings
urlpatterns = [
url(r'^create_thing/$', views.create_thing, name='create_thing'),
]
if settings.DEBUG:
urlpatterns += [
url(r'^media/(?P<path>.*)$', 'django.views.static.serve', {
'document_root': settings.MEDIA_ROOT,
}),
]
forms.py
from django.forms import ModelForm
from .models import ProductsTbl
class ProductsTblForm(ModelForm):
class Meta:
model = ProductsTbl
fields = ('model_number','name','feature', 'material','release','image',)
create_thing.html
{% extends 'base.html' %} {% block title %}
Create a Thing - {{ block.super }} {% endblock title %}
{% block content %}
<h1>Create a Thing</h1>
<form role="form" action="" method="post">
{% csrf_token %}
{{ form.as_p }}
<input type="submit" value="Submit" />
</form>
{% endblock content %}
when I click the create things I can see form here,,however I do not know how can let the image upload
I have looking for this link ,,however I do not know how to let it work in my app,,
First, you will need to add enctype="multipart/form-data" in your <form> definition. As this is required for file uploads.
<form role="form" action="" method="post" enctype="multipart/form-data">
Second, instead of form_class(request.POST) you will need to create form in your view by passing request.FILES too.
form_class(request.POST, request.FILES)
I've been working on WTF form with flask and mongoengine. When I try to register on html side as a new user this debug message appears.
ValidationError: ValidationError (User:None) (Field is required: ['password'] cannot parse date "asd": ['created_at'])
I've basic django background. I am new to flask and I don't know how to figure it out.
Model:
import datetime
from copylighter import db, app
from slugify import slugify
from flask_login import UserMixin
class User(db.Document, UserMixin):
created_at = db.DateTimeField(default=datetime.datetime.now)
name = db.StringField(max_length=30, required=True, unique=True, help_text="Your helptext here")
email = db.StringField(max_length=100, required=True, unique=True, help_text="Your helptext here")
active = db.BooleanField()
password = db.StringField(max_length=255, required=True, help_text="Your helptext here")
slug = db.StringField(help_text="Your helptext here")
roles = db.ListField(db.ReferenceField('Role'))
def save(self, *args, **kwargs):
if not self.slug:
self.slug = slugify(self.name)
return super(User, self).save(*args, **kwargs)
def __unicode__(self):
return self.name
forms.py
from flask_wtf import Form
from wtforms.fields import StringField, PasswordField, BooleanField, SubmitField, HiddenField
from wtforms import validators
from models import User
import datetime
class SignUpForm(Form):
created_at = HiddenField()
name = StringField(u'Username', [validators.Required()])
email = StringField(u'Email', [validators.Required()])
password = PasswordField(u'Password', [validators.Required()])
submit = SubmitField('Sign Up')
class Meta():
__model__ = 'User'
views.py
from flask import Flask, render_template, redirect, url_for, request, flash
from flask_login import login_required, login_user
from copylighter import db, app, login_manager
import datetime
from forms import LoginForm,SignUpForm
from slugify import slugify
from flask_login import UserMixin
from models import User
#app.route("/register", methods=['GET','POST'])
def register():
formS = SignUpForm()
#if formS.validate_on_submit():
#name = formS.name.data
#email = formS.email.data
#password = formS.password.data
if request.method == 'POST':
formS = SignUpForm()
formS.created_at.data = datetime.datetime.now()
if formS.validate() == False:
return render_template('register.html', form=formS)
if formS.validate_on_submit():
newuser = User(formS.name.data, formS.email.data, formS.password.data)
newuser.save()
return redirect(url_for('profile'))
return render_template("register.html", form=formS)
and finally
register.html
{% extends "base.html" %}
{% block content %}
<div class="container">
<form action="" method="post">
{{form.hidden_tag()}}
{{form.name.label}}
{{form.name}}
{% if form.name.errors %}
<span class="text-danger">Error</span>
{% endif %}
{{form.email.label}}
{{form.email}}
{% if form.email.errors %}
<span class="text-danger">Error</span>
{% endif %}
{{form.password.label}}
{{form.password}}
{% if form.password.errors %}
<span class="text-danger">Error</span>
{% endif %}
{{ form.submit }}
</form>
</div>
{% endblock content %}
any help will be appreciated...
The problem was based on views.py
if formS.validate_on_submit():
newuser = User(formS.name.data, formS.email.data, formS.password.data)
newuser.save()
save() function doesn't know where to insert form.blahblah.data. I added required model variables into newuser object and matched to values those came from the html form
Here is the right sample:
newuser = User(name=formS.name.data, email=formS.email.data, password=formS.password.data, created_at=datetime.datetime.now())
I just want to add fields dynamically like Django admin . ( + ) and ( - ) button must perform add and delete img_formset using javascript
The below code is taken from a tutorial I got from web and its working fine. But for now I just need to know how to extend this code do the above.
models.py
from django.db import models
class Pet(models.Model):
name = models.CharField(max_length=100)
breed = models.CharField(max_length=100)
def __unicode__(self):
return self.name
class PetImage(models.Model):
image = models.ImageField(upload_to='pets')
pet = models.ForeignKey(Pet)
created = models.DateTimeField(auto_now_add=True)
#Delete Path
def delete(self, *args, **kwargs):
self.image.delete(False)
super(PetImage, self).delete(*args, **kwargs)
forms.py
from django.forms.models import inlineformset_factory
from django import forms
from .models import Pet, PetImage
class PetForm(forms.ModelForm):
class Meta:
model = Pet
PetImageFormset = inlineformset_factory(Pet, PetImage,
fields=('image',), can_delete=True)
urls.py
from django.conf.urls import *
urlpatterns = patterns('pets.views',
url(r'^add/$', 'add_pet', name='add_pet'),
url(r'^update/(\d+)/$', 'update_pet', name='update_pet'),
)
views.py
from django.core.urlresolvers import reverse
from django.http import HttpResponseRedirect
from django.shortcuts import get_object_or_404, render
from .forms import PetForm, PetImageFormset
from .models import Pet, PetImage
def add_pet(request):
form = PetForm()
img_formset = PetImageFormset(instance=Pet())
if request.method == 'POST':
form = PetForm(request.POST)
if form.is_valid():
pet = form.save()
img_formset = PetImageFormset(request.POST,
request.FILES, instance=pet)
if img_formset.is_valid():
img_formset.save()
return HttpResponseRedirect(reverse('pets:home'))
return render(request, "form.html", {
'form': form,
'img_formset': img_formset,
'action': "Create"
})
def update_pet(request, pet_id):
pet = get_object_or_404(Pet, pk=pet_id)
form = PetForm(instance=pet)
img_formset = PetImageFormset(instance=pet)
if request.method == 'POST':
form = PetForm(request.POST, instance=pet)
if form.is_valid():
pet = form.save(commit=False)
img_formset = PetImageFormset(request.POST,
request.FILES, instance=pet)
if img_formset.is_valid():
pet.save()
img_formset.save()
return HttpResponseRedirect(reverse('pets:home'))
return render(request, "form.html", {
'form': form,
'img_formset': img_formset,
'action': "Update"
})
form.html
{% extend "base.html" %}
{% block title %}Pet{% endblock title %}
{% block content %}
<h4>{{ action }}</h4>
<form method="POST" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
{{ img_formset.as_p }}
</form>
{% endblock content %}