Assign request.user.id to OneToOneField in Model using form - python

I'm using django auth for users. Every user can create one row - based on Client model. But i have problem because I cant assign in form.is_valid to field id request.user.id.
Because id is required I exclude this field in form class Meta.
Please give me some advice how i can assign user.id to my OneToOneField field.
I'm using PyCharm and when i put form. i dont see any of fields in my Model so i thing that i make some mistake in my code :(
Model:
class Client(models.Model):
id = models.OneToOneField(User, on_delete=models.CASCADE, unique=True, primary_key=True)
name = models.CharField(max_length=256, unique=True)
vat = models.CharField(max_length=12, unique=True)
address = models.CharField(max_length=64)
zip_code = models.CharField(max_length=10, help_text='Zip Code')
city = models.CharField(max_length=64)
country = models.CharField(max_length=6, default='US')
forwarding_address = models.CharField(max_length=64, blank=True)
forwarding_zip_code = models.CharField(max_length=10, blank=True)
forwarding_city = models.CharField(max_length=64, blank=True)
forwarding_country = models.CharField(max_length=6, blank=True)
phone = models.CharField(max_length=20)
def __str__(self):
re = self.name + ' [' + str(self.id) + ']'
return re
Form:
class ClientProfileForm(forms.ModelForm):
class Meta:
model = Client
exclude = ['id']
View:
def profile_create(request):
if request.method == 'POST':
form = ClientProfileForm(request.POST)
if form.is_valid():
form.save(commit=False)
form.id = request.user.id
form.save()
return HttpResponseRedirect('/client/profile/')
dict = {}
dict['form'] = form
return render(request, 'client/profile_edit.html', dict)
else:
if Client.objects.filter(id=request.user.id).exists():
return HttpResponseRedirect('/client/profile/edit/')
else:
dict = {}
dict['form'] = ClientProfileForm()
return render(request, 'client/profile_edit.html', dict)
Template:
{% extends 'registration/base.html' %}
{% block title %} Client profile {% endblock %}
{% block content %}
{{ form.non_field_errors }}
<form role="form" action="" method="post">{% csrf_token %}
{{ form.name.errors }}
<div class="form-group login-input">
<i class="fa fa-envelope overlay"></i>
<input type="text" class="form-control text-input"
{% if form.name.value != nulls %} value="{{ form.name.value }}" {% endif %}
id="{{ form.name.name }}" name="{{ form.name.name }}">
</div>
{{ form.vat.errors }}
<div class="form-group login-input">
<i class="fa fa-envelope overlay"></i>
<input type="text" class="form-control text-input"
{% if form.vat.value != nulls %} value="{{ form.vat.value }}" {% endif %}
id="{{ form.vat.name }}" name="{{ form.vat.name }}">
</div>
{{ form.address.errors }}
<div class="form-group login-input">
<i class="fa fa-envelope overlay"></i>
<input type="text" class="form-control text-input"
{% if form.address.value != nulls %} value="{{ form.address.value }}" {% endif %}
id="{{ form.address.name }}" name="{{ form.address.name }}">
</div>
(....)
<div class="row">
<div class="col-sm-12">
<button type="submit" class="btn btn-default btn-block">Create</button>
</div>
</div>
</form>
{% endblock %}
Cheers!

That's not the right pattern. It should be:
if form.is_valid():
obj = form.save(commit=False)
obj.id = request.user.id
obj.save()

Related

django does not show value form db

I have problem. My template don't show my value from db.
I think that I don't have defined model UserProduct in views.py in function product.
wievs.py
def index(request):
context = {
'products': Product.objects.order_by('category').filter(is_published=True)
}
return render(request, 'offers/products.html', context)
def userproduct(request):
context = {
'userproduct': UserProduct.objects.filter(user_id=request.user.id),
}
return render(request, 'offers/userproducts.html', context)
def product(request, product_id):
product = get_object_or_404(Product, pk=product_id)
context = {
'product': product,
}
return render(request, 'offers/product.html', context)
models.py
class Product(models.Model):
product_name = models.CharField(max_length=100)
category = models.CharField(max_length=50)
weight = models.FloatField()
description = models.TextField(blank=True)
photo = models.ImageField(upload_to='photos/%Y/%m/%d/')
is_published = models.BooleanField(default=True)
list_date = models.DateField(default=datetime.now, blank=True)
def __str__(self):
return self.product_name
class UserProduct(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
product_name = models.ForeignKey(Product, on_delete=models.CASCADE)
price = models.FloatField()
is_published = models.BooleanField(default=True)
list_date = models.DateField(default=datetime.now, blank=True)
def __str__(self):
return str(self.user.username) if self.user.username else ''
offers/product.html
<div class="p-4">
<p class="lead">
{% if user.is_authenticated %}
<span class="mr-1">
<p>Price</p></span>
<p class="colores lead font-weight-bold">{{ product.price }} £</p>
{% endif %}
<p >Description</p>
<p class="colores lead font-weight">{{ product.description }}</p>
<p class="colores lead font-weight-bold">Weight: {{ product.weight }}kg</p> </p>
{% if user.is_authenticated %}
<form class="d-flex justify-content-left">
<!-- Default input -->
<input type="number" value="1" aria-label="Search" class="form-control" style="width: 100px">
<button class="btn send-click btn-md my-0 p" type="submit">Add to cart
<i class="fas fa-shopping-cart ml-1"></i>
</button>
</form>
{% endif %}
</div>
Value product.price does not show.
The idea is that each user will have a different product price.
That's because your Product model has no price field; What you have is userproduct_set as a reverse foreign key relationship from the UserProduct model.
So you may have multiple price for one Product instance.
You can use the following code to show all the available prices for your product:
<div class="p-4">
<p class="lead">
{% if user.is_authenticated %}
<span class="mr-1">
<p>Price</p></span>
{% for userproduct in product.userproduct_set.all %}
<p class="colores lead font-weight-bold">{{ userproduct.price }} £</p>
{% endfor %}
{% endif %}
<p>Description</p>
<p class="colores lead font-weight">{{ product.description }}</p>
<p class="colores lead font-weight-bold">Weight: {{ product.weight }}kg</p> </p>
{% if user.is_authenticated %}
<form class="d-flex justify-content-left">
<!-- Default input -->
<input type="number" value="1" aria-label="Search" class="form-control" style="width: 100px">
<button class="btn send-click btn-md my-0 p" type="submit">Add to cart
<i class="fas fa-shopping-cart ml-1"></i>
</button>
</form>
{% endif %}
</div>
Read more about them in the docs.
Edit
As you mentioned in the comments, you want to find out the price assigned to the current logged in user, if the user is logged in and show weight and description even if the user is not logged in. So you need:
def product(request, product_id):
product = get_object_or_404(Product, pk=product_id)
user_product = None
if request.user.is_authenticated:
user_product = UserProduct.objects.filter(product_name_id=product_id, user=request.user)
if user_product:
user_product = user_product.first()
context = {
'product': product,
'user_product': user_product,
}
return render(request, 'offers/product.html', context)
and your template as well:
<div class="p-4">
<p class="lead">
{% if user.is_authenticated and user_product %}
<span class="mr-1">
<p>Price</p></span>
<p class="colores lead font-weight-bold">{{ user_product.price }} £</p>
{% endif %}
<p>Description</p>
<p class="colores lead font-weight">{{ product.description }}</p>
<p class="colores lead font-weight-bold">Weight: {{ product.weight }}kg</p> </p>
{% if user.is_authenticated and user_product %}
<form class="d-flex justify-content-left">
<!-- Default input -->
<input type="number" value="1" aria-label="Search" class="form-control" style="width: 100px">
<button class="btn send-click btn-md my-0 p" type="submit">Add to cart
<i class="fas fa-shopping-cart ml-1"></i>
</button>
</form>
{% endif %}
</div>

TypeError at /students/exam/1/ int() argument must be a string, a bytes-like object or a number, not 'list'

I'm trying to submit this form through this model and views, but I am getting the TypeError which is shown in the screenshot. Though I want to also submit it to the database. I have taking all my value just to drop it into database.
I'd be very happy if you'd assist to solve the save() method as well.
student.py:
#login_required
#student_required
def take_exam(request, pk):
course = get_object_or_404(Course, pk=pk)
student = request.user.student
question = course.questions.filter()
#correct_answers = student.course_answers.filter(answer__question__quiz=course, answer__is_correct=True).count()
total_questions = course.questions.count()
choice = Answer.objects.filter()
marks_obtainable = Details.objects.get(course_id=course)
if request.method == 'POST':
question_pk = request.POST.getlist('question_pk')
question_obj = Question.objects.filter(id=int(question_pk))
choice_pk = [request.POST['choice_pk{}'.format(q)] for q in question_obj]
#print(marks_obtainable.marks_obtained)
zipped = zip(question_obj, choice_pk)
for x, y in zipped:
correct_answers = Answer.objects.filter(question_id=x, is_correct=True).values("id").first()['id']
print(x, y, correct_answers)
if int(y) == int(correct_answers):
#z = TakenQuiz(student=student, course=course, \
#question=x, selected_choice=y, marks_obtained=marks_obtainable, is_correct=True)
print("correct")
else:
print("Not Correct")
return render(request, 'classroom/students/take_exam_form.html', {
'course': course,
'question': question,
'course': course,
'total_questions': total_questions,
'choice': choice,
'marks_obtainable': marks_obtainable
})
models.py:
class Question(models.Model):
course = models.ForeignKey(Course, on_delete=models.CASCADE, related_name='questions')
text = models.CharField('Question', max_length=500)
def __str__(self):
return self.text
class Answer(models.Model):
question = models.ForeignKey(Question, on_delete=models.CASCADE, related_name='answers')
text = models.CharField('Answer', max_length=255)
is_correct = models.BooleanField('Correct answer', default=False)
def __str__(self):
return self.text
take_exam_form.html:
<h2 class="mb-3">{{ course.name }}</h2>
Course id <h2 class="mb-3">{{ course.id }}</h2>
Student id <h2 class="mb-3">{{ request.user.id }}</h2>
Total Question: <h2 class="mb-3">{{ total_questions }}</h2>
Mark Obtainable <h2 class="mb-3">{{ marks_obtainable.maximum_marks }}</h2>
<form method="post" novalidate>
{% csrf_token %}
{% for questions in question %}
<input type="hidden" name="question_pk" value="{{ questions.pk }}">
<h3 class="text-info">{{ questions.text|safe }}</h3>
{% for choices in questions.answers.all %}
<input class="form-check-input" type="radio" name="choice_pk{{ questions.pk }}" id="choices-{{ forloop.counter }}" value="{{ choices.pk }}">
<label class="form-check-label" for="choices-{{ forloop.counter }}">
{{ choices.text|safe }}
</label>
{% endfor %}
{% endfor %}
<button type="submit" class="btn btn-primary">Submit Now →</button>
</form>
I can see that the only int() call is in
int(y)
Try this print(type(y)). Maybe y is a list object. That's why the error said:
The arg must be string or ... not a list

django modelform how to know input type is checkbook?

My modelform is a dynamically generated modelform,I want to know the type of is_true in the modelForm. The type of the input tag is the checkbook type.
If I know the type=‘checkbox’ of the is_true field, add a class attr to him separately.
The default type='checkbox’ interface is too ugly
models
class Employee(AbstractBaseUser):
"""
用户表
"""
username = models.CharField(max_length=30, verbose_name='姓名')
email = models.EmailField(verbose_name='邮箱', unique=True)
is_true = models.BooleanField(default=False, verbose_name='是否超级用户')
views
class ModelFormDemo(ModelForm):
class Meta:
model = self.model
if self.list_editable:
fields = self.list_editable
else:
fields = '__all__'
excluded = self.excluded
def __init__(self, *args, **kwargs):
super(ModelFormDemo, self).__init__(*args, **kwargs)
def add_view(self, request):
form = ModelFormDemo()
if request.method == "POST":
res_dict = {'status': 1, 'msg': 'success'}
form = ModelFormDemo(request.POST)
if form.is_valid():
obj = form.save()
else:
res_dict['msg'] = form.errors
res_dict['status'] = 2
return JsonResponse(res_dict)
return render(request, "xadmin/add_view.html", locals())
html
<form class="layui-form" method="post">
{% csrf_token %}
{% for field in form %}
{% if field.name == 'employee' %}
<input type="hidden" name="employee" value="{{ user.id }}">
{% else %}
<div class="layui-form-item">
<label class="layui-form-label">{{ field.label }}</label>
<div class="layui-input-inline">
{{ field }}
</div>
</div>
{% endif %}
{% endfor %}
<div class="layui-form-item">
<div class="layui-input-block">
<input type="button" class="layui-btn" lay-filter="add" lay-submit="" value="add">
</input>
<button type="reset" class="layui-btn layui-btn-primary">reset</button>
</div>
</div>
</form>
You can use the Widget.attrs arg in your form __init__ method.
https://docs.djangoproject.com/en/dev/ref/forms/widgets/#django.forms.Widget.attrs

saving multiple data like checkbox at once in django

I am working in ang django project onlinevoting. In my template I use
looping to loop all the positions and also the candidates. I have trouble in saving many data at once in one attribute for example in my model I have:
class Vote(models.Model):
candidate_id = models.ForeignKey('Candidate', blank=True, null=True)
election_id = models.ForeignKey('Election', blank=True, null=True)
user_id = models.ForeignKey('User', blank=True, null=True)
def __str__(self):
return "%s %s" % (user_id.first_name, election_id.year)
and in my template vote.html:
<form method="POST" class="form-horizontal" role="form">
{% if success %}
<div class="alert alert-success">
×
<strong>Success!</strong> {{ success }}
</div>
{% endif %}
{% if exist %}
<div class="alert alert-warning">
×
<strong>Warning!</strong> {{ exist }}
</div>
{% endif %}
{% csrf_token %}
<div class="form-group ">
{% for position in positions %}
<label for="cname" class="control-label col-lg-2">{{ position }}<span class="required">*</span></label>
{% for candidate in candidates %}
{% if position.pk == candidate.position_id.pk %}
<div class="col-lg-3">
<input type="checkbox" name="candidate_id" value="{{ candidate.pk }}">{{ candidate }}<br>
</div>
{% endif %}
{% endfor %}
</div>
{% endfor %}
<button class="btn btn-primary" type="submit">Save</button>
<button class="btn btn-default" type="button">Cancel</button>
</div>
</div>
</form>
How can I add/save all the candidates? because the user can select many candidates and I want to save them at once. This is my views.py
def vote(request):
if request.user.is_authenticated and request.user.is_admin:
candidates = Candidate.objects.all()
election = Election.objects.all().filter(is_active=True)
positions = Position.objects.all()
user = get_object_or_404(User, pk=request.user.pk)
try:
if request.method == 'POST':
candidate_id = request.POST['candidate_id']
vote = Vote.objects.create(candidate_id=candidate_id)
vote.save()
vote.election_id = election
vote.save()
vote.user_id = user
vote.save()
else:
form = VoteForm()
return render(request,'system/vote.html', {'form':form, 'candidates': candidates,
'election': election, 'user': user,
'positions': positions})
except:
exist = "ERROR!"
form = VoteForm()
return render(request,'system/vote.html', {'form':form, 'exist': exist})
elif not request.user.is_authenticated:
return redirect('system.views.user_login')

Django Class Based View Form Won't Save Data To Database

I can not get my form data to commit to my sqlite3 database. I don't see any errors. I can commit data through admin, but not through my own controller using form. I've tried many diff. combos and still no success. I would like to use class based view, please. Everything works, the form just won't save the data to database. There are no errors.
url: url(r'^create/$', CreateRequest.as_view())
forms.py:
class CreateForm(ModelForm):
date_due = forms.DateTimeField(widget=widgets.AdminSplitDateTime)
class Meta:
model = Request
fields = ['region', 'user_assigned', 'user_requester', 'description']
views.py:
class CreateRequest(LoginRequiredMixin, CreateView):
model = Request
fields = ['region', 'user_assigned', 'user_requester', 'date_due', 'description']
template_name = "requests_app/createRequest.html"
form_class = CreateForm
success_url = '/'
def form_valid(self, form):
objects = form.save()
return super(CreateRequest, self).form_valid(form)
models.py:
class Request(models.Model):
region = models.ForeignKey(Region)
completed = models.BooleanField(default=False)
user_assigned = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True, related_name='user_assigned')
user_requester = models.ForeignKey(settings.AUTH_USER_MODEL, related_name='user_requester')
date_due = models.DateTimeField()
date_completed = models.DateTimeField(null=True, blank=True)
description = models.CharField(max_length=500)
objects = models.Manager()
open_requests = OpenRequests()
completed_requests = CompletedRequests()
def mark_completed(self):
if not self.completed:
self.completed = True
self.date_completed = datetime.datetime.now()
index.html:
<h1>hi</h1>
<form action="/create/" method="post">
{% csrf_token %}
{{ form.non_field_errors }}
<div class="fieldWrapper">
{{ form.region.errors }}
<label for="id_region">Region</label>
{{ form.region }}
</div>
<div class="fieldWrapper">
{{ form.user_assigned.errors }}
<label for="id_user_assigned">User Assigned</label>
{{ form.user_assigned }}
</div>
<div class="fieldWrapper">
{{ form.user_requester.errors }}
<label for="id_user_requester">user_requester: </label>
{{ form.user_requester }}
</div>
<div class="fieldWrapper">
<p> {{ form.date_due.errors.as_text }} </p>
<label for="id_date_due">Due Date</label>
{{ form.date_due }}
</div>
<div class="fieldWrapper">
{{ form.description.errors }}
<label for="id_description">Descr.</label>
{{ form.description }}
</div>
<p><input type="submit" value="Submit Request" /></p>
{% if form.non_field_errors %}
{% for err in form%}
<div class="fieldWrapper">
<p class="form-error">{{ err }}</p>
<p class="form-error">{{ err.label_tag }} {{ field }}</p>
</div>
{% endfor %}
{% endif %}
</form>
{% endblock %}
in views.py you don't need this line: objects = form.save()
It can be
class ContaktCreateView(CreateView):
model = Contakt
form_class = ContaktForm
template_name = "www/www_contakt.html"
success_url = '/thanks/'
def form_valid(self, form):
return super(ContaktCreateView, self).form_valid(form)
Also I'm not using action in form action="/create/" method="post"
You are calling this html form via your line in urls.py:
url(r'^create/$', CreateRequest.as_view())
which is using your CreateRequest view which is using your index.html form file.

Categories