Creating a form with four fields - python

Good day!
I'm trying to create a form with four fields, like in the screenshot. I'm not getting anywhere yet.
Now I use this form in template:
<form>
<form id="FirstForm" action="{% url one.views.FirstForm %}" method="POST">
{% csrf_token %}
{{ form1 }}
</form>
<form id="SecondForm" action="{% url one.views.SecondForm %}" method="POST">
{% csrf_token %}
{{ form2 }}
</form>
<div>
<input type="submit" name="subform1" value="Отправить" class="form_button">
</div>
</form>
And here is the code in views.py:
def FirstForm(request):
if request.method == 'GET':
form = FirstForm()
return render(request, 'home.html', {'form':form})
else:
form = FirstForm(request.POST)
if form.is_valid():
name = form.cleaned_data['name']
email = form.cleaned_data['email']
try:
send_mail(name, email, settings.EMAIL_HOST_USER, ['daribian#list.ru'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, 'home.html', {'form': form})
def SecondForm(request):
if request.method == 'GET':
form = SecondForm()
else:
form = SecondForm(request.POST)
if form.is_valid():
date = form.cleaned_data['date']
number = form.cleaned_data['number']
try:
send_mail(date, number, settings.EMAIL_HOST_USER, ['daribian#list.ru'])
except BadHeaderError:
return HttpResponse('Invalid header found.')
return redirect('success')
return render(request, 'home.html', {'form': form})
def successView(request):
return HttpResponse('Success!')
As well as the forms themselves:
class FirstForm(forms.Form):
name = forms.CharField(widget=forms.TextInput(attrs={'class' : 'name_class'}), max_length=100, required=True)
email = forms.EmailField(widget=forms.TextInput(attrs={'class' : 'email_class'}), required=True)
class SecondForm(forms.Form):
date = forms.CharField(widget=forms.TextInput(attrs={'class' : 'my_name_class'}), max_length=100, required=True)
number = forms.EmailField(widget=forms.TextInput(attrs={'class' : 'my_email_class'}), required=True)
I keep getting various errors and I think I'm doing something wrong. Can someone tell me what my mistake is?
enter image description here

Related

django image gives me an error "This field is required."

When I send an image to the bank to save, it always returns this message "This field is required." but I fill the field with an image but it always returns this error.
Views
def criar (request):
form = forms_user()
if request.method == 'GET':
return render(request, 'create.html', {'form': form})
if request.method == 'POST':
form = forms_user(request.POST, request.FILES )
if form.is_valid():
form.save()
messages.add_message(request, constants.SUCCESS, 'Cadastro realizado com sucesso.')
form_clean = forms_user()
return render(request, 'create.html', {'form': form_clean})
else:
print(form.errors)
messages.add_message(request, constants.ERROR, f'{form.errors}')
return render(request, 'create.html', {'form': form})
Models
class items(models.Model):
titulo:models.CharField(max_length=30, blank=False)
descricao = models.TextField(max_length=50, blank=False)
usuario = models.CharField(max_length=20, blank=False)
Preco = models.BooleanField(blank=False)
royalties = models.PositiveIntegerField(blank=False)
image = models.ImageField(upload_to='image/', null=True, blank=True)
Forms
class forms_user (forms.ModelForm):
class Meta:
model = items
fields = '__all__'
HTML
<form id="contact" action="" method="post" enctype="multipart/form-data">
<fieldset>
<label for="file">Seu arquivo</label>
{% render_field form.image type="file" id="file" name="myfiles[]" %}
</fieldset>
</form>
Here in the forms I just put the form and the IMG field so it doesn't get too big but the other fields I put everything right.
At first there's a typo in model field titulo it should be = not :.
Secondly, you should always return an HttpResponseRedirect after dealing with POST data, the tip is not specific to Django, it's a good web practice in general, so use following view:
def criar(request):
if request.method == 'GET':
return render(request, 'create.html', {'form': forms_user()})
else:
form = forms_user(request.POST, request.FILES )
if form.is_valid():
form.save()
messages.add_message(request, constants.SUCCESS, 'Cadastro realizado com sucesso.')
return redirect("success")
else:
print(form.errors)
messages.add_message(request, constants.ERROR, f'{form.errors}')
return render(request, 'create.html', {'form': forms_user()})
If you have created modelform then render image field as below, and you can also remove the action attribute as Django by default takes current page route.
Html:
<form id="contact" method="POST" enctype="multipart/form-data">
<fieldset>
<label for="file">Seu arquivo</label>
{{form.image}}
</fieldset>
</form>
urls.py
urlpatterns=[
path("success/", views.success, name="success")
...
]
success.html:
<body>
<h1> The form has been successfully submitted </h1>
</body>

ValueError at /getGiftFromFaucet/ The view contract.views.getGiftFromFaucet didn't return an HttpResponse object. It returned None instead

I'm doing my first question on StackOverFlow about something ig going me crazy.
My project is an Auction site, and is based on django and Web3 to interact with a smart contract deployed on my Ganache.
Now I have got this error on my view :
ValueError at /getGiftFromFaucet/ The view contract.views.getGiftFromFaucet didn't return an HttpResponse object. It returned None instead.
The problem is:
If I register a customer and an address,
then I try to receive tokens from the Faucet,
If I put customer address I don't receive anything.
But if i select another address, I receive token in the first address.
I really don't understand why...
my Model:
class Customer(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
address = models.CharField(max_length=256,
blank=False,
null=False,
unique=True,
error_messages={'unique': 'This address is already registered'})
tokenBalance = models.FloatField(default=0)
dollarBalance = models.FloatField(default=0)
my Registration to the site
def registrationForm(request):
if request.method == 'POST':
form = RegistrationForm(request.POST)
if form.is_valid():
username = form.cleaned_data['username']
password = form.cleaned_data['password']
address = form.cleaned_data['address']
user = User.objects.create_user(
username=username,
password=password,
)
newCustomer = Customer(
user=user,
dollarBalance=random.randrange(500, 1500),
address=address,
tokenBalance=0
)
user.save()
newCustomer.save()
user = authenticate(username=username, password=password)
login(request, user)
messages.success(request, f'''Welcome in DNote {request.user}''')
return redirect('homepage')
else:
form = RegistrationForm()
context = {'form': form}
return render(request, 'registration.html', context)
my Form:
class ReceiveTokenFromFaucet(forms.ModelForm):
class Meta:
model = Customer
fields = ['address']
My view:
def getGiftFromFaucet(request):
customer = Customer.objects.get(user=request.user)
customerAddress = customer.address
if request.method == 'POST':
form = ReceiveTokenFromFaucet(request.POST)
if form.is_valid():
form.save(commit=False)
customerAddress = form.cleaned_data['address']
if customerAddress not in alreadyRecompensed:
contract.functions.transfer(
customerAddress, 100000000000000000000
).transact({'from': faucet})
alreadyRecompensed.append(customerAddress)
customer.tokenBalance += 100000000000000000000
customer.save()
messages.success(request, 'Your Tokens Are accreditate on your Account')
return redirect('/homepage/')
if customerAddress in alreadyRecompensed:
messages.error(request, 'Already Recompensed')
return redirect('/homepage/')
else:
form = ReceiveTokenFromFaucet()
context = {'form': form, 'alreadyRecompensed': alreadyRecompensed}
return render(request, 'requireFromFaucet.html', context)
My Html:
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block head_title %}{{ block.super }} ReceiveFreeTokens {% endblock head_title %}
{% block content %}
<div class="row justify-content-center mt-4">
<div class="col-4">
<h2>DNote</h2>
<h3>Receive Free Tokens</h3>
<p>Available only one time</p>
<br>
<form method="POST" enctype="multipart/form-data" style="max-width:100%">
{% csrf_token %}
{{ form|crispy }}
<br>
<input type="submit" class="btn btn-info" value="Create">
</form>
</div>
</div>
{% endblock content %}

form not display on html, django

I tried to make a blog that allows user posts, store the posts in the db along with the posted date time and the person who posted it.
My problem is that I somehow cannot load the {{form}} to my UI, which makes my form invalid and I just don't know why it doesn't show up the input text box.
I'm not sure if I need a get_post function, but I'll just put it in views.py. (I havnt write the html of that part yet. Just need to see the form first.)
I'm pretty new to Django, can somebody pls help me with this!!! Thanks!
Below are my files.
blog.html file:
{% block posts %}
<div>
<span>New Post: </span>
<form method="post" action="{% url 'posts' %}" enctype="multipart/form-data">
{% csrf_token %}
<table>
{{form}}
<!--not showing in UI-->
</table>
<input id="id_post_button" type="submit" value="Submit" /><br>
</form>
<div>
{% endblock %}
urls.py
urlpatterns = [
path('posts', views.post_action, name='posts'),
path('post/<int:id>', views.get_post, name='post'),
]
Models.py
class PostModel(models.Model):
user_id = models.IntegerField()
post_input_text = models.CharField(max_length=100)
post_profile = models.CharField(max_length=30)
post_date_time = models.DateTimeField(default=timezone.now)
def __str__(self):
return 'id=' + str(self.user_id) + ", post_date_time=" + self.post_date_time + ", post_input_text=" + self.post_input_text + ", post_profile=" + self.post_profile
Views.py:
#login_required
def post_action(request):
print("----post action---")
context = {}
if request.method == "GET":
context['form'] = CreatePost()
context['posts']= PostModel.objects.get(user_id = request.user.id)
return render(request, "socialnetwork/blog.html", context)
form = CreatePost(request.POST, request.FILES)
if not form.is_valid():
print("not valid ~~~~~~~~")
context['form'] = form
context['posts'] = PostModel.objects.get(user_id = request.user.id)
return render(request, "socialnetwork/blog.html", context)
post_input_text = form.cleaned_data.get("post_input_text")
post_date_time = form.cleaned_data.get("post_date_time")
post_profile = form.cleaned_data.get("post_profile")
obj = PostModel.objects.get(
user_id = request.user.id,
)
obj.post_input_text = form.cleaned_data.get("post_input_text")
obj.post_date_time = form.cleaned_data.get("post_date_time")
obj.post_profile = form.cleaned_data.get("post_profile")
obj.save()
form = CreatePost() #refresh the form to original state
context['form'] = form
context['posts'] = obj
return render(request, "socialnetwork/blog.html", context)
def get_post(request, id):
item = get_object_or_404(PostModel, id=id)
print('Picture #{} fetched from db: {} (type={})'.format(id, item.post_input_text, item.post_profile, item.post_date_time))
if not item.post_input_text:
raise Http404
return HttpResponse(item.post_input_text)
forms.py
class CreatePost(forms.Form):
post_input_text = forms.CharField(max_length=100)
post_profile = forms.CharField(max_length=30)
post_date_time = forms.DateTimeField()
Update the template with {{ form.as_table }}, instead of {{form}}

How to update a value in the database in Django?

I am creating a project using Python and Django in which I keeping track of all the products in my store, once I sell a particular product I need to update the number of units of that product remaining
Here is my Models.py file
from django.db import models
class Product(models.Model):
prod_name=models.CharField(max_length=100, blank=False)
company=models.CharField(max_length=100, blank=False)
quantity=models.IntegerField()
price=models.IntegerField()
prod_type=models.CharField(max_length=100)
units=models.IntegerField()
def __str__(self):
return('Name:{0} Company: {1} Qty:{2} Price: {3} Type:{4} Units: {5}'.format(self.prod_name, self.company,self.quantity, self.price, self.prod_type, self.units))
Here is my views.py file
from django.shortcuts import render, redirect, get_object_or_404
from .models import *
from .forms import *
def index(request):
return render(request, 'index.html')
def display_product(request):
items=Product.objects.all()
context={
'items':items
}
return render(request, 'index.html', context)
def add_product(request):
if request.method == "POST":
form = ProductForm(request.POST)
if form.is_valid():
form.save()
return redirect('index')
else:
form =ProductForm(request.POST)
return render(request, 'add_new.html', {'form':form})
def edit_product(request, pk):
item = get_object_or_404(Product, pk=pk)
if request.method == 'POST':
form = ProductForm(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect('index')
else:
form = ProductForm(instance=item)
return render(request, 'edit_product.html', {'form':form})
def sell_product(request, pk):
item = get_object_or_404(Product, pk=pk)
if request.method == 'POST':
form = ProductForm(request.POST, instance=item)
if form.is_valid():
form.save()
return redirect('index')
else:
form = ProductForm(instance=item)
return render(request, 'sell_product.html', {'form':form})
Here is my sell_product.html
{% extends 'base.html' %}
{% block body %}
<div class="container">
<form method="POST">
<br>
{% csrf_token %}
<div class ="form-form row">
<label for="UpdateSold">Units Sold</label>
<input type="Units Sold" class="form-control" id="UpdateSold" aria-describedby="emailHelp" placeholder="Units Sold">
</div>
</div>
<button type="submit" class="btn btn-primary" name="button">Update Product</button>
</form>
</div>
{% endblock %}
So here is a snippet of front end
I have 25 Oreo cookies I sell 3 of them and I enter 3 in Units Sold so I want the Units value of Oreo cookies to be updated to 22Snippet

django : SetPasswordForm is not valid without error

This is my first time to use SetPasswordForm. The form is not valid but does not shows error message. So I'm having hard time to figure out which part went wrong.
urls.py
url(r'^password_change/(?P<username>[-\w.]+)/$', views.password_change, name='password_change'),
url(r'^password_change_done/$', views.password_change_done, name='password_change_done'),
When user input their new password and if the action succeeded, the page will redirect to password_change_done.
views.py
#login_required
def password_change(request, username):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
oldpassword = form.cleaned_data.get('oldpassword')
password1 = form.cleaned_data.get('password1')
password2 = form.cleaned_data.get('password2')
if password1 == password2:
update_session_auth_hash(request, form.username)
form.save()
return HttpResponseRedirect('/blog/password_change_done/')
else:
return render(request, 'blog/profile.html', {'error_message': 'password mismatch'})
else:
return render(request, 'blog/profile.html', {'error_messages': form.errors })
else:
return redirect(reverse('blog:profile', args=[form.user.get_username()]))
#login_required
def password_change_done(request):
return render(request, 'blog/password_change_done.html')
forms.py
class PasswordChangeForm(SetPasswordForm):
error_messages = dict(SetPasswordForm.error_messages, **{
'password_incorrect': ("Your old password was entered incorrectly. Please enter it again."),
})
oldpassword = forms.CharField(
label=("Old password"),
strip=False,
widget=forms.PasswordInput(attrs={'autofocus': True}),
)
field_order = ['oldpassword', 'password1', 'password2']
def __init__(self, user, data, **kwargs):
self.user = user
super(PasswordChangeForm, self).__init__(data, **kwargs)
def clean_oldpassword(self):
oldpassword = self.cleaned_data["oldpassword"]
if not self.user.check_password(oldpassword):
raise forms.ValidationError(
self.error_messages['password_incorrect'],
code='password_incorrect',
)
return oldpassword
templates.py
{{ form.errors }}
{{ form.non_field_errors }}
{% if error_message %}
<h2><strong>{{ error_message }}</strong></h2>
{% else %}<br>
{% endif %}
<form class="form-horizontal" role="form" action="{% url 'blog:password_change' user.username %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
{{ form.as_p }}
<button type="submit" class="button-primary">submit</button></div>
</form>
I put {{ form.errors }} and {{ form.non_field_errors }} so if error happens than it can display error message on website. However till now no message displayed and seems like nothing happens whenever user click submit button.
You have quite a few issues here, but the main problem - as I have told you before - is how you are passing things to the template. You need to follow the pattern as shown in the documentation, and you need to be consistent about your variable naming.
Firstly, move your password check to the form itself:
class PasswordChangeForm(SetPasswordForm):
...
def clean(self):
password1 = self.cleaned_data.get('password1')
password2 = self.cleaned_data.get('password2')
if password1 1= password2:
raise forms.ValidationError('password mismatch')
Now, fix your view:
def password_change(request, username):
if request.method == 'POST':
form = PasswordChangeForm(data=request.POST, user=request.user)
if form.is_valid():
update_session_auth_hash(request, form.username)
form.save()
return HttpResponseRedirect('/blog/password_change_done/')
else:
return render(request, 'blog/profile.html', {'form': form })
else:
return redirect(reverse('blog:profile', args=[username]))
And finally, remove {{ error_messages }} from your template.

Categories

Resources