how to show a manytomany django form - python

I am trying to do that a user can modify his/her profile.
At the rigth (in the image attached in url) we can see that the user has coins and wallets (Bitcoin, Ethereum and coinbase)
The goal is that in the left form, the user could change his/her data and add or remove coins and wallets.
I need:
How can I do that with ModelMultipleChoiceField?
How can I show the user's data in the input when the form is loaded?. e.g: antonigalile will be un name input
I would like that my widget looks like that:
Here my files:
models.py
from django.db import models
from django.utils.timezone import now
from django.contrib.auth.models import AbstractUser
class Coin(models.Model):
name = models.CharField(unique=True,max_length=50)
url = models.CharField(max_length=200)
transaction_fee = models.FloatField(default=0.0,blank=True)
price = models.FloatField(default=0.0,blank=True)
market_cap = models.IntegerField(default=0,blank=True)
volume = models.IntegerField(default=0,blank=True)
circulating = models.IntegerField(default=0,blank=True)
change = models.FloatField(default=0.0,blank=True)
def __str__(self):
return self.name
class Wallet(models.Model):
name = models.CharField(unique=True,max_length=50)
url = models.CharField(max_length=200)
coins = models.ManyToManyField(Coin)
def __str__(self):
return self.name
class Usuario(AbstractUser):
name = models.CharField(max_length=12, help_text="The name must be between 2 and 12 characters")
email = models.EmailField(max_length=60, unique=True, help_text="The email must be between 5 and 30 characters")
password = models.CharField(max_length=78)
change_password_code = models.CharField(blank=True,max_length=15)
activated = models.BooleanField(default=False)
activated_code = models.CharField(default="",max_length=15)
ip = models.CharField(blank=True,max_length=15)
last_login = models.DateField(default=now)
wallets = models.ManyToManyField(Wallet)
coins = models.ManyToManyField(Coin)
avatar = models.CharField(blank=True,default="bitcoin.png",max_length=15)
delete_code = models.CharField(default="",max_length=9,blank=True)
two_factors_auth = models.BooleanField(default=False)
two_factors_auth_code = models.CharField(default="",max_length=12,blank=True)
fingerprint = models.CharField(max_length=64,blank=True)
forms.py
class EditProfileForm(forms.ModelForm):
class Meta:
model = Usuario
exclude = ()
wallets = forms.ModelMultipleChoiceField(queryset=Wallet.objects.all(),to_field_name="name")
name = forms.CharField(label='Name')
email = forms.EmailField(label='Email')
two_factors_auth = forms.BooleanField()
coins = forms.ModelMultipleChoiceField(queryset=Coin.objects.all(),to_field_name="name")
form.html
<form method="post">
{% csrf_token %}
<div class="form-group">
<p> {{ edit_profile_form.name.label }} </p>
{% render_field edit_profile_form.name class+="form-control" %}
{{ edit_profile_form.name.errors }}
</div>
<div class="form-group">
<p> {{ edit_profile_form.email.label }} </p>
{% render_field edit_profile_form.email class+="form-control" %}
{{ edit_profile_form.email.errors }}
</div>
<div class="form-group">
<p>My Wallets</p>
{{ edit_profile_form.wallets}}
{{ edit_profile_form.wallets.errors }}
</div>
<div class="form-group">
<p>My Coins</p>
{{ edit_profile_form.coins }}
{{ edit_profile_form.coins.errors }}
</div>
<div class="form-group">
<p>Activate two factor authentication
{{ edit_profile_form.two_factors_auth }}</p>
{{ edit_profile_form.two_factors_auth.errors }}
</div>
<button type="submit" name="profileButton" class="btn btn-primary">Save</button>
</form>
views.py (no finished)
class userPageView(TemplateView):
template_name = 'user.html'
def get_context_data(self, **kwargs):
context = super().get_context_data(**kwargs)
context['edit_profile_form'] = EditProfileForm(prefix='contact')
return context
def post(self, request, *args, **kwargs):
return render(request, 'user.html')
¿What can I do?
Thanks

Related

Show item details together with item name in forms dropdown

currently I'm trying to show part quantity (quan) together with part name in the dropdown. I have a Part table that carries the part name and part quantity and this table called as ForeignKey into the Order table. So, in the Order form during choose the part name from the part dropdown, I would like to show part quantity as well besides the part name. Any idea to make it like that?
models.py
class Part(models.Model):
partno = models.CharField(max_length=50)
partname = models.CharField(max_length=50)
quan = models.PositiveIntegerField(default= 0)
def __str__(self):
return '{}, quantity - {}'.format(self.partname, self.quan)
class Order(models.Model):
supplier = models.ForeignKey(Supplier, on_delete=models.CASCADE)
product = models.ForeignKey(Product, on_delete=models.CASCADE)
part = models.ForeignKey(Part, on_delete=models.CASCADE)
views.py
def create_order(request):
from django import forms
form = OrderForm()
if request.method == 'POST':
for form_data in forms_data:
forms = OrderForm(request.POST)
if forms.is_valid():
supplier = forms.cleaned_data['supplier']
product = forms.cleaned_data['product']
part = forms.cleaned_data['part']
order = Order.objects.create(
supplier=supplier,
product=product,
part=part,
)
return redirect('order-list')
context = {
'form': form
}
return render(request, 'store/addOrder.html', context)
HTML
<form action="#" method="post" id="form-container" novalidate="novalidate">
{% csrf_token %}
<div class="form-group">
<label for="product" class="control-label mb-1">Product</label>
{{ form.product }}
</div>
<div class="form-group">
<label for="supplier" class="control-label mb-1">Supplier</label>
{{ form.supplier }}
</div>
<div class="form-group">
<label for="part" class="control-label mb-1">Part Name</label>
{{ form.part }}
</div>
</form>
You will have to write "__ str __"(without spaces between str and __) method for model 'Part'
def __str__(self):
return '{}, quantity - {}'.format(self.partname, self.quan)
Check this post also: What is doing __str__ function in Django?

How can I display the db values of a row in a form before I update the form?

I'm trying to display the employee data after filtering the DB by pk which I passed via the URL.
I can update the form, although I don't want the form fields to be empty since I just want to update, which means its not all the fields I'm going to touch
forms.py
class AddEmployeeForm(forms.Form):
genderset = [(0,'--Select an Option--'),('Male','Male'), ('Female', 'Female')]
marital_status_set = [(0,'--Select an Option--'),('Married','Married'), ('Single', 'Single')]
employment_type_set = [(0,'--Select an Option--'),('Contract','Contract'), ('Full-Time', 'Full-Time'),('Intern', 'Intern')]
employment_status_set = [(0,'--Select an Option--'),('Active','Active'), ('Inactive', 'Inactive')]
first_name = forms.CharField(label = "First Name ", max_length = 200)
last_name = forms.CharField(label = "Last Name ", max_length = 200)
employee_id = forms.IntegerField()
email = forms.EmailField(label = "Email ", max_length = 200)
address = forms.CharField(label = "Address", max_length = 200)
role = forms.CharField( max_length = 200)
date_of_birth = forms.DateField()
join_date = forms.DateField()
end_date = forms.DateField()
location = forms.CharField( max_length = 200)
hod = forms.ModelChoiceField(queryset=Department.objects.only('lead'))
phone_number = forms.CharField( max_length = 200)
employment_type = forms.ChoiceField( choices = employment_type_set)
employment_status = forms.ChoiceField( choices = employment_status_set )
marital_status = forms.ChoiceField( choices = marital_status_set )
gender = forms.ChoiceField( choices = genderset )
department = forms.ModelChoiceField(queryset=Department.objects.only('dept_name'))
credentials = forms.FileField()
passport = forms.FileField()
date_added = forms.DateTimeField( initial = datetime.now, widget=forms.HiddenInput())
views.py
#login_required(login_url='/accounts/login')
def edit(request, pk):
employee = Employee.objects.filter(pk=pk)
form = AddEmployeeForm()
context = {
'employee': employee,
'form':form
}
return render(request, 'employees/edit.html', context)
edit.html
{% extends 'base.html' %}
{% load crispy_forms_tags %}
{% block content %}
<div class="page-wrapper">
<div class="content container-fluid">
<div class="row">
<div class="col-xs-4">
<h4 class="page-title">Edit Employee Details</h4>
</div>
<div class="col-xs-4 text-center">
{% include "partials/_alerts.html" %}
</div>
</div>
<form class="m-b-30" action="{% url 'add' %}" method="post" enctype="multipart/form-data">
{% csrf_token %}
<div class="row"></div>
{% for field in form %}
<div class="col-sm-6">
<div class="form-group">
{{ field.errors }}
{{ field|as_crispy_field }}
{% if field.help_text %}
<p class="help">{{ field.help_text|safe }}</p>
{% endif %}
</div>
</div>
{% endfor %}
</div>
<div class="m-t-20 text-center">
<button class="btn btn-primary">Save Changes</button>
</div>
</form>
</div>
</div>
{% endblock content %}
Its meant to display the values of an employee that was filterd from the database using the PK value
In views.py, you can pass a dictionary into AddEmployeeForm constructor to display the values:
#login_required(login_url='/accounts/login')
def edit(request, pk):
employee = Employee.objects.filter(pk=pk)
field_values = { 'first_name': employee.first_name } #...other fields
form = AddEmployeeForm(field_values)
context = {
'employee': employee,
'form':form
}
return render(request, 'employees/edit.html', context)
A Form instance is either bound to a set of data, or unbound.
If it’s bound to a set of data, it’s capable of validating that data and rendering the form as HTML with the data displayed in the
HTML.
If it’s unbound, it cannot do validation (because there’s no data to validate!), but it can still render the blank form as HTML.
Reference https://docs.djangoproject.com/en/2.2/ref/forms/api/#ref-forms-api-bound-unbound
You can create a form instance and use this format:
form = In_Form(initial={'username': name})
And in your template you can then populate your form using :
{{employee.name}}

The view students.views.addgrregister didn't return an HttpResponse object. It returned None instead

ValueError at /students/addgrregister/
i am trying to add students in gr_register but its giving an error due to this error the code is not working i also upload the template (addgrregister.html) kndly tell me where is the issue in these pages
models.py
class gr_register(models.Model):
Gender_Choices = (
('M', 'Male'),
('FM', 'Female'),
)
Status_Choices = (
('P', 'Present'),
('FM', 'Left'),
)
gr_no = models.IntegerField(primary_key=True)
first_name = models.CharField(max_length=20)
last_name = models.CharField(max_length=20)
date_birth = models.DateField(null=True)
classes_A = models.ForeignKey(Classes, on_delete=models.CASCADE, related_name="classes_A", default=1, verbose_name="Class of Admission")
sections_A = models.ForeignKey(Sections, on_delete=models.CASCADE, related_name="sections_A", default=1, verbose_name="Section of Admission")
gender = models.CharField(max_length=10, choices=Gender_Choices)
classes_C = models.ForeignKey(Classes, on_delete=models.CASCADE, related_name="classes_C", verbose_name="Current Class")
sections_C = models.ForeignKey(Sections, on_delete=models.CASCADE, related_name="sections_C", verbose_name="Current Section")
address = models.CharField(max_length=100, null=True, verbose_name="Home Address")
area_code = models.ForeignKey(Area, on_delete=models.CASCADE, verbose_name="Area")
status = models.CharField(max_length=10, choices=Status_Choices, default='P')
class Meta:
ordering = ('gr_no',)
def __str__(self):
return self.first_name
views.py
from django.shortcuts import get_object_or_404, render, redirect
def addgrregister(request):
if request.method == 'POST':
form = gr_registerForm(request.POST)
if form.is_valid():
form.save()
return redirect('home')
else:
form = gr_registerForm()
return render(request, 'students/addgrregister.html', {'form': form})
forms.py
from django import forms
from django.forms import ModelChoiceField, ModelForm
from .models import *
class gr_registerForm(ModelForm):
classes_A = forms.ModelChoiceField(queryset=Classes.objects.all())
sections_A = forms.ModelChoiceField(queryset=Sections.objects.all())
classes_C = forms.ModelChoiceField(queryset=Classes.objects.all())
sections_C = forms.ModelChoiceField(queryset=Sections.objects.all())
area_code = forms.ModelChoiceField(queryset=Area.objects.all())
class Meta:
model = gr_register
fields = '__all__'
def init(self, *args, **kwargs):
forms.ModelForm.init(self, *args, **kwargs)
addgrregister.html
{% extends 'authenticate/base.html' %}
{% block content %}
<div class="container">
<h4 class="text-center">ADD GR_REGISTER</h4>
<hr/>
<form method="POST" action="{% url 'addgrregister' %}" enctype="multipart/form-data">
{% csrf_token %}
{% for field in form %}
<div class="form-group row">
<label for="id_{{ field.name }}" class="col-2 col-form-label">{{ field.label }}</label>
<div class="col-10">
{{ field }}
</div>
</div>
{% endfor %}
<button type="submit" class="btn btn-primary" name="button">Add GR_REGISTER</button>
</form>
<br/><br/>
</div>
{% endblock %}
There is nothing returned when form is not valid. I think you try like this:
def addgrregister(request):
form = gr_registerForm(request.POST or None) # it initates a form. If the request type is POST, then there will be a dict available with posted data in request.POST. If request is not POST, then the form will initiate with empty data.
if request.method == 'POST':
if form.is_valid(): # Form valid checks if the submitted form is valid or not. If not, it will store errors in the form. When that form is passed to template, it will show errors in html
form.save() # It will store data in DB
return redirect('home')
# when for is invalid, it will show the error in the form
return render(request, 'students/addgrregister.html', {'form': form})
Update
Show form errors in template:
{% for field in form %}
<div class="form-group row">
<label for="id_{{ field.name }}" class="col-2 col-form-label">{{ field.label }}</label>
<div class="col-10">
{{ field }}
{{ field.errors }} // <-- Updated here
</div>
</div>
{% endfor %}

Accessing database Model from HTML Template in DJango

In the below code Instead of {{ i.user }} I want to access a value from another table with {{ i.user }} as matching value. How to done it within HTML
{% for i in obj reversed %}
<div class="container">
<blockquote>
<header> {{ i.topic }} {{ i.user }} </header>
<p> {{ i.desc }} </p>
<footer> {{ i.time }} </footer>
</blockquote>
{% endfor %}
</div>
Here are My Models
from django.db import models
class Accounts(models.Model):
name=models.CharField(max_length=30)
phone=models.CharField(max_length=20,unique=True)
mail=models.EmailField()
password=models.CharField(max_length=20)
def __str__(self):
return self.name
class BlogPost(models.Model):
user=models.CharField(max_length=30)
topic=models.CharField(max_length=100)
desc=models.CharField(max_length=1000)
likes=models.IntegerField(null=True,default=0)
time=models.DateTimeField(null=True)
def __str__(self):
return self.user
And I want to get value from Accounts using Blogspot.user i.e {{ i.user }} in template
Thanks in Advance...
from django.contrib.auth.models import AbstractBaseUser
class Accounts(AbstractBaseUser):
name = models.CharField(max_length=30)
phone = models.CharField(max_length=20,unique=True)
mail = models.EmailField()
password = models.CharField(max_length=20)
def __str__(self):
return self.name
class BlogPost(models.Model):
user = models.ForeignKey(Accounts, related_name='accounts')
topic = models.CharField(max_length=100)
desc = models.CharField(max_length=1000)
likes = models.IntegerField(null=True,default=0)
time = models.DateTimeField(null=True)
def __str__(self):
return self.user
Now, using foreign key you can access accounts model attributes in your template.

User got saved in django regardless of other two forms with it are valid or not

UserForm got saved no matter if other two forms (StudentOrFacultyForm and UserIdForm) are valid or not. User should not be created if other two forms are invalid. Please help!
models.py
class StudentOrFaculty(models.Model):
STUDENT = 'S'
FACULTY = 'F'
PROFILE_CHOICES = (
(STUDENT, 'Student'),
(FACULTY, 'Faculty'),
)
# Links to a User model instance
user = models.OneToOneField(User, related_name='fors')
# The Additional attributes
st_or_faculty = models.CharField(max_length=1, choices=PROFILE_CHOICES)
def __str__(self):
if(self.st_or_faculty == 'S'):
fullname = 'Student'
elif(self.st_or_faculty == 'F'):
fullname = 'Faculty'
else:
fullname = 'Unknown'
return str(self.user) + " is " + fullname
class UserActivation(models.Model):
user = models.OneToOneField(User)
activation_key = models.CharField(max_length=255, blank=True)
key_expires = models.DateTimeField(default=(timezone.now() + timedelta(days=1)))
def __str__(self):
return self.user.username
class Meta:
verbose_name_plural=u'Activation'
class UserIdCard(models.Model):
user = models.OneToOneField(User)
id_card = models.ImageField(upload_to='id_cards')
forms.py
FORS_CHOICES = (('F','Faculty'),('S','Student'))
class UserForm(forms.ModelForm):
first_name = forms.CharField(help_text="Frist Name")
last_name = forms.CharField(help_text="Last Name")
username = forms.CharField(help_text="Username")
email = forms.CharField(help_text="Email")
password = forms.CharField(widget=forms.PasswordInput(),
help_text="Password")
class Meta:
model = User
fields = ('first_name', 'last_name', 'username', 'email',
'password')
def clean_email(self):
email = self.cleaned_data.get('email')
username = self.cleaned_data.get('username')
if email and User.objects.filter(email=email).exclude(username=username).count():
raise forms.ValidationError(u'this Email is already registered.')
return email
class StudentOrFacultyForm(forms.ModelForm):
"""
Studentorfaculty option
"""
st_or_faculty = forms.ChoiceField(
label="Student Or Faculty",
required=True,
choices=FORS_CHOICES,
widget=forms.RadioSelect,
help_text="Student Or Faculty")
class Meta:
model = StudentOrFaculty
fields = ('st_or_faculty',)
class UserIdCardForm(forms.ModelForm):
id_card = forms.ImageField(label="College Id Card")
class Meta:
model = UserIdCard
fields = ('id_card',)
def clean_id_card(self):
image = self.cleaned_data.get('id_card',False)
if image:
if hasattr(image,'_size'):
if image._size > 4*1024*1024:
raise ValidationError("Image file too large (should be < 4mb )")
return image
else:
raise ValidationError("Couldn't read uploaded image")
views.py
def user_signup(request):
# get the request's context
context = RequestContext(request)
if request.user.is_authenticated():
return HttpResponseRedirect(reverse('notices:index'))
# A boolean value for telling the template whether the signup was successfull
# Set to flase initially. Code changes value to True when registration
#successfull
registered = False
# If it's a HTTP POST, we're interested in processing form data
if request.method == 'POST':
# Attempt to grab information
# We make use of UserForrm and UserProfileForm
user_form = UserForm(data=request.POST)
student_or_faculty_form = StudentOrFacultyForm(data=request.POST)
user_id_card_form = UserIdCardForm(data=request.POST, files=request.FILES)
# If the two foms are valid
if user_form.is_valid() and student_or_faculty_form.is_valid() and\
user_id_card_form.is_valid():
# Save the user's form data to the database.
user = user_form.save()
# Now we hash the password with set_password method.
# One hashed, we can update the user object.
user.set_password(user.password)
user.is_active = False
user.save()
uid = user_id_card_form.save(commit=False)
uid.user = user
uid.save()
fors = student_or_faculty_form.save(commit=False)
fors.user = user
fors.save()
username = user_form.cleaned_data['username']
email = user_form.cleaned_data['email']
tmp = random.random()
tmp = str(tmp)
tmp = tmp.encode('utf-8')
salt = hashlib.sha1(tmp).hexdigest()[:5]
salt = salt.encode('utf-8')
email_en = email.encode('utf-8')
activation_key = hashlib.sha1(salt+email_en).hexdigest()
key_expires = datetime.datetime.today() + datetime.timedelta(2)
email = user_form.cleaned_data['email']
#Get user by username
user=User.objects.get(username=username)
new_profile = UserActivation(user=user, activation_key=activation_key,
key_expires=key_expires)
new_profile.save()
# Send email with activation key
email_subject = 'Account confirmation'
email_body = "Hey %s, thanks for signing up. To activate your account, click this link within \
48hours http://www.socialboard.in/accounts/confirm/%s" % (username, activation_key)
send_mail(email_subject, email_body, 'support#socialboard.in',
[email], fail_silently=False)
# log in the user
user_name = request.POST['username']
'''new_user = authenticate(username=request.POST['username'],
password=request.POST['password'])
login(request, new_user)'''
# Update the variable to tell the registration was successful
registered = True
return HttpResponseRedirect(reverse('accounts:aftersignup', kwargs={'user_name':user_name}))
# Invalid forms
# Print problems to the terminal.
# they will also be show to the user
else:
print( user_form.errors, student_or_faculty_form.errors, user_id_card_form.errors )
# Not a HTTP POST, so we render our form using two instance
# These forms will be blank, ready for the user input.
else:
user_form = UserForm()
student_or_faculty_form = StudentOrFacultyForm()
user_id_card_form = UserIdCardForm()
# Render the template depending on the context.
return render_to_response(
'accounts/signup.html',
{ 'user_form': user_form, 'student_or_faculty_form': student_or_faculty_form,
'user_id_card_form': user_id_card_form,
'registered': registered},
context)
signup.html
<form class="form-horizontal" role="form" id="user_form" method="post" action="{% url 'accounts:signup' %}"
enctype="multipart/form-data">
{% csrf_token %}
{% for field in user_form.visible_fields %}
<div class="form-group has-feedback">
<div class="col-sm-12"><input type="{{ field.field.widget.input_type }}" class="form-control" name="{{ field.name }}" placeholder="{{ field.label}}" value="{% if field.value %}{{field.value}}{% endif %}"></div>
{% if field.errors %} <div class="col-sm-10 text-danger"> {{ field.errors }} </div> {% endif %}
</div>
{% endfor %}
{% for fieldi in student_or_faculty_form.visible_fields %}
<div class="from-group has-feedback">
<!--<label class="col-sm-2 control-label">I am </label>-->
{% for value,text in fieldi.field.choices %}
<label class="radio-inline">
<input type="radio" name="{{ fieldi.name }}" id="" value="{{ value }}"><b> {{ text }}</b>
</label>
{% endfor %}
{% if fieldi.errors %} <div class="col-sm-10 text-danger "> {{ fieldi.errors }} </div> {% endif %}
</div>
{% endfor %}
<br>
{% for field in user_id_card_form.visible_fields %}
<div class="form-group has-feedback">
<div class="col-sm-12"><b>{{field.field.label}} :</b></div>
<div class="col-sm-12"><input type="{{ field.field.widget.input_type }}" class="form-control" name="{{ field.name }}"
placeholder="{{ field.label}}" value="{% if field.value %}{{field.value}}{% endif %}"></div>
{% if field.errors %} <div class="col-sm-10 text-danger"> {{ field.errors }} </div> {% endif %}
</div>
{% endfor %}
<!-- Provide a button to click to submit the form -->
<div class="form-group">
<div class="col-sm-offset-0 col-sm-10">
<button type="submit" class="btn btn-warning"><b>Sign Up</b></button><br><br>
<div>or have an account? <span class="btn btn-xs btn-default">Log In</span></div>
</div>
</div>
</form>

Categories

Resources