Okay Guys, I have a custom User Registration form, whenever the form is submitted a browser alert pops up saying "The Page at 127.0.0.1:8000 says: Submitted!" and nothing happens. No data is saved. Following is the code of the Index view where i am trying to save the form:
def Index(request):
"""View to serve the index page."""
regform = models.RegistrationForm()
loginform = models.LoginForm()
if request.method == 'POST':
if 'signup' in request.POST:
form = models.RegistrationForm(request.POST)
if form.is_valid():
form.save()
message = 'Your Account has been created. You may login now.'
return shortcuts.render_to_response(
'index.html', {'message' : message, 'regform' : regform, 'loginform' : loginform})
else:
message = 'Error: Please fill in all the fields and try again'
return shortcuts.render_to_response(
'index.html', {'regform' : regform, 'message' : message, 'loginform' : loginform})
elif 'login' in request.POST:
requser = request.POST['loginemail']
reqpass = request.POST['loginpass']
'''check if email exists'''
emailexist = models.member.objects.filter(Email=requser).count()
if emailexist == 1:
exists = True
else:
exists = False
'''if email exists check for password'''
if exists == True:
mem = models.member.objects.get(Email=requser)
if reqpass == mem.Password:
request.session['member_id'] = mem.id
return shortcuts.render_to_response(
'login.html')
else:
error = 'You entered an invalid Password, Please try again.'
return shortcuts.render_to_response(
'index.html', {'error' : error, 'regform' : regform, 'loginform' : loginform})
else:
error = 'That E-mail Address is Not Registered, Please Check the spelling and try again.'
return shortcuts.render_to_response(
'index.html', {'regform' : regform, 'loginform' : loginform, 'error' : error})
else:
return shortcuts.render_to_response(
'index.html', {'regform' : regform, 'loginform' : loginform})
Sorry, Here's the Code to the model and registration form
Model:
class member(models.Model):
"""Model to represent a User."""
First_Name = models.CharField(max_length=100, blank=False)
Last_Name = models.CharField(max_length=100, blank=False)
Stage_Name = models.CharField(max_length=100, unique=True, blank=False)
Account_Type = models.CharField(max_length=200, choices=USERTYPE_CHOICES, blank=False)
Password = models.CharField(max_length=100, blank=False)
Email = models.EmailField(max_length=100, blank=False)
Sex = models.CharField(max_length=1, choices=GENDER_CHOICES, blank=False)
Birthday = models.CharField(max_length=2, blank=False)
def __unicode__(self):
return self.Email
Registration Form:
class RegistrationForm(forms.ModelForm):
Stage_Name = forms.CharField(label='Username')
Email = forms.CharField(initial='you#example.com')
Birthday = forms.CharField(initial='dd/mm/yyyy')
Password = forms.CharField(widget=forms.PasswordInput)
class Meta:
model=member
And here is the template :::::
{% extends 'base.html' %}
{% load login_checkbox %}
{% block topbar %}
<head>
</head>
<body>
<div id="logo" class="left"><img src="/static/images/logo.png" alt="Muzikube" width="200" height="52" border="0"/></div>
<div id="login" class="right">
<form id="loginform" action="." method="post">
{% for field in loginform %}
{% if field.field.widget|is_checkbox %}
<div class="checkbox">{{field}}{{field.label_tag}}<span id="forgotpass">Can't Sign In?</span></div>
{% else %}
{{field.label_tag}}{{field}}
{% endif %}
{% endfor %}
<input id="submit" class="submit" "type="submit" name="login" value="In!" />
</form>
{% if error %}
{{error}}
{% endif %}
</div>
<div class="clear"></div>
</body>
{% endblock topbar %}
{% block content %}
<body>
<div class="left">
<div id="heading">Connect To Other Musicians</div>
<div class="subheading">Upload your music, Share Pictures, Share Videos, Make Friends, Get Known !</div>
<div id="homepageimage"><img src="/static/images/comm.png" alt="Connect to other Musicians Around the world!" width="450" height=""/></div>
<div class="subheading">Muzikube let's you connect to other people around the world that share same interests as you !</div>
</div>
<div id="registrationform" class="right">
<div id="form-title">Sign Up, It's Free !</div>
<div id="form-subtitle">Connect to other musicians around the world.</div>
<div class="border"></div>
<div class="error">
{% if message %}
{{message}}
{% endif %}
</div>
<form id="regform" action="." method="post">
<table>
{{ regform.as_table }}
</table>
<input id="register-submit" class="submit" type="submit" name="signup" value="Sign Up" />
</form>
<div class="border"></div>
</div>
<div class="clear"></div>
</body>
{% endblock content %}
It's a little hard to tell from the code above, but I would guess that you get a POST that doesn't have 'login' or 'signup' in (I can't see why it would have those parameters from the code, maybe it's in the html?) - and so nothing is saved or returned from the post request.
Related
I'm trying to filter a model called "CartItem" , that has a field called item , I want to check whether a product id is in this field. each cartitem instance is connected to a cart.id. The product id is taken from a form in templates.
I currently have " {% if cartitem.objects.filter(item_id=product_id).exists %} " in the template, I also tried making an items list in the views.py , to try to use the "if in" statement in the template, based off the "items" contents, the only problem was that when the browser is refreshed the for loop to create this list is not called , it is only called when the user clicks on the "add to cart" button. Hope that makes sense.
at the moment I get an error:
TemplateSyntaxError
Exception Value:
Could not parse the remainder: '(item.id=product.id).exists' from 'cartitem.objects.filter(item.id=product.id).exists'
Thanks
models.py
class CartItem(models.Model):
item = models.ForeignKey(Product, blank=True, on_delete=models.CASCADE, null=True)
items_cart = models.ForeignKey('Cart', blank=True, on_delete=models.CASCADE, null=True)
quantity = models.IntegerField(null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
timestamp = models.DateTimeField(auto_now_add=True)
def __str__(self):
return 'item:{} cart:{} quantity:{}'.format(self.item, self.items_cart, self.quantity)
views.py
def cart_update(request):
product_id = request.POST.get('product_id')
cart_obj, new_obj = Cart.objects.new_or_get(request)
cart_items = CartItem.objects.filter(items_cart_id=cart_obj)
items = []
for item in cart_items:
items.append(item.item.id)
print(items)
if product_id is not None:
try:
product_obj = Product.objects.get(id=product_id)
except Product.DoesNotExist:
print("Show message to user, product is gone?")
return redirect("cart:home")
cart_obj, new_obj = Cart.objects.new_or_get(request)
cart_items = CartItem.objects.filter(items_cart_id=cart_obj)
if product_obj in cart_items:
cart_items.delete(product_obj)
added = False
else:
newitem = CartItem(item=product_obj, items_cart=cart_obj, quantity=1)
newitem.save()
added = True
request.session['cart_items'] = cart_items.count()
# return redirect(product_obj.get_absolute_url())
if request.is_ajax(): # Asynchronous JavaScript And XML / JSON
print("Ajax request")
json_data = {
"added": added,
"removed": not added,
"cartItemCount": cart_items.count()
}
return JsonResponse(json_data, status=200) # HttpResponse
# return JsonResponse({"message": "Error 400"}, status=400) # Django Rest Framework
return redirect("cart:home")
cart.html
<form class='form-product-ajax' method='POST' action='{% url "cart:update" %}' data-endpoint='{% url "cart:update" %}' class="form" {% if request.user.is_authenticated %}data-user='abc'{% endif %}> {% csrf_token %}
<input type='hidden' name='product_id' value='{{ product.id }}' {% if product.is_digital %}data-is-digital='true'{% endif %}/>
<span class='submit-span'>
{% if cartitem.objects.filter(item_id=product_id).exists %}
<div class='btn-group'> <a class='btn btn-link' href='/cart/'>In cart</a> <button type='submit' class='btn btn-link'>Remove?</button></div>
{% else %}
<button type='submit' class='btn btn-success'>Add to cart</button>
{% endif %}
</span>
</form>
you can not use this syntax in template django:
cartitem.objects.filter(item.id=product.id).exists
you can use templatetags and call it in your template:
register = template.Library()
#register.filter
def existing_product(product):
return CartItem.objects.filter(item.id=product.id).exists()
then load your templatetag in your template
{% load file_name_containing_your_method %}
<form class='form-product-ajax' method='POST' action='{% url "cart:update" %}' data-endpoint='{% url "cart:update" %}' class="form" {% if request.user.is_authenticated %}data-user='abc'{% endif %}> {% csrf_token %}
<input type='hidden' name='product_id' value='{{ product.id }}' {% if product.is_digital %}data-is-digital='true'{% endif %}/>
<span class='submit-span'>
{% if product|existing_product %}
<div class='btn-group'> <a class='btn btn-link' href='/cart/'>In cart</a> <button type='submit' class='btn btn-link'>Remove?</button></div>
{% else %}
<button type='submit' class='btn btn-success'>Add to cart</button>
{% endif %}
</span>
</form>
hope this can help your second question
NB: you should reboot your server after adding a templatetag
I made a project with net-ninja on youtube now I am adding "uploading media" feature in my own project but it is not working although every thing is set just tell me where i m going wrong.
My form is keep asking me to upload image file even though i had already done, every time i send a post request it renders the page again with no value in image field. what is wrong here, why it is not taking image input?Don't comment set the required to false that is not the solution i don't know why some people said this to others on stackoverflow when they asked the same question as me.
My model class looks like this
class Products(models.Model):
name = models.CharField(max_length=500, unique=True, )
price = models.IntegerField()
stock = models.IntegerField()
date_added = models.DateTimeField(verbose_name="date added", auto_now_add=True, )
thumb = models.ImageField(default='default.png', blank=True)
profile = models.ForeignKey(Profile, on_delete=models.CASCADE, default=None,)
def __str__(self):
return self.name
class Meta():
verbose_name_plural = "Products"
My form looks like this
class AddProduct(forms.ModelForm):
name = forms.CharField(widget=forms.TextInput(attrs={'placeholder':'Product Name', 'required':'True', 'class': 'form-control'}))
price = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder':'Set Price', 'required':'True', 'class': 'form-control'}))
stock = forms.IntegerField(widget=forms.NumberInput(attrs={'placeholder':'Number of items', 'required':'True', 'class': 'form-control'}))
thumb = forms.ImageField(required=False, widget=forms.ClearableFileInput(attrs={'placeholder':'Upload Picture', 'enctype' : 'multipart/form-data'}))
class Meta():
model = Products
fields = ('name', 'price', 'stock','thumb', )
HTML looks like this
<form class="row contact_form" action="/shop/add_products" method="post">
{% csrf_token %}
{% for field in form %}
<div class="col-md-12 form-group p_star">
{{ field }}
{{ field.errors }}
</div>
{% endfor %}
<!-- {% for field in form %}
{% for error in field.errors %}
<div class="col-md-12 form-group p_star">
{{ error }}
</div>
{% endfor %}
{% endfor %} -->
{% if form.non_field_errors %}
<div class="col-md-12 form-group p_star">
{{ form.non_field_errors }}
</div>
{% endif %}
<div class="col-md-12 form-group">
<button type="submit" value="submit" class="btn_3">
Add Product
</button>
</div>
</form>
My views file looks like this
#login_required(login_url='/shop/login')
def shop_add_products(request):
if request.method == 'POST':
form = AddProduct(request.POST, request.FILES)
if form.is_valid():
instance = form.save(commit=False)
instance.profile = request.user
instance.save()
return redirect("/shop/products")
else:
form = AddProduct()
return render(request, "pillow_site_html/add_product.html", { 'form':form })
Oh sorry i didn't understood the question here, you are getting that because in fact you are not sending the picture inside your form as you have to add this to your form so it can accept files handling
<form class="row contact_form" action="/shop/add_products" method="post" enctype="multipart/form-data">
First error :I want to check if group_name field value is unique in a modelforms
I tried this code but seems not working as if i put a new value in this field, there is no message but data as not been add to table
Second error: i nether have any message. Maybe, I should not redirect pages ?
my code in views.py:
def group_create(request):
group_form = GroupForm()
if request.method == "POST":
group_form = GroupForm(request.POST)
if group_form.is_valid():
group_name = group_form.cleaned_data.get('group_name')
if Group.objects.filter(group_name=group_name).exists:
messages.error(request, 'this group already exists')
else:
group_form.save()
messages.success(request, 'Group created')
return redirect('group_list')
return render(request, 'imports/group_create.html', {
"group_form": group_form,
})
my model:
class Group(models.Model):
group_id = models.AutoField(primary_key=True)
groupParent_id = models.ForeignKey('self', blank=True, null=True, related_name='Parent', on_delete=models.CASCADE)
group_name = models.CharField(max_length=100, null=False, blank=False, unique=True)
my html:
<div class="container-fluid">
<!-- Code pour message type toaster -->
{% if messages %}
<div class="row">
<div class="col-xs-12">
<ul class="alert" role="alert">
{% for message in messages %}
<p {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</p>
{% endfor %}
</ul>
</div>
</div>
{% endif %}
<!-- fin messages -->
<div class="row">
<div class="col-lg-2 col-md-2 col-sm-2 sidebar">
{% block sidebar %}{% endblock %}
</div>
<div class="col-lg-10 col-lg-offset-2 col-md-10 col-md-offset-2 col-sm-10 col-sm-offset-2 content">
{% block heading %}{% endblock %}
{% block page %}{% endblock %}
</div>
</div>
</div>
Django's ModelForm [Django-doc] already validates the uniqness of fields that you marked unique=True [Django-doc], as is specified in the documentation on Interaction with model validation [Django-doc]:
(...)
The model's clean() method will be called before any uniqueness
checks are made. (...).
If the field is not valid, than it will add that error to the group_form.errors [Django-doc]. The reason why you did not see those is that you, regardless whether the form is valid or not, just redirect to a view, and thus the form is discarded.
If you render the form accordingly, it will add extra messages to the fields with errors:
def group_create(request):
if request.method == "POST":
group_form = GroupForm(request.POST)
if group_form.is_valid():
group_form.save()
messages.success(request, 'Group created')
# only in case of success
return redirect('group_list')
else:
group_form = GroupForm()
return render(request, 'imports/group_create.html', {
"group_form": group_form,
})
I have a model with Usuario where the profile foto goes and it saves perfectly in the database, so to be able to add more images as if it were a gallery, I created another model called Gallery, I copied the same specificiation of what was already working in the model Usuario, however he is not saving the photos in the database, and I do not know where I am going wrong.
I appreciate any help.
and I need the Gallery model to receive the foreign Usuario key
Erro:
IntegrityError at /gallery-novo/
null value in column "usuario_id_id" violates not-null constraint
DETAIL: Failing row contains (3, IMG_20180622_101716179_BURST006.jpg, eu e meu amor, null).
views.py
def gallery(request):
gallery = Gallery.objects.all()
form = GalleryForm()
data = {'gallery': gallery, 'form': form}
return render(request, 'gallery.html', data)
def gallery_novo(request):
if request.method == 'POST':
form = GalleryForm(request.POST, request.FILES)
if form.is_valid():
form.save(user=request.user)
return redirect('sistema_perfil')
else:
form = GalleryForm
return render(request, 'gallery.html', {'form': form})
models.py
class Gallery(models.Model):
gallery = StdImageField( blank=False, variations={
'large': (600, 400),
'thumbnail': (100, 100, True),
'medium': (300, 200),
})
titulo = models.CharField(max_length=50, blank=False)
usuario_id = models.ForeignKey(User, on_delete=models.CASCADE, blank=False)
forms.py
class GalleryForm(forms.ModelForm):
gallery = forms.FileField(
widget=forms.ClearableFileInput(attrs={'multiple': 'True'}))
titulo = forms.CharField()
class Meta:
model = Gallery
fields = ( 'gallery', 'titulo')
def __init__(self, *args, **kwargs):
self.request = kwargs.pop('request', None)
return super(GalleryForm, self).__init__(*args, **kwargs)
def save(self, commit=True, user=None):
form = super(GalleryForm, self).save(commit=False)
form.usario_id = user
if commit:
form.save()
return form
gallery.html
{%extends 'bases/base.html' %}
{% load static %}
{% load bootstrap %}
{% load widget_tweaks %}
{% load crispy_forms_tags %}
{% block main %}
<div class="card text-white bg-primary">
<div class="card-header"><p class="card-text">
<small class="text-muted">
Home /
<a class="text-white">Cadastro</a>
</small></a></p> Cadastro de UsĂșario
</div>
<div class="card title ">
<div class="card-body text-secondary">
<form class="exampleone" action="{% url 'sistema_gallery_novo' %}" method="POST" enctype="multipart/form-data" id="form" name="form" validate >
{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-4">
{{ form.gallery | as_crispy_field }}
</div>
<div class="form-group col-md-4">
{{ form.titulo | as_crispy_field }}
</div>
<div class="form-group col-md-4">
</div>
</div>
</div>
<button type="submit" class="btn btn-primary btn-block">Cadastrar</button>
</form>
</div>
</div>
</div>
{% endblock %}
{% block rightcol %}
{% include 'bases/rightcol.html' %}
{% endblock %}
{% block footer %}
{% include 'bases/footer.html' %}
{% endblock %}
urls.py
url(r'gallery/$', gallery, name='sistema_gallery'),
url(r'gallery-novo/$', gallery_novo, name='sistema_gallery_novo'),
In my opinion, you are reinventing the wheel, the django right approach is to use commit=False on save method:
def gallery_novo(request):
if request.method == 'POST':
form = GalleryForm(request.POST, request.FILES)
if form.is_valid():
my_novo_gallery = form.save(commit=False) #save no commit
my_novo_gallery.user=request.user #set user
my_novo_gallery.save() #save to db
return redirect('sistema_perfil')
This view is supposed to find a blog post and change it's information, but instead of that it just makes a new Blog object with the new (and old) information.
The update view
#login_required
def view_updatepost(request, blog_id):
if not request.user.is_staff or not request.user.is_superuser:
raise Http404
#post = Blog.objects.get(pk=blog_id)
post_to_be_changed = get_object_or_404(Blog, pk=blog_id)
form = BlogForm(request.POST or None, instance=post_to_be_changed)
if form.is_valid():
post_to_be_changed = form.save(commit=False)
#
#
post_to_be_changed.save()
#messages.success(request, "<a href='#'>Item</a> Saved", extra_tags='html_safe')
return HttpResponseRedirect(post_to_be_changed.get_absolute_url())
context = {
'post_to_be_changed': post_to_be_changed,
'form': form,
}
return render(request, 'blog/makepost.html', context)
The template used by the view makepost.html
{% extends "base.html" %}
{% load staticfiles %}
{% block main_content %}
<!-- Page Header -->
<!-- Set your background image for this header on the line below. -->
<header class="intro-header" style="background-image: url('{% static "img/about-bg.jpg" %}')">
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
<div class="page-heading">
<h1>Make a Post</h1>
<hr class="small">
<span class="subheading">Share with the World.</span>
</div>
</div>
</div>
</div>
</header>
<!-- Main Content -->
<div class="container">
<div class="row">
<div class="col-lg-8 col-lg-offset-2 col-md-10 col-md-offset-1">
{% if not user.is_authenticated %}
You must be <u>logged in</u> to make a post.
{% else %}
<form action="{% url "makepost" %}" method="post">
{% csrf_token %}
{{form.as_p}}
<div align="center">
<input class="btn btn-default" type="submit" value="Post to Blog" onclick="window.location='{% url "" %}';"/>
{# Home #}
</div>
</form>
{% endif %}
</div>
</div>
</div>
<hr>
{% endblock main_content %}
The models.py
from django.db import models
import datetime
# Create your models here.
class Blog(models.Model):
title = models.CharField(max_length=250)
subtitle = models.CharField(max_length=250, null = True, blank=True)
date_added = models.DateTimeField(default=datetime.datetime.now())
image = models.TextField(max_length=1000, null = True, blank=True)
tags = models.TextField(max_length=500, null=True, blank=True)
article = models.TextField(max_length=15000, null=True, blank=True)
author = models.CharField(max_length=150, null=True, blank=True)
def get_absolute_url(self):
return "/blog/%i" % self.pk
The forms.py
from django import forms
from .models import Blog
import datetime
class PostForm(forms.Form):
title = forms.CharField()
subtitle = forms.CharField(required=False)
date_added = forms.DateTimeField()
image = forms.URLField(required=False)
tags = forms.CharField(required=False)
article = forms.CharField()
author = forms.CharField()
class BlogForm(forms.ModelForm):
class Meta:
model = Blog
fields = ('title', 'subtitle',
'image', 'tags', 'article')
It seems that you are not referring to your update view in your form action url:
<form action="{% url **"makepost"** %}" method="post">