How to show choice field in template form - django-models

I want to show the Django choice field from Model on the HTML template like in the following picture. I can't see anything after doing this code.
models.py
class Author(models.Model):
TITLE_CHOICES = [
('MR', 'Mr.'),
('MRS', 'Mrs.'),
('MS', 'Ms.'),
]
title = models.CharField(max_length=3, choices=TITLE_CHOICES)
views.py
def AuthorView(request):
form = Author(request.POST or None)
title = Author.objects.all()
context = {
"form": form,
"ttile": title,
}
if form.is_valid():
form.save()
return render(request, 'index.html')
return render(request, 'index.html', context)
index.html
<select name="confirm_type" id="confirm_type">
{% for object in ttile %}
<option value="by_email"> {{ object }} </option>
{% endfor %}
</select>

Related

How can i filter model field ForeignKey group django

i get All Profiles
i need just Profile of my group
How can I filter the options shown for a ForeignKey field in a Model Form?
In that form I want to show only the profiles in the group , so the user can only get a profile for the new user
class Profile_user(models.Model):
group = models.ForeignKey (Group, null=True ,on_delete=models.CASCADE)
name_Profile= models.CharField(max_length=200, null=True)
class Account(AbstractBaseUser , PermissionsMixin):
Profile = models.ForeignKey(Profile_user,null= True, on_delete=models.CASCADE)
email = models.EmailField(max_length=60, unique=True)
username = models.CharField(max_length=30, unique=True)
class Registration_Form_Users(UserCreationForm):
class Meta:
model = Account
fields = ('email', 'username', 'password1', 'password2','Profile',)
form = Registration_Form_Users()
if request.method == 'POST':
form = Registration_Form_Users(request.POST)
form = Registration_Form_Users()
if request.method == 'POST':
form = Registration_Form_Users(request.POST)
<div class="col-md-6 mb-4">
<h6>Select Profile User</h6>
<fieldset class="form-group">
<select class="form-select" name="Profile"
<option ></option>
{% for item in form.Profile %}
{{item}}
{% endfor %}
</select>
</fieldset>

how to return a verification error message when a user is already authenticated with that same Email address or when the email already exists

i need help on how to return a validation error message when a user try's to register with the already registered email. below its my code
views.py
from audioop import reverse
from email import policy
from multiprocessing import context
from urllib import response
from django.urls import is_valid_path
from .models import actiongame, feature, gpost
from django.contrib.auth import login as dj_login , authenticate, login as real_login, login as bond_to_terms
from django.shortcuts import render
from django.contrib.auth.models import User
from .forms import ProfileUpdateForm, SignUpForm, LoginForm, UserUpdateForm, UserTermsAggrement
from django.shortcuts import redirect
from django.contrib import messages
def trials(request):
# if this is a POST request we need to process the form data
template = 'trials.html'
if request.method == 'POST':
email = request.POST.get('email')
form = SignUpForm(request.POST)
if form.is_valid():
if User.objects.filter(email=email).exists():
messages.info(request, 'Email Aready Used')
form.save()
username = form.cleaned_data.get('username')
raw_password = form.cleaned_data.get('password1')
email = form.cleaned_data.get('email')
user = authenticate(username=username, password=raw_password, email=email)
dj_login(request,user)
return redirect('signup:terms')
else:
form = SignUpForm()
return render(request, 'trials.html', {'form': form})
form.py
from pyexpat import model
from .models import profile as ProfileModel
from dataclasses import fields
from django import forms
from django.contrib.auth.forms import UserCreationForm
from django.contrib.auth.models import User
class SignUpForm(UserCreationForm):
first_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}),help_text='*First Name is Required', required=True)
last_name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}),required=False,help_text='*Optional')
date_of_birth = forms.DateField(widget=forms.DateInput(attrs={'class':'form-control'}),help_text='*Enter A Valid Date Of Birth',required=True)
email = forms.EmailField(widget=forms.EmailInput(attrs={'class':'form-control'}), required=True,help_text='*Enter Email Required', )
username = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control'}), required=True, help_text='*Username is Required')
password1 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}))
password2 = forms.CharField(widget=forms.PasswordInput(attrs={'class':'form-control'}),help_text='*First password must match with the Second Password')
class Meta:
model = User
fields = ('username', 'first_name', 'last_name', 'email', 'password1', 'password2')
trials.html
{% block content %}
<h2>Signup</h2>
<form method="post">
{% csrf_token %}
{% for field in form %}
<p>
{{ field.label_tag }} <br>
{{ field }} <br>
{% if field.help_text %}
<p class="help_text">{{ field.help_text }}</p>
{% endif %}
{% for error in field.errors %}
<p class="error">{{ error }}</p>
{% endfor %}
</p>
{% endfor %}
<input type="submit" value="Register" class="register">
</form>
{% endblock %}
PLEASE I NEED HELP ON SOME OF THESE QUESTIONS BELOW:
How can l write that validation error in django validators.py?
Where did i made a mistake aand how to solve it

Why the NO Null constrained error keeps raising when trying to comment

I am trying to comment in a room but anytime I commented a Non NUll constrained error raised and I cannot find the problem.
The models are as follows:
class Room(models.Model):
host = models.ForeignKey(User, on_delete=models.SET_NULL, null=True)
topic = models.ForeignKey(Topic, on_delete=models.SET_NULL, null=True)
name = models.CharField(max_length=200)
description = models.TextField(null=True, blank=True)
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
class Meta:
ordering = ['-updated', '-created']
def __str__(self):
return self.name
class Message(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
room = models.ForeignKey(Room, on_delete=models.CASCADE)
body = models.TextField()
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return self.body[0:50]
The views is as follows:
def room(request, pk):
room = Room.objects.get(id=pk)
room_messages = room.message_set.all().order_by('-created')
if request.method == 'POST':
message = Message.objects.create(
user=request.user,
room=room,
body=request.POST.get('body')
)
return redirect('room', pk=room.id)
context = {
'room': room, 'room_messages':room_messages
}
return render(request, 'base/room.html', context)
The html:
{% if request.user.is_authenticated %}
<div class="comment-form">
<form method="POST" action="">
{% csrf_token %}
<!-- {{form}} -->
<input type="text" name="comment" placeholder="Write your message here..."/>
</form>
</div>
{% endif %}
{% endblock content %}
Thank you. I found out that in the html I've assigned "comment" instead of "body" to the name=''" in the input tag.

WTForms not working on Google App Engine 1.6.1 & Python 2.7

I'm new at GAE and all that python stuff, so question might be stupid at last.)
I have model:
from google.appengine.ext import db
class Task(db.Model):
name = db.StringProperty()
summary = db.StringProperty(multiline=True)
and I want to auto generate form, so:
import webapp2
import jinja2
import os
from wtforms.ext.appengine.db import model_form
from Tasks.model import Task
jinja_environment = jinja2.Environment(
loader=jinja2.FileSystemLoader(os.path.dirname(__file__) + '/../templates/admin'))
class AddTaskPage(webapp2.RequestHandler):
def get(self):
AddForm = model_form(Task)
template_values = {
'form_self_link': self.request.path,
'form_content': AddForm
}
template = jinja_environment.get_template('add_task.html')
self.response.out.write(template.render(template_values))
add_task.html template:
<form method="POST" action="{{form_self_link}}">
{{form_content}}
<input type="submit" value="Add">
</form>
And the most confusing is output – 
<form method="POST" action="/admin/tasks/add">
<class 'wtforms.ext.appengine.db.TaskForm'>
<input type="submit" value="Добавить">
</form>
There is NO form's elements, there is just very strange <class 'wtforms.ext.appengine.db.TaskForm'> stuff.
I use GAE 1.6.1, python 2.7.2, jinja 2.6 (bundled with GAE), WTForms 0.6.3 (latest)
Could you please help?
UPDATE:
I've used instruction bundled with class and it is not working:
from google.appengine.ext import db
from tipfy.ext.model.form import model_form
# Define an example model and add a record.
class Contact(db.Model):
name = db.StringProperty(required=True)
city = db.StringProperty()
age = db.IntegerProperty(required=True)
is_admin = db.BooleanProperty(default=False)
new_entity = Contact(key_name='test', name='Test Name', age=17)
new_entity.put()
# Generate a form based on the model.
ContactForm = model_form(Contact)
# Get a form populated with entity data.
entity = Contact.get_by_key_name('test')
form = ContactForm(obj=entity)
The only strange moment is "from tipfy.ext.model.form import model_form" string, but I think it is just an error in docs.
UPDATE 2
Well I managed to get it work and may be I missed something, seems like there is no feature "auto print form" in WTForm. So it works now like that:
class AddTaskPage(webapp2.RequestHandler):
def get(self):
AddForm = model_form(Task)()
template_values = {
'form_self_link': self.request.path,
'form_name_field': AddForm.name
}
template = jinja_environment.get_template('add_task.html')
self.response.out.write(template.render(template_values))
And prints out
<form method="POST" action="/admin/tasks/add">
<input id="name" name="name" type="text" value="">
<input type="submit" value="Добавить">
</form>
Well... seems like the only option is to do something like in future (taken from docs)
<form method="POST" action="/...">
<div>{{ form.username.label }}: {{ form.username(class="css_class") }}</div>
<div>{{ form.password.label }}: {{ form.password() }}</div>
<!-- and so on .... -->
</form>
Is it really no any auto-generate and auto-print form libraries for GAE with Python 2.7?(
LAST UPDATE
Well... I found one option to get it work and render all form elements:
class AddTaskPage(webapp2.RequestHandler):
def get(self):
addForm = model_form(Task)()
template_values = {
'form_self_link': self.request.path,
'form': addForm
}
template = jinja_environment.get_template('add_task.html')
self.response.out.write(template.render(template_values))
def post(self):
addForm = model_form(Task)(self.request.POST)
template_values = {
'form_self_link': self.request.path,
'form': addForm
}
template = jinja_environment.get_template('add_task.html')
self.response.out.write(template.render(template_values))
In template:
{% for field in form %}
<tr>
<th>{{ field.label }}</th>
<td>{{ field }}</td>
</tr>
{% endfor %}
Looks not so bad .)
I think you have to pass AddForm.content as a template value (instead of AddForm)
template_values = {
'form_self_link': self.request.path,
'form_content': AddForm**.content**
}
UPDATE
found this in the docs
(http://wtforms.simplecodes.com/docs/0.6.1/ext.html#wtforms.ext.appengine.db.model_form)
wtforms.ext.appengine.db.model_form(model)
Creates and returns a dynamic wtforms.Form class for a given db.Model class. The form class can be used as it is or serve as a base for extended form classes...
So what you are passing into the template is the class, not an instance of it.
AddForm = model_form(Task)()

How to upload a file using the BlobStore in Python App Engine?

I did everything specified in the documentation of app engine but i couldn't get the blobstore work. Maybe some of you can detect what i am doing wrong. When i clicked the submit button
This kind of a url is seen in the address bar and an empty white page is in front of me.
http://localhost:8080/_ah/upload/agltb2JpbHNvcnVyGwsSFV9fQmxvYlVwbG9hZFNlc3Npb25fXxg9DA
Does anyone have a suggestion?
These are my Handlers :
class MainHandler(webapp.RequestHandler):
def get(self):
years = Years.all().order("Year")
months = Months.all().order("SortNumber")
upload_url = blobstore.create_upload_url('/imidergi/upload')
content = {
'upload': upload_url,
'yearList':years,
'monthList':months,
}
render_template(self, 'imidergi.html', content)
class AddDergi(blobstore_handlers.BlobstoreUploadHandler):
def post(self):
# 'file' is file upload field in the form
upload_files = self.get_uploads('file')
blob_info = upload_files[0]
dergi = Dergiler()
dergi.Year = self.request.get("yil")
dergi.Month = self.request.get("ay")
dergi.DergiPDF = str(blob_info.key())
dergi.Name = self.request.get("isim")
dergi.Image = self.request.get("resim")
dergi.put()
self.response.out.write(dergi.Name)
And this is the html which renders the form.
<form action="{{ upload }}" method="post" id="dergiform" enctype="multipart/form-data">
{{ upload }}
<label>Yil:</label><select name="yil">
{% for year in yearList %}
<option value="{{ year.Year }}">{{ year.Year }}</option>
{% endfor %}
</select><br/>
<label>Ay:</label><select name="ay">
{% for month in monthList %}
<option value="{{ month.Name }}">{{ month.Name }}</option>
{% endfor %}
</select><br/>
<label>Isim: </label><input type='text' id="isim" name="isim"/><br/>
<label>Dergi: </label><input type='file' id="file" name="file"/><br/>
<label>Resim: </label><input type='file' id="resim" name="resim"/><br/>
<label></label><input type='submit' value='Ekle'/>
</form>
IIRC BlobstoreUploadHandler expects you to return a redirect after you have handled the POST as your handler is really responding to the special BlobStore upload servers and not directly with the client/browser like in a normal request.
Copy the example from the blobstore docs, and remember that you can only respond with headers (like redirects) and not with body content.

Resources