After a user fills out a form on my site, I user render(request, html, context). I'd like to return the user to the same part of the page after they register. I am not using any front end frameworks (like angular - thats my next project). How would I go about doing this?
views.py:
def homepage(request):
countries = Country.objects.count()
cities = City.objects.count()
start_trip_date = date(xxxx, x, x)
today = date.today()
total_days = today - start_trip_date
queryset_list = Post.objects.active()[:6]
query = request.GET.get("q")
if query:
queryset_list = queryset_list.filter(
Q(title__icontains=query) |
Q(content__icontains=query) |
Q(user__first_name__icontains=query) |
Q(user__last_name__icontains=query)
).distinct()
contact_form = EmailUpdatesForm(request.POST or None)
if contact_form.is_valid():
contact = contact_form.save(commit=False)
contact.email = request.POST['email']
contact.first_name = request.POST['first_name']
contact.save()
profile_data = {
'email': contact.email,
'first_name': contact.first_name,
}
plaintext = get_template('email/frontpage_registered_email/email_text.txt')
htmly = get_template('email/frontpage_registered_email/email_template.html')
text_content = plaintext.render(profile_data)
html_content = htmly.render(profile_data)
subject = "{0}, thank you for registering with xx!".format(contact.first_name)
from_email = 'xx#gmail.com'
to_email = contact.email
msg = EmailMultiAlternatives(subject, text_content, from_email, [to_email])
msg.attach_alternative(html_content, "text/html")
msg.send()
return render(request, "homepage/homepage.html", {})
else:
print contact_form.errors,
context = {
'object_list': queryset_list,
'countries': countries,
'cities': cities,
'days_traveling': total_days.days,
'contact_form': contact_form,
}
return render(request, "homepage/homepage.html", context)
and a made up html to show what I mean:
<body>
<div class="first">content</div>
<div class="second">
<form id="contact_form" method="POST" action="." enctype="multipart/form-data" novalidate>
<fieldset>
{% csrf_toke %}
{{ contact_form|crispy }}
<input class="btn..." type="submit" name="submit" value="Register" />
</fieldset>
</form>
</div>
</body>
In the above I want to return the user to the div class="second".
Thanks you.
To do this, you need to differentiate the default GET request to access the page and the POST of the form.
E.g. You could do:
contact_form = EmailUpdatesForm()
if request.method == 'POST':
contact_form = EmailUpdatesForm(request.POST)
if contact_form.is_valid():
contact = contact_form.save(commit=False)
contact.email = request.POST['email']
....
....
form_submit = True
and pass form_submit in the context.
Then, in HTML:
{% if form_submit %}
<div class="second"></div>
{% else %}
<div class="first"></div>
{% endif %}
Related
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 %}
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
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}}
I have a page with a form that once it gets submitted, the form loads again for the next person. I switched from class based views to function based due to a problem I was having to render modals and I noticed that now, since I'm not redirecting to the form again, it does not clear the data that was entered previously. How can I clear the form upon submission?
views.py
def enter_exit_area(request):
form = WarehouseForm(request.POST or None)
enter_without_exit = None
exit_without_enter = None
if form.is_valid():
emp_num = form.cleaned_data['employee_number']
area = form.cleaned_data['work_area']
station = form.cleaned_data['station_number']
if 'enter_area' in request.POST:
# Some rules to open modals/submit
message = 'You have entered %(area)s' % {'area': area}
if station is not None:
message += ': %(station)s' % {'station': station}
messages.success(request, message)
elif 'leave_area' in request.POST:
# more Rules
message = 'You have exited %(area)s' % {'area': area}
if station is not None:
message += ': %(station)s' % {'station': station}
messages.success(request, message)
return render(request, "operations/enter_exit_area.html", {
'form': form,
'enter_without_exit': enter_without_exit,
'exit_without_enter': exit_without_enter,
})
forms.py
class WarehouseForm(AppsModelForm):
class Meta:
model = EmployeeWorkAreaLog
widgets = {
'employee_number': ForeignKeyRawIdWidget(EmployeeWorkAreaLog._meta.get_field('employee_number').remote_field, site, attrs={'id':'employee_number_field'}),
}
fields = ('employee_number', 'work_area', 'station_number', 'edited_timestamp')
enter_exit_area.html
{% extends "base.html" %}
{% load core_tags %}
{% block main %}
{% if enter_without_exit %}
<div id="auto-open-ajax-modal" data-modal="#create-update-modal" data-modal-url="{% url "operations:update_timestamp_modal" enter_without_exit.id %}" class="hidden"></div>
{% endif %}
{% if exit_without_enter %}
<div id="auto-open-ajax-modal" data-modal="#create-update-modal" data-modal-url="{% url "operations:update_timestamp_modal" exit_without_enter.id %}" class="hidden"></div>
{% endif %}
<form id="warehouseForm" action="" method="POST" class="form-horizontal" novalidate >
{% csrf_token %}
<div>
<div>
<label>Employee</label>
{{ form.employee_number }}
</div>
<div>
<label>Work Area</label>
{{ form.work_area }}
</div>
<label>Station</label>
{{ form.station_number }}
</div>
</div>
<div>
<div>
<button type="submit" name="enter_area" value="Enter">Enter Area</button>
<button type="submit" name="leave_area" value="Leave">Leave Area</button>
</div>
</div>
</form>
{% modal id="create-update-modal" title="Update Timestamp" primary_btn="Submit" default_submit=True %}
{% endblock main %}
# Form not resetting upon submission, because you are sending data to your form
form = WarehouseForm(request.POST or None)
# If you want to reset your form, you should not send data to your form
form = WarehouseForm()
For Example:-
if request.method == 'POST':
form = WarehouseForm(request.POST or None)
else:
form = WarehouseForm()
# Your views.py can be:-
views.py
def enter_exit_area(request):
enter_without_exit = None
exit_without_enter = None
if request.method == 'POST':
form = WarehouseForm(request.POST or None)
if form.is_valid():
emp_num = form.cleaned_data['employee_number']
area = form.cleaned_data['work_area']
station = form.cleaned_data['station_number']
if 'enter_area' in request.POST:
# Some rules to open modals/submit
message = 'You have entered %(area)s' % {'area': area}
if station is not None:
message += ': %(station)s' % {'station': station}
messages.success(request, message)
elif 'leave_area' in request.POST:
# more Rules
message = 'You have exited %(area)s' % {'area': area}
if station is not None:
message += ': %(station)s' % {'station': station}
messages.success(request, message)
else:
form = WarehouseForm()
return render(request, "operations/enter_exit_area.html", {
'form': form,
'enter_without_exit': enter_without_exit,
'exit_without_enter': exit_without_enter,
})
I want the user to submit the registration form and then redirect to another page to verify the number he entered in the mobile number field. If the verification is successful, my user should be created otherwise an error.
Currently my Register View looks like this:
def register_view(request):
template = "accounts/register.html"
print(request.user.is_authenticated())
next = request.GET.get('next')
print next
title = "Register"
form = UserRegisterForm(request.POST or None,)
if form.is_valid():
user = form.save(commit=False)
# number = user.mobile_number
# to_check = phonenumbers.parse(number,"TR")
# if phonenumbers.is_possible_number(to_check) and phonenumbers.is_valid_number(to_check):
# formatted_number = phonenumbers.format_number(to_check, phonenumbers.PhoneNumberFormat.E164)
# params = {
# 'api_key': ' api-key',
# 'api_secret': 'api-secret',
# 'number': formatted_number,
# 'brand': 'MobileVerification',
# }
# url = 'https://api.nexmo.com/verify/json?' + urllib.urlencode(params)
# response = urllib.urlopen(url)
# resp_dict = json.loads(response.read())
# request.session["user_request_id"] = resp_dict['request_id']
# messages.success(request,"A 4 digit pin has been successfully sent to your number.")
# return HttpResponseRedirect(reverse('pin_verify'))
# else:
# messages.error(request,"Enter a valid mobile number.")
# params2 = {
# }
# url = 'https://api.nexmo.com/verify/search/json?' + urllib.urlencode(params)
password = form.cleaned_data.get('password')
user.set_password(password)
user.save()
new_user = authenticate(username=user.mobile_number, password=password)
login(request, new_user)
if next:
return redirect(next)
return redirect("/")
context = {
"form": form,
"title": title
}
return render(request, template, context)
The commented code in the view is what I tried by getting the number and then redirecting but this is not how it should be.
My Register template looks like this:
{% extends "base.html" %}
{% load i18n %}
{% load crispy_forms_tags %}
{% block content %}
<div class='row'>
<div class='col-sm-6 col-sm-offset-3'>
<h1>Register for free!</h1>
<form method="post" action=".">
{% csrf_token %}
{{ form|crispy }}
<input class='btn btn-block btn-primary' type="submit" value="{% trans 'Join' %}" />
</form>
</div>
</div>
<hr/>
<div class='row'>
<div class='col-sm-6 col-sm-offset-3 text-align-center'>
<p>Need to Login?</p>
</div>
</div>
{% endblock %}