Cannot assign "''": "IncomeExpense.username" must be a "User" instance - python-3.x

I am working on this below code, trying the add data to the table by getting the values from the form. I have also marked where I am getting the error with #.
I have pasted views.py, models.py and createentry.html below. What might be the reason why I am getting this error and also explain me what I can change to get rid of this error.
#views.py
def create_entry_form(request):
if request.method=='POST':
entry_type=request.POST.get("expensetype")
amount=request.POST.get("amount")
details=request.POST.get("entrydetails")
capture_date=time.strftime('%Y-%m-%d')
entry_username=request.POST.get("entryusername")
entry=IncomeExpense.objects.create(entry_type=entry_type, amount=amount, details=details, capture_date=capture_date, username=entry_username) #getting_error_in_this_line
entry.save()
user_balance = UserBalance.objects.filter(username=username).values_list('balance', flat=True)[0]
if entry_type=="income":
total_balance = user_balance + amount
else:
total_balance=user_balance - amount
update_balance=UserBalance.objects.get(username=username)
update_balance.value=total_balance
update_balance.save()
return render(request, "homepage.html", {'name':username, 'balance':total_balance})
else:
return redirect("www.google.com")
<!---- createentry.html ---->
<form action="{% url 'create_entry_form' %}" method="post">
{% csrf_token %}
<div class="container register-form">
<div class="form">
<div class="note">
<p>Create Entry Form</p>
</div>
<div class="form-content">
<div class="row">
<div class="col-md-6">
<div class="form-group">
<select name="expensetype" id="expensetype" class="form-control">
<option value="expensetype">Select Expense Type</option>
<option value="income">income</option>
<option value="expense">expense</option>
</select>
</div>
<div class="form-group">
<input type="text" name="amount" id="amount" class="form-control" placeholder="Enter the Amount" value=""/>
</div>
</div>
<div class="col-md-6">
<div class="form-group">
<input type="text" name="entrydetails" id="entrydetails" class="form-control" placeholder="Enter the entry details" value=""/>
</div>
<div class="form-group">
<input type="text" name="entryusername" id="entryusername" class="form-control" placeholder="{{name}}" value=""/>
</div>
</div>
</div>
<button type="submit" class="btnSubmit">Submit</button>
</div>
</div>
</div>
</form>
#models.py
from django.db import models
from django.contrib.auth.models import User
class IncomeExpense(models.Model):
entry_type=models.CharField(max_length=100)
amount=models.IntegerField()
details=models.TextField()
capture_date=models.DateField()
username=models.ForeignKey(User, on_delete=models.CASCADE)
def __str__(self):
return f"{self.id}"
class UserBalance(models.Model):
balance=models.IntegerField()
username=models.ForeignKey(User, on_delete=models.CASCADE)
Also, why am I getting an error Cannot assign "''": "IncomeExpense.username" must be a "User" instance. and if I change something I get another similar one.
I tried changing the username to username__username inside this method:
entry=IncomeExpense.objects.create(entry_type=entry_type, amount=amount, details=details, capture_date=capture_date, username=entry_username)

Here we use username field to save user id but you pass username.That is wrong.
def create_entry_form(request):
if request.method=='POST':
entry_type=request.POST.get("expensetype")
amount=request.POST.get("amount")
details=request.POST.get("entrydetails")
capture_date=time.strftime('%Y-%m-%d')
entry_username=request.POST.get("entryusername")
entry=IncomeExpense.objects.create(entry_type=entry_type, amount=amount, details=details, capture_date=capture_date, username=request.user) #getting_error_in_this_line
entry.save()
user_balance = UserBalance.objects.filter(username=request.user).values_list('balance', flat=True)[0]
if entry_type=="income":
total_balance = user_balance + amount
else:
total_balance=user_balance - amount
update_balance=UserBalance.objects.get(username=request.user)
update_balance.balance=total_balance
update_balance.save()
return render(request, "homepage.html", {'name':request.user, 'balance':total_balance})
else:
return redirect("www.google.com")

Related

(1062, "Duplicate entry '' for key 'email'") and (1062, "Duplicate entry '' for key 'phone'") in Django

I am trying to implement Sign Up page in Django using User models. In HTML page, there is an input field for email or phone number. The value I got from this field is assigned to username in Django User model and if the entered value is email, then the value is assigned to email in the User model. Otherwise value assigned to the phone in the User model. When I run the server, user can enter his details with email once. For the second time onwards, I got an error like this:
IntegrityError at /Accounts/CandidateRegister/
(1062, "Duplicate entry '' for key 'phone'")
Request Method: POST
Request URL: http://127.0.0.1:8000/Accounts/CandidateRegister/
Django Version: 4.0.2
Exception Type: IntegrityError
Exception Value:
(1062, "Duplicate entry '' for key 'phone'")
Exception Location: C:\job\venv\lib\site-packages\MySQLdb\connections.py, line 254, in query
Python Executable: C:\job\venv\Scripts\python.exe
Python Version: 3.9.7
Python Path:
['C:\\job\\jobsite',
'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39\\lib',
'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39',
'C:\\job\\venv',
'C:\\job\\venv\\lib\\site-packages']
Similarly, when a user enter with his phone number, their details will saved to database once. After that I got an error like this:
IntegrityError at /Accounts/CandidateRegister/
(1062, "Duplicate entry '' for key 'email'")
Request Method: POST
Request URL: http://127.0.0.1:8000/Accounts/CandidateRegister/
Django Version: 4.0.2
Exception Type: IntegrityError
Exception Value:
(1062, "Duplicate entry '' for key 'email'")
Exception Location: C:\job\venv\lib\site-packages\MySQLdb\connections.py, line 254, in query
Python Executable: C:\job\venv\Scripts\python.exe
Python Version: 3.9.7
Python Path:
['C:\\job\\jobsite',
'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39\\python39.zip',
'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39\\DLLs',
'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39\\lib',
'C:\\Users\\Student\\AppData\\Local\\Programs\\Python\\Python39',
'C:\\job\\venv',
'C:\\job\\venv\\lib\\site-packages']
Can anyone suggest a solution to solve this issue.
HTML code:
<form style="padding:10px 25%;" class="signup-form" id="candidate" method="POST" action="{% url 'candidateregister' %}">
{% csrf_token %}
<div class="form-row">
<div class="form-group col-md-6">
<label for="cafname" style="font: normal normal normal 16px/18px Poppins;">First name</label>
<input type="text" class="form-control" id="cafname" name="cafname" placeholder="Your first name" style="font-family:sans-serif;border:2px solid #d4d2d2;" required>
</div>
<div class="form-group col-md-6">
<label for="calname" style="font: normal normal normal 16px/18px Poppins;">Last name</label>
<input type="text" class="form-control" id="calname" name="calname" placeholder="Your last name" style="font-family:sans-serif;border:2px solid #d4d2d2;" required>
</div>
</div>
<div class="form-group">
<label for="caemorpn" style="font: normal normal normal 16px/18px Poppins;">Email or Phone number</label>
<input type="text" class="form-control" id="caemorpn" name="caemorpn" placeholder="Enter email or phone number" style="font-family:sans-serif;border:2px solid #d4d2d2;" required>
</div>
<div class="form-group">
<label for="capassword1" style="font: normal normal normal 16px/18px Poppins;">Password</label>
<input type="password" class="form-control" id="capassword1" name="capassword1" placeholder="Enter your password" style="font-family:sans-serif;border:2px solid #d4d2d2;" required>
</div>
<div class="form-group">
<label for="capassword2" style="font: normal normal normal 16px/18px Poppins;">Confirm Password</label>
<input type="password" class="form-control" id="capassword2" name="capassword2" placeholder="Confirm your password" style="font-family:sans-serif;border:2px solid #d4d2d2;" required>
</div>
<div class="form-group">
<div class="form-check">
<input class="form-check-input" type="checkbox" id="cagridCheck" name="cagridCheck" style="font-family:sans-serif;border:2px solid #d4d2d2;" required>
<label class="form-check-label mt-3" for="cagridCheck" style="font: normal normal normal 15px/23px Poppins;color: #000000;">
I agree with the Terms and conditions
</label>
</div>
</div>
<input type="hidden" id="catype" name="catype" value="Candidate"/>
{% for msg in messages %}
<center>
<h4 style="color:red;">{{msg}}</h4>
</center>
{% endfor %}
<button type="submit" class="btn btn-primary btn-block btype" style="background-color:#486DFC;margin-top:5%;font-family:sans-serif;">SIGN UP</button>
</form>
models.py
class User(AbstractUser):
email = models.CharField(max_length=30,unique=True)
phone = models.CharField(max_length=30,unique=True)
terms_and_conditions_confirmed = models.BooleanField()
otp = models.CharField(max_length=6)
type = models.CharField(max_length=30)
views.py
def candidateregister(request):
User = get_user_model()
if request.method=='POST':
fname = request.POST.get('cafname')
lname = request.POST.get('calname')
email_phone = request.POST.get('caemorpn')
password1 = request.POST.get('capassword1')
password2 = request.POST.get('capassword2')
terms = request.POST.get('cagridCheck')
type = request.POST.get('catype')
if terms == 'on':
terms = True
else:
terms = False
regex = r'\b[A-Za-z0-9._%+-]+#[A-Za-z0-9.-]+\.[A-Z|a-z]{2,}\b'
if (re.fullmatch(regex, email_phone)):
if (User.objects.filter(email=email_phone).exists()):
messages.info(request, "Email ID Already Taken")
return redirect('register')
user = User.objects.create_user(first_name=fname, last_name=lname, password=password1,
terms_and_conditions_confirmed=terms, type=type, email=email_phone,username=email_phone)
user.save()
return redirect('login')
else:
if (User.objects.filter(phone=email_phone).exists()):
messages.info(request, "Phone number Already Taken")
return redirect('register')
user = User.objects.create_user(first_name=fname, last_name=lname, password=password1,
terms_and_conditions_confirmed=terms, type=type,phone=email_phone,username=email_phone)
user.save()
return redirect('login')
Just set unique=False in models.py
example:
class User(AbstractUser):
email = models.CharField(max_length=30,unique=False)
phone = models.CharField(max_length=30,unique=False)

Python Error AttributeError: 'NoneType' object has no attribute 'encode'

Im creating an update password function on a project using python and flask. The users can update their password by inserting their current password into the first input field in the form and their new password into the second field. The problem is that once I click the update button, I keep getting the error in the title above. AttributeError: 'NoneType' object has no attribute 'encode'
I have inserted the python code I am using below
#user.route("/update_password/<username>", methods=['GET', 'POST'])
def update_password(username):
user = mongo.db.users.find_one({"username": username})
if request.method == "GET":
return render_template(
"update_password.html", username=username)
if request.method == 'POST':
updated_password = generate_password_hash(
request.form.get('updated-password'))
if check_password_hash(
user['password'], request.form.get('existing-password')
):
mongo.db.users.update_one(
{'username': username},
{'$set': {'password': updated_password}}
)
flash("Password Updated Successfully")
return redirect(url_for("user.profile", username=user['session']))
else:
flash("Passwords Do Not Match")
return redirect(url_for("user.update_password", username=user['session']))
Here's the html code I am using for the form:
<div class="row">
<div class="col-lg-8 col-md-10 offset-lg-2 offset-md-1">
<div class="card">
<div class="card-body text-center">
<h1>Update Password</h1>
<form method="POST" action="{{ url_for('user.update_password', username=username) }}">
<div class="mb-3">
<i class="fas fa-lock icon-style"></i>
<label for="existing-password" class="form-label">Enter your existing password</label>
<input type="password" name="existing-password" class="form-control" id="existing-password" required>
</div>
<!-- Password pattern from w3 Schools. See contribution in ReadMe -->
<div class="mb-3">
<i class="fas fa-lock icon-style"></i>
<label for="updated_password" class="form-label">Enter your new password</label>
<input type="password" name="updated_password" class="form-control" id="updated_password"
pattern="(?=.*\d)(?=.*[a-z])(?=.*[A-Z]).{8,15}"
title="Must contain at least one number, one uppercase and lowercase
letter, and at least 8 or more characters" required>
</div>
<button type="submit" class="btn btn-lg register-btn">Update</button>
</form>
</div>
</div>
</div>
</div>
When inspecting the code, it seems there may be a problem with my python function on the following line
updated_password = generate_password_hash(request.form.get('updated-password'))
I would be so grateful if anybody could give me any information on how to solve this
I assume the error is because of field name mismatch. In the Form
<input type="password" name="updated_password">
name is updated_password
And in your route:
if request.method == 'POST':
updated_password = generate_password_hash(
request.form.get('updated-password'))
you are accessing
updated-password
which will give you None because the key name is wrong

Django Python POST Method not writing to database

I now have an issue with my POST Method not writing to the database and not showing in Admin site.
the views.py file works until it gets to the 'if form.is_valid()' but doesn't go any further than that. What am I doing wrong?
Please help, I've spent time trying to search for the answer but to no avail.
code as below
urls.py
path('weekly/', user_views.weekly, name='weekly'),
views.py
def weekly(request):
if request.method == 'POST':
form = SubscriptionForm(request.POST)
print('I got this far 3!')
if form.is_valid():
form.save()
messages.success(request, 'Thank you for your payment!')
return redirect('classes')
else:
return render(request, 'clubex/weekly.html', {'title': '1 Week Free'})
else:
return render(request, 'clubex/weekly.html', {'title': '1 Week Free'})
models.py (do these names have to match the 'id' in the HTML doc?)
class Subscription(models.Model):
firstName = models.CharField(max_length=100)
lastName = models.CharField(max_length=100)
username = models.CharField(max_length=100)
sub_type = models.CharField(max_length=50)
email = models.EmailField(max_length=100)
address = models.CharField(max_length=100)
address2 = models.CharField(max_length=100)
state = models.CharField(max_length=100)
country = models.CharField(max_length=100)
zip = models.CharField(max_length=10)
same_address = models.BooleanField()
save_info = models.BooleanField()
credit = models.BooleanField()
debit = models.BooleanField()
paypal = models.BooleanField()
cc_name = models.CharField(max_length=100)
cc_number = models.CharField(max_length=20)
cc_expiration = models.CharField(max_length=10)
cc_cvv = models.IntegerField()
def __str__(self):
return f'{self.firstName} {self.lastName} {self.sub_type}'
forms.py (do these names have to match the 'id' in the HTML doc?)
class SubscriptionForm(forms.ModelForm):
class Meta:
model = Subscription
fields = [
'firstName',
'lastName',
'username',
'sub_type',
'email',
'address',
'address2',
'state',
'country',
'zip',
'same_address',
'save_info',
'credit',
'debit',
'paypal',
'cc_name',
'cc_number',
'cc_expiration',
'cc_cvv',
]
weekly.html (note the link to the validating js file)
<link rel="canonical" href="https://getbootstrap.com/docs/4.5/examples/checkout/">
<!-- Bootstrap core CSS -->
<link href="../assets/dist/css/bootstrap.min.css" rel="stylesheet">
<Link rel="stylesheet" href="{% static 'ClubEx/form-validation.css' %}" type="text/css" >
<h2>Checkout form for {{ user.username }}</h2>
<p class="lead">Hi {{ user.username }}. Please check and fill out the following form to complete your subscription application. </p>
</div>
<div class="row">
<div class="col-md-4 order-md-2 mb-4">
<h4 class="d-flex justify-content-between align-items-center mb-3">
<span class="text-muted">Your cart</span>
<span class="badge badge-secondary badge-pill">1</span>
</h4>
<ul class="list-group mb-3">
<li class="list-group-item d-flex justify-content-between lh-condensed">
<div>
<h6 class="my-0">Product name</h6>
<small class="text-muted">1 Free Weekly Subscription</small>
</div>
<span class="text-muted">Free</span>
</li>
<li class="list-group-item d-flex justify-content-between">
<span>Total (NZD)</span>
<strong>0.00</strong>
</li>
</ul>
</div>
<div class="col-md-8 order-md-1">
<form method="post" action="/weekly/" class="needs-validation">
{% csrf_token %}
<h4 class="mb-3">Billing address</h4>
<div class="row">
<div class="col-md-6 mb-3">
<label for="firstName">First name</label>
<input type="text" class="form-control" id="firstName" placeholder="" required>
<div class="invalid-feedback">
Valid first name is required.
</div>
</div>
<div class="col-md-6 mb-3">
<label for="lastName">Last name</label>
<input type="text" class="form-control" id="lastName" placeholder="" value="" required>
<div class="invalid-feedback">
Valid last name is required.
</div>
</div>
</div>
<div class="mb-3">
<label for="username">Username</label>
<div class="input-group">
<div class="input-group-prepend">
<span class="input-group-text">#</span>
</div>
<input type="text" class="form-control" id="username" placeholder="Username" required>
<div class="invalid-feedback" style="width: 100%;">
Your username is required.
</div>
</div>
</div>
<div class="mb-3">
<label for="sub_type">Subscription Type</label>
<select class="custom-select d-block w-100" id="sub_type" required>
<option value="">Choose...</option>
<option>Weekly $ Free</option>
<option>Monthly $10</option>
<option>Annual $100</option>
</select>
<div class="invalid-feedback">
Please select a valid Subscription.
</div>
</div>
<div class="mb-3">
<label for="email">Email <span class="text-muted">(Optional)</span></label>
<input type="email" class="form-control" id="email" placeholder="you#example.com">
<div class="invalid-feedback">
Please enter a valid email address for shipping updates.
</div>
</div>
<div class="mb-3">
<label for="address">Address</label>
<input type="text" class="form-control" id="address" placeholder="1234 Main St" required>
<div class="invalid-feedback">
Please enter your shipping address.
</div>
</div>
<div class="mb-3">
<label for="address2">Address 2 <span class="text-muted">(Optional)</span></label>
<input type="text" class="form-control" id="address2" placeholder="Apartment or suite">
</div>
<div class="row">
<div class="col-md-4 mb-3">
<label for="state">State</label>
<select class="custom-select d-block w-100" id="state" required>
<option value="">Choose...</option>
<option>Auckland</option>
<option>Christchurch</option>
</select>
<div class="invalid-feedback">
Please select a valid country.
</div>
</div>
<div class="col-md-5 mb-3">
<label for="country">Country</label>
<select class="custom-select d-block w-100" id="country" required>
<option value="">Choose...</option>
<option>New Zealand</option>
</select>
<div class="invalid-feedback">
Please provide a valid City.
</div>
</div>
<div class="col-md-3 mb-3">
<label for="zip">Postcode</label>
<input type="text" class="form-control" id="zip" placeholder="" required>
<div class="invalid-feedback">
Postcode required.
</div>
</div>
</div>
<hr class="mb-4">
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="same_address">
<label class="custom-control-label" for="same_address">Shipping address is the same as my billing address</label>
</div>
<div class="custom-control custom-checkbox">
<input type="checkbox" class="custom-control-input" id="save_info">
<label class="custom-control-label" for="save_info">Save this information for next time</label>
</div>
<hr class="mb-4">
<h4 class="mb-3">Payment</h4>
<div class="d-block my-3">
<div class="custom-control custom-radio">
<input id="credit" name="paymentMethod" type="radio" class="custom-control-input" checked required>
<label class="custom-control-label" for="credit">Credit card</label>
</div>
<div class="custom-control custom-radio">
<input id="debit" name="paymentMethod" type="radio" class="custom-control-input" required>
<label class="custom-control-label" for="debit">Debit card</label>
</div>
<div class="custom-control custom-radio">
<input id="paypal" name="paymentMethod" type="radio" class="custom-control-input" required>
<label class="custom-control-label" for="paypal">PayPal</label>
</div>
</div>
<div class="row">
<div class="col-md-6 mb-3">
<label for="cc_name">Name on card</label>
<input type="text" class="form-control" id="cc_name" placeholder="" required>
<small class="text-muted">Full name as displayed on card</small>
<div class="invalid-feedback">
Name on card is required
</div>
</div>
<div class="col-md-6 mb-3">
<label for="cc_number">Credit card number</label>
<input type="text" class="form-control" id="cc_number" placeholder="" required>
<div class="invalid-feedback">
Credit card number is required
</div>
</div>
</div>
<div class="row">
<div class="col-md-3 mb-3">
<label for="cc_expiration">Expiration</label>
<input type="text" class="form-control" id="cc_expiration" placeholder="" required>
<div class="invalid-feedback">
Expiration date required
</div>
</div>
<div class="col-md-3 mb-3">
<label for="cc_cvv">CVV</label>
<input type="text" class="form-control" id="cc_cvv" placeholder="" required>
<div class="invalid-feedback">
Security code required
</div>
</div>
</div>
<hr class="mb-4">
<button class="btn btn-primary btn-lg btn-block" type="submit">Pay Now!</button>
</form>
</div>
</div>
<script src="https://code.jquery.com/jquery-3.5.1.slim.min.js"
integrity="sha384-DfXdz2htPH0lsSSs5nCTpuj/zy4C+OGpamoFVy38MVBnE+IbbVYUew+OrCXaRkfj"
crossorigin="anonymous"></script>
<script>window.jQuery || document.write('<script src="../assets/js/vendor/jquery.slim.min.js"><\/script>')</script>
<script src="../assets/dist/js/bootstrap.bundle.min.js"></script>
<script src="form-validation.js"></script>
{% endblock content %}
from the terminal
I got this far 3!
[14/Sep/2020 10:49:41] "POST /weekly/ HTTP/1.1" 200 11778
Not Found: /weekly/form-validation.js
Not Found: /assets/dist/css/bootstrap.min.css
Not Found: /assets/dist/js/bootstrap.bundle.min.js
[14/Sep/2020 10:49:41] "GET /weekly/form-validation.js HTTP/1.1" 404 5242
[14/Sep/2020 10:49:41] "GET /assets/dist/css/bootstrap.min.css HTTP/1.1" 404 5266
[14/Sep/2020 10:49:41] "GET /assets/dist/js/bootstrap.bundle.min.js HTTP/1.1" 404 5281
Not Found: /assets/dist/js/bootstrap.bundle.min.js
[14/Sep/2020 10:49:41] "GET /assets/dist/js/bootstrap.bundle.min.js HTTP/1.1" 404 5281
Not Found: /weekly/form-validation.js
[14/Sep/2020 10:49:41] "GET /weekly/form-validation.js HTTP/1.1" 404 5242
The form is not valid. With sub_type and state, you are passing a choicefield and the model needs a charfield
Your form must be:
class SubscriptionForm(forms.ModelForm):
firstName = forms.CharField(
required=True,
label="First Name",
widget=forms.TextInput( attrs = {
'type':"text",
'placeholder':"First name",
'class':'form-control', # html input class
})
)
sub_type = forms.ChoiceField(
required=True,
label="Subscription Type",
choices= (
('Option 1', 'Choose'),
('Option 2', 'Weekly $ Free'),
...
),
widget=forms.Select( attrs = {
'class':'your-css-class'
})
)
...
pass the form to your html
def weekly_get(request):
form = SubscriptionForm()
return render('weekly.html',{'form':form })
then, your html
<form method="post" action="/weekly/" class="needs-validation">
{% csrf_token %}
{% for field in form %}
<div class="row">
<div class="col-md-6 mb-3">
{{field.label_tag}}
{{field}}
</div>
</div>
{% endfor %}
</form>

How to build a form in angular such that it on submission it returns the array having same input names

<form (ngSubmit)="submit(feedbackForm)" #feedbackForm="ngForm">
<div class="form-group" *ngFor="let ques of questions;">
<label for="comment">{{ques.question}}</label>
<textarea
class="form-control"
rows="5"
id = "comment"
name="feedbackAnswers"
ngModel
required>
</textarea>
</div>
<button
type="submit"
class="btn btn-info"
*ngIf=!sendingEmail
[disabled]="!feedbackForm.valid">Save</button>
</form>
on ,
console.log(feedbackForm),
the 'values' property only shows first input. How can I get an array having name i.e 'feedbackAnswers' and having value what use did input.
You have to make the name attribute unique so that the template driven form will create a control for each input in the loop... try the following change. [name]="ques.question"
<form (ngSubmit)="submit(feedbackForm)" #feedbackForm="ngForm">
<div class="form-group" *ngFor="let ques of questions;">
<label for="comment">{{ques.question}}</label>
<textarea
class="form-control"
rows="5"
id = "comment"
[name]="ques.question"
ngModel
required>
</textarea>
</div>
<button
type="submit"
class="btn btn-info"
*ngIf=!sendingEmail
[disabled]="!feedbackForm.valid">Save</button>
</form>

Generate a new Timesheet related to a Task from website frontend Odoo 11.0

I'm making a module that let the user to read and add Timesheet from their task with some more functions(like material used...expenses etc).
Here the view of input fields that i need to store into db
<div class='row' style="margin: 5px;">
<div class="col-md-12 col-sm-12" style="margin-top: 15px;">
<button class="btn btn-default" onclick="openTab('TimeSheet')">TimeSheet</button>
<button class="btn btn-default" onclick="openTab('Materials')">Materials</button>
<button class="btn btn-default" onclick="openTab('Expenses')">Expenses</button>
<button type="submit" class="btn btn-default">Signature</button>
</div>
<div id="TimeSheet" class="col-md-12 tabs" style="display:none">
<h2>Add new TimeSheet</h2>
<form action="/my/taskReport/add/">
<div class="form-group">
<input type="hidden" name="task_id" t-attf-value="{{ task.id }}"
class="o_website_from_input form-control"/>
<label class="control-label" for="data">Data:</label>
<input type="date" name="date" class="o_website_from_input form-control"/>
<br/>
<label class="control-label" for="employee">Employee:</label>
<input type="text" name="partner_id" class="o_website_from_input form-control"
t-att-value="user.name"/>
<br/>
<label class="control-label" for="description">Description:</label>
<textarea type="text" name="description" class="o_website_from_input form-control"/>
<br/>
<label class="control-label" for="duration">Duration:</label>
<input type="time" name="unit_amount" class="o_website_from_input form-control"
value="00:00"/>
<br/>
</div>
<button type="submit" class="btn btn-default">Submit</button>
</form>
</div>
Here the controller that take datafields
#http.route(['/my/taskReport/add/'],
type='http',
auth="user",
methods=['POST', 'GET'],
csrf=False,
website=True)
def project_task_report_add_timesheet(self, task_id, **post):
timesheet_value = {
'date': post.get('date'),
'partner_id': post.get('partner_id'),
'description': post.get('description'),
'unit_amount': post.get('unit_amount'),
'res_model': 'project.task',
'res_id': task_id,
}
timesheet_id = request.env['project.task'].sudo().create(timesheet_value)
return werkzeug.utils.redirect('/my/tasksReport/')
The problem is that the Timesheet is not be stored.
Anyone can help?
The problem was related to the parameters taken by the post.get().
#http.route(['/my/taskReport/add/'],
type='http',
auth="user",
methods=['POST', 'GET'],
csrf=False,
website=True)
def project_task_report_add_timesheet(self, task_id, **post):
timesheet_value = {
'date': post.get('date'),
'partner_id': int(post.get('partner_id')),
'description': post.get('description'),
'unit_amount': post.get('unit_amount'),
'res_model': 'project.task',
'res_id': task_id,
}
timesheet_id = request.env['project.task'].sudo().create(timesheet_value)
return werkzeug.utils.redirect('/my/tasksReport/')
By casting with int() the partner_id i don't get error because the post.get('partner_id') return a string of the value not the integer of the id!

Resources