save() prohibited to prevent data loss due to unsaved related object 'user' - django

i am trying to save data in a table when a user click the checkout button of add to cart but it is showing me the above mention error i am unable to understand and one more thing is happening when i logout my the cart which i saved also got erased is it shomehow related to that i don't know
here is my views.py for checkout button
class Checkout(View):
def post (self, request,):
user = request.session.get('user')
ids = (list(request.session.get('cart').keys()))
sections = Section.get_sections_by_id(ids)
for section in sections:
order = Order(user = User(id=user),
section = section,
price = section.price,
)
order.save()
my views.py for cart.html
class Cart(View):
def get (self, request):
ids = (list(request.session.get('cart').keys()))
sections = Section.get_sections_by_id(ids)
print(sections)
return render(request, 'cart.html', {'sections': sections})
my urls.py
urlpatterns = [
path('cart/', Cart.as_view(),name='cart'),
path('Check-Out/', Checkout.as_view(),name='checkout'),
]
my cart.html
{% extends 'base.html' %}
{% load static %}
{% load cart %}
{% load custom %}
{% block head %}
<link rel="stylesheet" href="{% static 'css/cart.css' %}">
{% endblock %}
{% block content %}
<div class="container jumbotron">
<section>
<h1>My cart</h1>
<table class="table">
<thead>
<tr>
<th scope="col">S.no</th>
<th scope="col">Subject</th>
<th scope="col">Section</th>
<th scope="col">Teacher</th>
<th scope="col">Duration</th>
<th scope="col">Price</th>
</tr>
</thead>
{% for section in sections%}
<tbody style="margin-bottom: 20px;">
<tr>
<th scope="row">{{forloop.counter}}</th>
<td>{{section.subject.name}}</td>
<td>{{section.title}}</td>
<td>{{section.teacher}}</td>
<td>{{section.content_duration}}</td>
<td>{{section.price|currency}}</td>
</tr>
</tbody>
{% endfor %}
<tfoot>
<tr>
<th> Total</th>
<th></th>
<th></th>
<th></th>
<th></th>
<th>{{sections|total_price:request.session.cart|currency}}</th>
</tr>
<hr>
</tfoot>
</table>
<button type="button" data-toggle="modal" data-target="#exampleModal" style="float: right; margin-left:5px" class="btn btn-outline-primary">Check Out</button>
<button type="button" style="float: right; margin-left:5px" class="btn btn-info">Back To Site</button>
</tfoot>
</section>
</div>
<!-- Modal -->
<div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title" id="exampleModalLabel">Please Verify</h5>
<input type="button"class="btn-close btn-link" style="text-decoration:none; border:none; font-size:20px;" data-dismiss="modal" aria-label="Close" value="X">
</div>
<div class="modal-body">
<form action="{% url 'transactions:checkout' %}" method="Post">
{% csrf_token %}
<input type="submit" class="btn float-right btn-primary" value='Go Ahead'>
</form>
</div>
</div>
</div>
</div>
{% endblock %}
and my models.py
class Order(models.Model):
user = models.ForeignKey(User, on_delete=models.CASCADE,)
section = models.ForeignKey(Section, on_delete=models.CASCADE )
price = models.FloatField(blank=False)
update_at = models.DateTimeField(auto_now=True, editable=False)
def placeorder(self):
self.save()
please help if you can an

The issue caused by this line:
order = Order(user = User(id=user)
Using User(id=user) means you want to create an unsaved User and use it in an unsaved Order and then saving the order, but this will not work because you haven't saved the User yet, as mentioned by the error.
You can just simply just use the existing user in the order like this:
order = Order(user=user, section=section, price=section.price)
order.save()

Related

Django - Deleting using modal: show and delete only the first item from the table

Please help me understand the problem. I try to use the modal to delete each line separately but instead of displaying and deleting my actual line, it always displays and deletes the first line in the table. Where am I wrong with the code? Below my settings. Thank you very much.
models.py
class Post(models.Model):
class DisplayOnlyPublicat(models.Manager):
def get_queryset(self):
return super().get_queryset() .filter(status='publicat')
options =(
('draft', 'nepublicat'),
('publicat', 'publicat')
)
title = models.CharField(max_length=250)
poster = models.ImageField ( upload_to ='posts/', default='posts/poster_articole_pp.jpg')
category = models.ForeignKey(Category, on_delete=models.SET_DEFAULT, default=1)
slug = models.SlugField(max_length=250, unique_for_date='publish')
publish = models.DateTimeField(default=timezone.now)
author = models.ForeignKey (User, null=True, on_delete=models.SET_NULL, related_name='profipedia_posts')
short_content = models.TextField(null=True)
# content = models.TextField()
# content = RichTextField()
content = RichTextUploadingField(external_plugin_resources=[( 'emojione', '/static/vendor/ckeditor_plugins/emojione/' , 'plugin.js', )],)
status = models.CharField(max_length=10, choices=options, default='draft')
id = models.UUIDField(default=uuid.uuid4, unique=True, primary_key=True, editable=False)
objects = models.Manager() #denumire initiala
dop = DisplayOnlyPublicat() # denumire custom
def get_absolute_url(self):
return reverse('posts:articol', args=[self.slug])
# sa deschida articolul pe baza de denumire(slug) din sectiunea admin indiferent de statusul articolului (publicat/nepublicat)
# def get_absolute_url_adm(self):
# return reverse('posts:articolAdm', args=[self.slug])
class Meta:
ordering = ('-publish',)
def __str__(self):
return self.title
views.py
def delete_articol(request, articol_id):
post = Post.objects.get(pk=articol_id)
post.delete()
messages.success(request, "Articolul a fost sters!")
return redirect('posts:articoleAdm')
urls.py
urlpatterns = [
path('', views.articole, name='articole'),
path('articole-admin/', views.articoleAdm, name='articoleAdm'),
path('<slug:post>/', views.articol, name='articol'),
path('articole-admin/creare-articol/', views.creareArticol, name='creareArticol'),
path('articole-admin/<pk>/', views.articolAdm, name='articolAdm'),
path('modificare-articol/<str:pk>/', views.modificareArticol, name='modificareArticol'),
path('sterge-articol/<articol_id>/', views.delete_articol, name='stergeArticol'),
path('filtru/<category>', views.CatListView.as_view(), name='categorieArticol'),
]
html template
<table class="data-table data-table-pagination data-table-standard responsive nowrap hover"
id="datatableHover" data-order='[[ 0, "desc" ]]'>
<thead>
<tr>
<th class="text-muted text-small text-uppercase">Poster</th>
<th class="text-muted text-small text-uppercase">Autor</th>
<th class="text-muted text-small text-uppercase">Titlu</th>
<th class="text-muted text-small text-uppercase">Status</th>
<th class="text-muted text-small text-uppercase">Categorie</th>
<th class="text-muted text-small text-uppercase">Data</th>
<th class="empty"> </th>
<th class="empty"> </th>
<th class="empty"> </th>
</tr>
</thead>
<tbody>
{% for post in posts %}
<tr>
<td class="p-1"><img width="100" height="100%" class="rounded" src="{{post.poster.url}}"
alt=""></td>
<td>{{post.author}}</td>
<td><a class="list-item-heading body" href="{{post.id}}">{{post.title}}</a></td>
{% if post.status == "draft" %}
<td><span class="badge rounded-pill bg-muted">{{post.status}}</span></td>
{% else %}
<td><span class="badge bg-outline-success">{{post.status}}</span></td>
{% endif %}
{% if post.category.name == "nealocata" %}
<td><span class="badge rounded-pill bg-muted">{{ post.category }}</span></td>
{% else %}
<td><span class="badge bg-outline-muted">{{ post.category }}</span></td>
{% endif %}
<td> <small>{{post.publish|date:"d.m.Y - H:m:s"}}</small></td>
<td> <button class="btn btn-icon btn-icon-only btn-foreground-alternate edit-datatable " data-bs-toggle="tooltip" data-bs-placement="top" title="modificare articol" type="button" data-bs-delay="0"><i data-acorn-icon="eye"></i></button></td>
<td> <button class="btn btn-icon btn-icon-only btn-foreground-alternate edit-datatable " data-bs-toggle="tooltip" data-bs-placement="top" title="modificare articol" type="button" data-bs-delay="0"><i data-acorn-icon="edit"></i></button></td>
<td><button type="button" class="btn btn-icon btn-icon-only btn-foreground-alternate" data-bs-toggle="modal" data-bs-target="#deletePostPPP"><i data-acorn-icon="bin"></i></button></td>
</tr>
<!-- delete modal-->
<div class="modal fade" id="deletePostPPP" tabindex="-1" role="dialog" aria-hidden="true">
<div class="modal-dialog">
<div class="modal-content">
<div class="modal-header">
<h5 class="modal-title">Modal title</h5>
<button type="button" class="btn-close" data-bs-dismiss="modal"
aria-label="Close"></button>
</div>
<div class="modal-body">Sigur vrei să ștergi articolul <br>
<strong>"{{post.title}}"</strong>?</div>
<div class="modal-footer">
<button type="button" class="btn btn-secondary"
data-bs-dismiss="modal">Close</button>
<a href="{% url 'posts:stergeArticol' post.id %}"><button type="submit"
class="btn btn-primary">Understood</button></a>
</div>
</div>
</div>
</div>
{% endfor %}
</tbody>
</table>
Your delete buttons all refer to the same modal. The issue is that all the modals you generate have the same id. When referring to that id, the first modal will be shown.
What you should do instead is give each modal a separate id, containing e.g. the post id. Then call that specific modal in your delete button.
Your delete button:
<td><button type="button" class="btn btn-icon btn-icon-only btn-foreground-alternate" data-bs-toggle="modal" data-bs-target="#deletePostPPP-{{post.id}}"><i data-acorn-icon="bin"></i></button></td>
Your modal:
<!-- delete modal -->
<div class="modal fade" id="deletePostPPP-{{post.id}}" tabindex="-1" role="dialog" aria-hidden="true">

Django passing the value of the form in Django-forms

I have 2 models WorkoutCategory and workout with a ForeignKey with workout_Category in catig
in my template i have a collapsed div "WorkoutCategory" include a collapse form "to save in workoutmodel
the question is how I should pass the catig_id if it's not included in the form
below screenshot to simplify my idea
collapsed div for woroutcategory and the form
models:
from django.db import models
# Create your models here.
class WorkoutCategory(models.Model):
name = models.CharField(max_length=100)
def __str__(self):
return self.name
class Workout(models.Model):
catig = models.ForeignKey(WorkoutCategory,null=True, on_delete=models.CASCADE)
workout_name = models.CharField(max_length=250)
video_link = models.CharField(max_length=300)
def __str__(self):
return self.workout_name
the Form:
from django.forms import *
from .models import *
from django import forms
class CreateWorkoutForm(ModelForm):
class Meta:
model = Workout
exclude = ['catig']
widgets = {
'workout_name' : forms.TextInput(attrs={'class':'form-control','placeholder':'Workout Name'}),
'video_link' : forms.URLInput(attrs={'class':'form-control','placeholder':'https://www.youtube.com/ ...'}),
}
the Template:
{% for catg in allcetgs %}
<br>
<div class="card-header" data-toggle="collapse" href="#multiCollapseExample{{catg.id}}" role="button" aria- expanded="false" aria-controls="multiCollapseExample{{catg.id}}">
{{catg.name}}</div>
<div class="row">
<div class="col">
<div class="collapse multi-collapse" id="multiCollapseExample{{catg.id}}">
<div class="col">
<br>
<div class="btn btn-success" data-toggle="collapse" href="#addingworkout{{catg.id}}" role="button" aria-expanded="false" aria-controls="addingworkout{{catg.id}}" style="float: right;">add workout</div>
<br> <br>
<div class="collapse multi-collapse" id="addingworkout{{catg.id}}" >
<form method="POST" action="">
{% csrf_token %}
<div class="form-row">
<div class="col">
{{workoutForm.workout_name}}
</div>
<div class="col">
{{workoutForm.video_link}}
</div>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>
</div>
<br>
<table class="table">
<thead>
<tr>
<th scope="col">Workout Name</th>
<th scope="col">Youtube Link</th>
</tr>
</thead>
<tbody>
{% for wkout in catg.workout_set.all %}
<tr>
<td>{{wkout.workout_name}}</td>
<td>check video</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
I don't want the user it set the catig_id since it's already the parent div of the form. how should I pass that catig_id value
# You don't need to exclude the catig field in your form
class CreateWorkoutForm(ModelForm):
class Meta:
model = Workout
widgets = {
'workout_name' : forms.TextInput(attrs={'class':'form-control','placeholder':'Workout Name'}),
'video_link' : forms.URLInput(attrs={'class':'form-control','placeholder':'https://www.youtube.com/ ...'}),
}
# you can have the value of catig_id in the hidden input
<div class="collapse multi-collapse" id="addingworkout{{catg.id}}" value="{{catg.id}}">
<form id="addingworkout">
<div class="form-row">
<input type="hidden" name="catig" value="{{catg.id}}">
<div class="col">
{{workoutForm.workout_name}}
</div>
<div class="col">
{{workoutForm.video_link}}
</div>
<button type="submit" class="btn btn-primary">Save</button>
</div>
</form>
</div>

Why is my Class-based delete view not working?

My delete view is not working and the error message is:
Page not found (404) Request Method: GET.
I am trying to delete my uploaded file based on its primary key and so far, my url is able to link me correctly based on the pk.
This is my urls.py:
path('post/<int:post_id>/lesson_delete/<int:lesson_id>', LessonDeleteView.as_view(), name='lesson_delete'),
My views.py:
class LessonDeleteView(DeleteView):
model = Lesson
success_url = '../'
template_name = 'lesson_confirm_delete.html'
This is the html template that brings user to the delete view:
{% extends "store/base.html" %}
{% block content %}
<div id="main">
<table class="table mb-0">
<thead>
<tr>
<th>Title</th>
<th>Author</th>
<th>Download</th>
<th>Delete</th>
</tr>
</thead>
<tbody>
{% for l in Lesson %}
<tr>
<td>
{% if l.file %}
{{ l.title }}
{% else %}
<h6>Not available</h6>
{% endif %}
</td>
<td>{{ l.post.author }}</td>
<td>{% if l.file %}
Download
{% else %}
<h6>Not available</h6>
{% endif %}
</td>
<td> <a class="btn btn-danger btn-sm mt-1 mb-1" href="{% url 'lesson_delete' lesson_id=l.id %}">Delete</a>
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
{% endblock %}
This is my html template for DeleteView:
{% extends "store/base.html" %}
{% block content %}
<div class="content-section" id="main">
<form method="POST">
{% csrf_token %}
<fieldset class="form-group">
<legend class="border-bottom mb-4">Delete Lesson</legend>
<h2>Are you sure you want to delete the post "{{object.title}}"?
</h2>
</fieldset>
<span style="display:inline;">
<button class="btn btn-outline-danger" type="submit">Yes, Delete!
</button>
<a class="btn btn-outline-secondary" href ="">Cancel</a>
</span>
</form>
</div>
{% endblock content %}
This is my Lesson Model:
class Lesson(models.Model):
title = models.CharField(max_length=100)
file = models.FileField(upload_to="lesson/pdf")
date_posted = models.DateTimeField(default=timezone.now)
post = models.ForeignKey(Post, on_delete=models.CASCADE, null=False, blank=False)
def __str__(self):
return self.title
def get_absolute_url(self):
return reverse('lesson_upload', kwargs={'pk': self.pk})
Is you template called 'lesson_confirm_delete.html'?
Also, for your success url, I have feeling you don't have a path '../'. It should the specific path you want it to go to.
(Sorry, I can't comment yet.)

How to create such a table with checkbox in django?

I want to have a table with a checkbox on each row with Django as shown in the image. My Django view.py, models.py and HTML file are mentioned below. How this can be done? Is there any built-in function in Django or what?
Table with check box
I have models file as:
class AppsDescription(db.Model):
aws_response = aws_list_conf_api_call()
CHOICES = [("yes", "YES"),
("no", "NO")]
OPTIONS = list()
for apps in aws_response:
OPTIONS.append(('{name1}'.format(name1=apps.lower()), '{name2}'.format(name2=apps)), )
name = db.CharField(max_length=256)
description = db.TextField()
plan_to_migrate = db.CharField(choices=CHOICES, max_length=256)
# app_names = MultiSelectField(choices=OPTIONS)
def __str__(self):
return self.name
My views.py as
def createapp(request):
# import ipdb; ipdb.set_trace()
form = DashboardForm()
if request.method == "POST":
form = DashboardForm(request.POST)
list_of_inputs = request.POST.getlist("inputs")
if form.is_valid:
form.save(commit=True)
return HttpResponseRedirect(reverse("aws:createapp"))
server = aws_server_list_conf()
return render(request, "createapp.html", {'server':server, 'form': form})
My html file as
<form method="POST">
{{form.as_p}}
<table>
<tr>
<th>Select</th>
<th>Agent ID</th>
<th>Configuration ID</th>
<th>Host Name</th>
<th>OS Name</th>
<th>OS Version</th>
<th>Source</th>
<th>Time of Creation</th>
<th>Type</th>
</tr>
{% for apps in server %}
<tr>
<td><input type="checkbox" name="" value=""></td>
{% for k,v in apps.items %}
<td>{{ v }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
{% csrf_token %}
<input type="submit" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" name="" value="submit">
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="alert alert-success alert-dismissible">
<a class="close" data-dismiss="modal" aria-label="close">×</a>
<strong>Success!</strong> App information stored Successfully.
</div>
</div>
</div>
</form>
I want to have a table with checkbox on each row with django as shown in the image.
Your HTML file needs to look like this:
<form method="POST">
{{form.as_p}}
<table>
<tr>
<th>Select</th>
<th>Agent ID</th>
<th>Configuration ID</th>
<th>Host Name</th>
<th>OS Name</th>
<th>OS Version</th>
<th>Source</th>
<th>Time of Creation</th>
<th>Type</th>
</tr>
{% for apps in server %}
<tr>
{% for k,v in apps.items %}
<td><input type="checkbox" name="selected_options" value="v.id"></td>
<td>{{ v }}</td>
{% endfor %}
</tr>
{% endfor %}
</table>
{% csrf_token %}
<input type="submit" class="btn btn-info btn-lg" data-toggle="modal" data-target="#myModal" name="" value="submit">
<div class="modal fade" id="myModal" role="dialog">
<div class="modal-dialog">
<div class="alert alert-success alert-dismissible">
<a class="close" data-dismiss="modal" aria-label="close">×</a>
<strong>Success!</strong> App information stored Successfully.
</div>
</div>
</div>
</form>

Taking Attendance in Django Python

I am trying to mark attendance. But I am not able to get the code. My submit should send the input to database for each student. Any suggestion for doing this in better way is welcome.
My models.py is as follows
It has Employee, Mentor and Student and below is the model where values can be changed.
class ClassName(models.Model):
class_name = models.CharField(max_length=20)
class_date=models.DateField(blank=True, null=True)
Mentor= models.ForeignKey(Mentor, related_name='class_mentor')
student = models.ManyToManyField(Student, related_name='class_student')
attendance = models.BooleanField(default=True)
def __str__(self):
return str(self.class_name)
Views.py : This is just to display the markattendance page. I am not able to figure out how to get the value and Post the value to database. Right now, I am fetching Students value from the Students table. I think I should be creating Classname Form and and display students. I was getting Internal server error.
def markattendance(request):
students = Student.objects.all()
return render(request, 'home/markattendance.html',
{'students': students})
markattendance.html : On clicking submit, the attendance should be marked.
{% extends 'home/index.html' %}
{% block content %}
<div class="container-fluid">
<div>
<div class="card-body">
<div class="table-responsive">
<table class="table table-bordered" id="dataTable" width="100%" cellspacing="0">
<thead>
<tr>
<th>Name</th>
<th>Class</th>
<th>Attendance</th>
</tr>
</thead>
<tbody>
{% for students in students %}
{% ifequal students.Men_name|stringformat:"s" user.username %}
<tr>
<td>{{ students.Student_name }}</td>
<td>{{ students.Student_Class }}</td>
<td>
<label class="switch">
<input id="toggle-slider_position()" type="checkbox">
<span class="slider round"></span>
</label>
</td>
</tr>
{% endifequal %}
{% endfor %}
</tbody>
</table>
</div>
<br/>
<div class="row" >
<div class="col-sm-4"></div>
<div class='col-sm-4' align="center">
<div class="form-group">
<div class='input-group date' id='datetimepicker1'>
<input type='text' class="form-control" />
<span class="input-group-addon">
<span class="glyphicon glyphicon-calendar"></span>
</span>
</div>
</div>
<button class="btn btn-lg">Submit</button>
</div>
<div class="col-sm-4">
</div>
</div>
<br/><br/><br/><br/><br/>
</div>
</div>
</div>
{% endblock %}
Please help me out. Any suggestion is welcome.