How to i update a certain value in the database?
class Userdata(models.Model):
user = models.OneToOneField(User, on_delete= models.CASCADE)
faculty = models.ForeignKey(Fakultas,on_delete=models.CASCADE,default= 1)
is_voted = models.BooleanField(default=False)
def __str__(self):return self.user.username
class Voting(models.Model):
name = models.CharField(max_length=50)
faculty = models.ForeignKey(Fakultas, on_delete=models.CASCADE, default=1)
pic = models.CharField(max_length=50)
text = models.TextField()
voters = models.IntegerField()
def __str__(self): return self.name
My Views :
def voted(response):
if response.method == 'POST':
id = response.POST.get['idcalon']
user = Userdata.objects.get() #get the username
calon2 = Voting.objects.get() #get user selection in html
user.is_voted = True
calon2.voters +=1
user.save(['is_voted'])
calon2.save(['voters'])
I'm trying to grab the user's name and then when update the user's is_voted value to True when triggered.
Then, I wanted to grab my Voting model by id, for example, I wanted to edit id = 1
So how do I do it? I've been trying to understand the documentation, but still have 0 idea how to do it.
Thank you
def voted(request):
if request.method == 'POST':
id = request.POST.get['idcalon']
user = Userdata.objects.get(id=request.user.id) #get the username
calon2 = Voting.objects.get(id=id) #get user selection in html
user.is_voted = True
calon2.voters +=1
user.save()
calon2.save()
this will work if user is authenticated
Related
This is a single-page website that is kinda ecommerce site. I just want to count a single user how many products are ordered. How can I count?
index view:
def index(request):
total_user = User.objects.count()-1
total_orders =Frontend_Order.objects.count()
context = {
"total_user":total_user,
"total_orders":total_orders
}
return render(request,'0_index.html',context)
frontend_view:
def frontend_orders(request):
if request.user.is_authenticated:
if request.method == "POST":
frontend_orders_request = request.FILES['frontend_file'] if 'frontend_file' in request.FILES else None
sections = request.POST.get('numField11')
functionality = request.POST.get('frontend')
if functionality == "Portfolio":
price = int(sections)*10
elif (functionality == "e-Commerce") or (functionality == "social-media"):
price = int(sections)*15
Frontend_Order.objects.create(
files = frontend_orders_request,
Number_of_Section = sections,
Website_Functionality = functionality,
Price = price, USer = request.user,
Email = request.user.email
)
messages.success(request,f"{request.user.first_name}, Your order is procecing. I'll cotact you before placing the order.")
return redirect("/", userz = request.user)
else:
messages.error(request,"Please login or create an account.")
return redirect("/")
Frontend Order Model:
class Frontend_Order(models.Model):
USer = models.CharField(max_length=50, null=True)
Price = models.CharField(max_length=250, null=True)
Number_of_Section = models.CharField(max_length=250, null=True)
Website_Functionality = models.CharField(max_length=1, null=True)
Email = models.EmailField(max_length=50, null=True)
files = models.FileField(upload_to="new_file/", null=True, blank=True)
def __str__(self):
return str(self.pk)+ str(".") + str(self.USer)
Yes, it's possible. You can get the current user from the request object and use the filter method, like so:
def index(request):
total_user = User.objects.count()-1
total_orders =Frontend_Order.objects.filter(user=request.user).count()
context = {
"total_user":total_user,
"total_orders":total_orders
}
return render(request,'0_index.html',context)
However, this will only work if you connect your users to your orders, with a foreign key, instead of a CharField:
class Frontend_Order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE)
# etc...
You should use Frontend_Order.objects.filter(USer=userid) (or Frontend_Order.objects.filter(USer.id=userid) if it didn't worked) to get user orders by it's user id and then, use a for loop and a counter variable to iterate on filtered orders and add their products count to the counter.
It is better to reconsider your chosen names.
So i'm working on job application portal.
the logic is as follows :
Applicant ---> Applies for ---> Job
Models are (Job, User, Application)
I used the User model from django and i extend it.
Now the dilemma is when i render the ApplicationForm, because i have to update the foreign key and i want it to be updated automatically.
Here is my code :
Models.py
class Job(models.Model):
owner = models.ForeignKey(User,related_name='job_owner',on_delete=models.CASCADE)
title = models.CharField(max_length=100)
#location
job_type = models.CharField(max_length=15,choices=JOB_TYPE)
description= models.TextField(max_length=1000)
published_at = models.DateTimeField(auto_now=True)
vacancy = models.IntegerField(default=1)
salary = models.IntegerField(default=0)
experience = models.IntegerField(default=1)
category = models.ForeignKey('Category',on_delete=models.CASCADE)
icon = models.ImageField(upload_to ='job_icons/',default='job_icons/job.png')
slug = models.SlugField(blank = True,null=True)
class Application(models.Model):
job = models.ForeignKey(Job, related_name="job_applied",on_delete=models.CASCADE)
applicant = models.ForeignKey(User,related_name='job_applicant',on_delete=models.CASCADE)
first_name= models.CharField(max_length=40)
last_name= models.CharField(max_length=40)
email = models.EmailField(max_length=60)
website = models.URLField()
cv = models.FileField(upload_to='application/')
coverletter = models.TextField(max_length=550)
application_date = models.DateTimeField(auto_now=True)
def __str__(self):
return self.last_name+"\t"+self.first_name
Forms.py
class JobApplication(ModelForm):
class Meta:
model = Application
fields = ['first_name', 'last_name','email', 'website','cv','coverletter']
vews.py
def job_detail(request,slug):
job_specific = Job.objects.get(slug=slug)
form = JobApplication(instance=request.user)
if request.method == 'POST':
form = JobApplication(request.POST,request.FILES)
if form.is_valid():
my_form = form.save(commit=False)
my_form.job = job_specific
Application.applicant.user = request.user
Application.job = job_specific
my_form.save()
context ={'job_specific':job_specific, 'form':form,}
return render(request,"job/job_details.html",context)
So once the user submit their application, i wanted to updated the fields that are "foreign key" without prompting the user.
I do not know how to arrange this in the views.py or if it's even possible this way?
thanks to everyone in advance
So i solved the problem, it was really simple solution:
my_form = form.save(commit=False)
my_form.job = job_specific
my_form.applicant = request.user
I want to update user model in a views.py. Is there a way to do that? What I want to do is minus user point in views.py and update into models without a form. but it gave me " 'int' object has no attribute 'save'"
views.py
def buy_item(request, item_name):
item = ShopItem.objects.get(item_name=item_name)
price = item.item_price
user = request.user
user_point = user.point
if user_point >= price:
user_point = user_point - price
point_left = user_point
point_left.save()
msg = messages.success(request, 'You bought item!')
return redirect('/shop', msg)
else:
msg = messages.success(request, 'You do not have enough point')
context = ({
'point': user_point,
'item': item,
'form': form
})
return render(request, 'item.html', context)
item models.py
class ShopItem(models.Model):
item_name = models.CharField(max_length=16)
item_image = models.ImageField(upload_to='media_items')
item_description = models.CharField(max_length=255)
item_command = models.CharField(max_length=255)
item_price = models.IntegerField(default=0)
def __str__(self):
return self.item_name
def snippet(self):
return self.item_description[:45]
user models.py
class UserProfile(AbstractUser):
username = models.CharField(max_length=16, unique=True)
email = models.EmailField(default='', unique=True)
phone = models.CharField(max_length=10)
point = models.IntegerField(default=0)
password1 = models.CharField(max_length=255)
password2 = models.CharField(max_length=255)
USERNAME_FIELD = 'username'
What I want is to save the point after changed.
What should I do? Please help! I'm really new to this. Sorry for my English.
Sadly, I don't have enough reputation to make a comment, but you need to use save() method in a model, not in an Integer.
So, you should replace
point_left = user_point
point_left.save()
for this
user.point = user_point # Assign the new point to the user
user.save() # Update your user model
I want to be able to have a user update two models with one submit button. The first model will house all of the book titles (unique) and pages that users submit. The other will show which users submitted which books.
Ideally, I'd like to do something like this:
if request.method == "POST":
form = AddBookForm(request.POST)
if form.is_valid():
books = form.save(commit=False)
ub = UserBooks()
books.book_title = form.cleaned_data['book_title']
books.book_total_pages = form.cleaned_data['book_total_pages']
ub.user = request.user
ub.book_title = form.cleaned_data['book_title']
ub.save()
books.save()
return redirect('new_book')
But that's giving me the error:
Cannot assign "'Some Book Title'": "UserBooks.book_title" must be a
"Books" instance.
What would be the best way to update two models with one form?
Here are the other files.
models.py
class Books(models.Model):
created = models.DateTimeField(auto_now_add=True, editable=False)
last_updated = models.DateTimeField(auto_now=True, editable=False)
book_title = models.CharField(max_length=100, unique=True)
book_total_pages = models.IntegerField()
class Meta:
ordering = ('-created',)
def __str__(self):
return '{0}'.format(self.book_title)
class UserBooks(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE, null=False, blank=False)
book_title = models.ForeignKey(Books, on_delete=models.CASCADE, null=False, blank=False)
views.py
def new_book(request):
user = request.user
if request.method == "POST":
form = AddBookForm(request.POST)
if form.is_valid():
books = form.save(commit=False)
books.book_title = form.cleaned_data['book_title']
books.book_total_pages = form.cleaned_data['book_total_pages']
books.save()
return redirect('new_book')
else:
form = AddBookForm()
return render(request, 'main/addanewbook.html', {
'form': form,
'allBooks': allBooks,
'userbooks': userbooks,
})
forms.py
class AddBookForm(forms.ModelForm):
class Meta:
model = Books
fields = ('book_title', 'book_total_pages')
you need to change a bit in the view
if form.is_valid():
books = form.save(commit=False)
ub = UserBooks()
books.book_title = form.cleaned_data['book_title']
books.book_total_pages = form.cleaned_data['book_total_pages']
books = books.save()
ub.user = request.user
ub.book_title = books
ub.save()
return redirect('new_book')
this will do it
My app is a shopping cart. I have a function in views.py that is triggered when someone adds an item to the cart. The function checks if the user has an active order (one that is in the cart but hasn't been paid for).
But the code fails at `user_order, status = Order.objects.get_or_create(owner=user_profile, is_ordered=False)
#login_required()
def add_to_cart(request, **kwargs):
#get the user profile
user_profile = get_object_or_404(UserProfile, user=request.user)
#filter products by id
producto = Producto.objects.filter(id=kwargs.get("pk", "")).first()
#create OrderItem, of the selected product
order_item, status = OrderItem.objects.get_or_create(producto=producto)
if status == False: #adds one to the order_item
order_item.quantity += 1
order_item.save()
print(order_item.quantity)
#create order associated with the user
user_order, status = Order.objects.get_or_create(owner=user_profile, is_ordered=False)
user_order.items.add(order_item)
#print(user_order.items.all()) #queries the items
#print(user_order)
#date is not beign added
# generate a reference code
user_order.ref_code =random.randint(0,100000)
user_order.save()
return HttpResponseRedirect(request.META.get('HTTP_REFERER'))
Relevant models:
class Order(models.Model):
fecha_reparto = models.OneToOneField(DiasDeReparto, on_delete=models.CASCADE, default= 1)
order_nodo = models.OneToOneField(Nodo, on_delete=models.CASCADE, default= 1)
ref_code = models.CharField(max_length=15)
owner = models.ForeignKey(UserProfile, on_delete=models.CASCADE)
is_ordered = models.BooleanField(default=False)
items = models.ManyToManyField(OrderItem)
date_ordered = models.DateTimeField(null=True)
def get_cart_items(self):
return self.items.all()
def get_cart_total(self):
return sum([item.producto.precio * item.quantity for item in self.items.all()])
def __str__(self):
return self.ref_code
class UserProfile(models.Model):
user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
class OrderItem(models.Model):
producto = models.OneToOneField(Producto, on_delete=models.SET_NULL, null = True)
quantity = models.IntegerField(default=1)
is_ordered = models.BooleanField(default=False)
date_added = models.DateTimeField(auto_now = True)
date_ordered = models.DateTimeField(null=True)
def __str__(self):
return self.producto.nombre
The problem can be solved with something like this:
try:
Order.objects.get(owner=user_profile)
except:
Order.objects.create(fecha_reparto=dia_reparto[0], order_nodo=nodo[0], ref_code="asdas", owner=user_profile, is_ordered=False, date_ordered=datetime.datetime.now())
But I don't get why get_or_create doesn't work
On your Order model you have a few related model fields and in the get_or_create you are not specifying any defaults. The get or create needs the required values to input if creating and you have a few related fields which are required. That will also explain why the try and except works because you add the fields when creating in the except.
defaults = {fecha_reparto: dia_reparto[0], order_nodo: nodo[0]......}
user_order, status = Order.objects.get_or_create(owner=user_profile, is_ordered=False, defaults=defaults)
Use id instead model instace in this line:
user_order, status = Order.objects.get_or_create(owner=user_profile, is_ordered=False)
So it should look like this:
user_order, status = Order.objects.get_or_create(owner_id=user_profile.pk, is_ordered=False)
It worked for me with similar problem.