I am trying to create the object blank in a batch but it is only creating one object after I fill in the form, could anyone help me with what I am doing wrong?
html
{% block content %}
<form class="box" method = "post">
{% csrf_token %}
<h1>Air Ticket Sales</h1>
{{ form }}
batch size:
<input type="number" name="batch" value="{{ batch }}">
<input type="submit" name="" value="Create Blank">
</form>
{% endblock %}
model
class blank(models.Model):
#an integer field that automatically increments by itself as the object are created
number = models.AutoField(primary_key=True)
type = models.CharField(max_length=50, choices=type_choices, default='green')
is_sold = models.BooleanField(default=False)
is_refunded = models.BooleanField(default=False)
date = models.DateField(auto_now_add=True)
date.editable = True
advisor = models.ForeignKey(
User,
models.SET_NULL,
blank=True,
null=True,
)
view
def create_blanks(request):
if request.method == 'POST':
#initializes the data from the form to the value form
form = blank_form(data=request.POST)
batch = request.POST.get("batch", "")
if form.is_valid():
for b in batch:
form.save()
return render(request, "create_blanks.html")
else:
return render(request, "create_blanks.html")
else:
form = blank_form
return render(request, "create_blanks.html", {'form':form})
Yep just found the solution with your help I don't think it is the most efficient or the cleanest one but here you go
for b in range(int(batch)):
form.save()
form.instance = None
form = blank_form(data=request.POST)
Related
I am trying to pass string to a hidden field scenario of a form whose data is stored in a database. The goal is to be able to retrieve extra information on client side without having it as another field of the form.
I am getting 'PersonForm' object has no attribute 'as_widget' error.
This is my Model:
class Person(models.Model):
region = models.CharField(max_length=30)
industry = models.CharField(max_length=30)
uuid = models.CharField(max_length=50, blank=True, unique=True, default=uuid.uuid4)
scenario = models.ForeignKey(Scenario, on_delete=models.CASCADE,)
def __str__(self):
return "{}".format(self.uuid)
My Form
class PersonForm(forms.ModelForm):
class Meta:
model=Person
scenario = forms.CharField(widget=forms.HiddenInput())
fields = ['industry', 'region','scenario']
My View
def personforms(request):
persons = Person.objects.all()
if request.method == 'POST':
filled_form = PersonForm(request.POST)
if filled_form.is_valid():
created_person = filled_form.save()
#DEBUG
print(filled_form.cleaned_data['scenario'])
created_person_pk = created_person.id
filled_form = PersonForm()
return redirect('/scenariopage', {'persons':persons})
else:
created_person_pk = None
return render(request, 'core/scenario-landing-page.html', {'personform':filled_form, 'created_person_pk':created_person_pk})
else:
form = PersonForm()
return render(request, 'core/scenario-landing-page.html', {'personform':form})
And my template
<form action="{% url 'personform' %}" method="post" class="custom-form">
{% csrf_token %}
{% render_field personform class="form-control" %}
{% render_field personform.scenario class="form-control form-control-sm" value='{{ scenario.name }}' %}
<input type="submit" class="btn color-btn" value="Go to Scenario page" data-dismiss="gallery-item"/>
</form>
Questions I have:
I have no Error message. But debug print is indicating that filled_form.is_valid(): seems to be invalid.
And this line in the View never print result:
#DEBUG
print(filled_form.cleaned_data['scenario'])
What I am doing wrong?
How could I possibly pass the data to the field scenario.
I'm trying to create a pastebin clone in Django. I've created a paste app, and a Paste class in my models.py
class Paste(models.Model):
SYNTAX_CHOICES = {
(0, "Plain"),
(1, "Python"),
(2, "HTML"),
(3, "SQL"),
(4, "Javascript"),
(5, "CSS"),
}
content = models.TextField()
title = models.CharField(blank=True, max_length=30)
syntax = models.IntegerField(choices=SYNTAX_CHOICES, default=0)
poster = models.CharField(blank=True, max_length=30)
timestamp = models.DateTimeField(default=datetime.datetime.now, blank=True)
class Meta:
ordering = ('-timestamp',)
def __unicode__(self):
return "%s (%s)" % (self.title or "#%s" % self.id,
self.get_syntax_display())
#permalink
def get_absolute_url(self):
return ('django.views.generic.list_detail.object_detail',
None, {'object_id': self.id})
class PasteAdmin(admin.ModelAdmin):
list_display = ('__unicode__', 'title', 'poster', 'syntax', 'timestamp')
list_filter = ('timestamp', 'syntax')
admin.site.register(Paste, PasteAdmin)
In one of my templates, I have a form that requires the user enter the required details(name of paste, syntax, paste itself).
{% extends "base.html" %}
{% block content %}
<h1>Your user is</h1>
{{ request.user }}
{{ request.user.is.authenticated }}
<form action="" method="POST">
{% csrf_token %}
Title: <textarea rows="1" cols="50" placeholder="Title of paste"></textarea><br>
Syntax: <textarea rows="1" cols="50" placeholder="Enter syntax"></textarea><br>
{{ form.content }}<br>
<textarea rows="4" cols="50" placeholder="Please enter the text you'd wish to paste..."></textarea>
<input type="submit" name="submit" value="Paste" id="submit">
{% endblock content %}
But when the information is entered, the data is not saved when checking the admin. What am I missing to save the entered information to that specific model?
As well, I have a registration form that creates new users, as well as a form that allows you to login/logout.
pastes/views.py
def signup(request):
if request.method == 'POST':
form = UserCreationForm(request.POST)
if form.is_valid():
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
user = authenticate(username=username, password=raw_password)
login(request, user)
return redirect('/home')
else:
form = UserCreationForm()
return render(request, 'signup.html', {'form': form})
How would I go about linking the paste to the user? Or, allowing for it to remain anonymous?
Sorry for all the (dumb) questions, I'm quite lost in this and I've only been doing Django for 24 hours.
New to Django and Python and I need a little help with a foreign key drop down. Basically, I have a category model and a image model and I want users to be able to choose which category to put the image in. How do I create a drop down for the category in the image form? Are my views and html correct too? I have had a look online but I can't seem to do it myself. I keep getting errors.
Here are my models:
class Images(models.Model):
image = models.ImageField(upload_to='images', blank=False)
img_name = models.CharField(max_length=120, blank=True)
img_date = models.DateTimeField(default=now())
img_user = models.ForeignKey(User)
img_cat_id = models.ForeignKey(Categories)
def __unicode__(self):
return self.img_name
class Categories(models.Model):
cat_descr = models.CharField(max_length =120, blank=False)
def __unicode__(self):
return self.cat_descr
VIEWS:
#login_required
def upload_images(request):
context = RequestContext(request)
context_dict={}
if request.method == 'POST': # render the form, and throw it back.
# take the form data and process it!
form = UploadImagesForm(request.POST, request.FILES)
if form.is_valid():
print 'form is_valid'
upload_image = form.save(commit=False)
upload_image.img_user = request.user
if 'image' in request.FILES:
upload_image.image =request.FILES['image']
upload_image.save()
return render(request, 'rmb/upload.html', {'upload_image': form})
else:
print form.errors
# Not a HTTP POST, so we render our form using two ModelForm instances.
# These forms will be blank, ready for user input.
else:
form = UploadImagesForm()
context_dict = {'upload_image': form}
all_categories = Categories.objects.order_by('-id')
context_dict['all_categories'] = all_categories
print context_dict
return render_to_response('rmb/upload.html', context_dict, context)
FORMS:
class UploadImagesForm(forms.ModelForm):
#cat_list = ModelChoiceField(queryset=Categories.objects.all())
class Meta:
model = Images
fields=('image','img_name')
HTML:
{% block body_block %}
<form id="upload_form" method="post" action="/rmb/upload/"
enctype="multipart/form-data">
{% csrf_token %}
{{ upload_image.as_table }}
<input type="submit" name="submit" value="Upload" />
{% for categories in all_categories %}
<div> {{ categories.id }} </div>
{{ categories.cat_descr }}
<input type="submit" name="submit" value="Upload" />
{% endfor %}
</form>
{% endblock %}
You don't need to insert the HTML for the form manually, just use {{form}} in the template.
{% block body_block %}
<form id="upload_form" method="post" action="/rmb/upload/"
enctype="multipart/form-data">
{% csrf_token %}
{{ form }}
</form>
{% endblock %}
By default a ForeignKey will be a select field so you shouldn't need to do much else.
As an aside, give your models and fields more appropriate names. We know these are all image fields, because they are on the image and make sure, unless your model is a collection of things, you give it a singular name. Lastly, when using a Foreign Key and item gets an extra field of fieldname_id that is just the ID, whereas fieldname is the property that gives the related item as well.
So instead of:
class Images(models.Model):
image = models.ImageField(upload_to='images', blank=False)
img_name = models.CharField(max_length=120, blank=True)
img_date = models.DateTimeField(default=now())
img_user = models.ForeignKey(User)
img_cat_id = models.ForeignKey(Categories)
Use:
class Image(models.Model):
image = models.ImageField(upload_to='images', blank=False)
name = models.CharField(max_length=120, blank=True)
date = models.DateTimeField(default=now())
user = models.ForeignKey(User)
category = models.ForeignKey(Categories)
A user will have photos which will be related with their specific album.
So this was the model for that:
class Album(models.Model):
user = models.ForeignKey(User)
title = models.CharField(max_length=200)
pub_date = models.DateTimeField(auto_now_add=True, auto_now=False)
update = models.DateTimeField(auto_now_add=False, auto_now=True)
class Photo(models.Model):
photo_privacy = models.CharField(max_length=1,choices=PRIVACY, default='F')
user = models.ForeignKey(User)
caption = models.TextField()
image = models.ImageField(upload_to=get_upload_file_name)
pub_date = models.DateTimeField(auto_now_add=True, auto_now=False)
Views.py:
def create_album(request, user_name):
user = User.objects.get(username=unquote(user_name))
if request.method=='POST':
pform = AlbumPhotoForm(request.POST, request.FILES)
aform = AlbumForm(request.POST)
p_valid = pform.is_valid()
a_valid = aform.is_valid()
if p_valid and a_valid:
photo = pform.save(commit=False)
album = aform.save(commit=False)
photo.user = user
album.user = user
album.save()
photo.album = album
photo.save()
return HttpResponseRedirect('/'+user.username+'/photos')
else:
return render(request, 'create_album.html',{
'pform':pform,
'aform':aform
})
else:
pform = AlbumPhotoForm()
aform = AlbumForm()
return render(request, 'create_album.html', {
'pform':pform,
'aform':aform
})
And the form:
<form action="/{{ user.username }}/create_album/" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ aform.as_p }}
{{ pform.as_p }}
<input type="submit" value="Create and Upload Album"/>
</form>
This works fine if I only have to upload one file (photo) with that form.
Update:
However what I want to do is, show minimum of three input for uploading photos to the new album:
<form action="/{{ user.username }}/create_album/" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ aform.as_p }}
{{ pform.as_p }}
{{ pform.as_p }}
{{ pform.as_p }}
<input type="submit" value="Create and Upload Album"/>
</form>
When doing so, only the last pform is gets saved. And the other two pform's are ignored. How do I get to save all the three forms of photo (pform) accordingly?
Or is there any other way around? Your help will be much appreciated! Thank you.
Use formsets. They do exactly what you want:
from django.forms.models import formset_factory
PhotoFormSet = formset_factory(AlbumPhotoForm, can_delete=False,
min_num=1, validate_min=True,
max_num=3, validate_max=True,
extra=3)
def create_album(request, user_name):
user = User.objects.get(username=unquote(user_name))
if request.method=='POST':
form = AlbumForm(request.POST)
formset = PhotoFormSet(request.POST, request.FILES)
if all([form.is_valid(), formset.is_valid()]):
album = form.save(commit=False)
album.user = user
album.save()
for photo_form in formset:
if photo_form.cleaned_data:
photo = photo_form.save(commit=False)
photo.album = album
photo.user = user
photo.save()
return redirect('/%s/photos' % user.username )
else:
form = AlbumForm()
formset = PhotoFormSet()
return render(request, 'create_album.html',
{'form': form, 'formset': formset})
And template may look like this:
<form action="." method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<table>
{{ formset }}
</table>
<input type="submit" value="Create and Upload Album"/>
</form>
i'm building a message system for a virtual community, but i can't take the userprofile id
i have in views.py
def save_message(request):
if request.method == 'POST':
form = MessageForm(request.POST)
if form.is_valid():
new_obj = form.save(commit=False)
new_obj.sender = request.user
u = UserProfile.objects.get(request.POST['userprofile_id'])
new_obj.owner = u
new_obj.save()
return HttpResponseRedirect('.')
else:
form = MessageForm()
return render_to_response('messages/messages.html', {
'form': form,
},
context_instance=RequestContext(request))
and the template:
{% block primary %}
<form action="." method="post">
{{ form.as_p }}
<p><input type="hidden" value="{{ userprofile.id }}" name = "owner" /></p>
<p><input type="submit" value="Send Message!" /></p>
</form>
{% endblock %}
forms.py:
class MessageForm(ModelForm):
class Meta:
model = Messages
fields = ['message']
models.py:
class Messages(models.Model):
message = models.CharField(max_length = 300)
read = models.BooleanField(default=False)
owner = models.ForeignKey(UserProfile)
sender = models.ForeignKey(User)
I don't figure out why i get this error,since i'm just trying to get the profileId of a user, using a hiddeen field.
the error is:
Key 'UserProfile_id' not found in <QueryDict: {u'owner': [u''], u'message': [u'fdghjkl']}>
and i'm getting it after i fill out the message text field.
Thanks!
it should be
u = UserProfile.objects.get(request.POST['owner'])
because the input's name is 'owner!!
Can you set raise(raise Exception,request.POST) before string: u = UserProfile.objects.get(request.POST['userprofile_id'])
And show me output.