Error when Django form try tu update data - django-models

I am very new in django.
Situation is like this
I have a model
class Slotmodels (models.Model):
modelid = models.AutoField(primary_key=True)
model_desc = models.TextField()
categoryid = models.ForeignKey(categories, on_delete=models.CASCADE)
shopid = models.ForeignKey(shops, on_delete=models.CASCADE)
brandid = models.ForeignKey(brands, on_delete=models.CASCADE)
reference = models.CharField(max_length=50,null=True)
history = models.TextField(null=True)
year = models.IntegerField(null=True)
purchase_price = models.FloatField(default=0)
actual_price = models.FloatField(default=0)
limited_edition = models.BooleanField(null=False,default=False)
color = models.CharField(max_length=50,null=True)
number = models.IntegerField(null=True)
livery = models.CharField(max_length=50,null=True)
sponsor = models.CharField(max_length=50,null=True)
scale = models.CharField(max_length=10,null=True)
engine = models.CharField(max_length=20,null=True)
eng_position = models.CharField(max_length=20,null=True)
crown = models.IntegerField(null=True)
pinion = models.IntegerField(null=True)
crown_bnd = models.CharField(max_length=20,null=True)
pinion_bnd = models.CharField(max_length=20,null=True)
active = models.BooleanField(default=True)
chasis = models.CharField(max_length=20,null=True)
rear_axis = models.CharField(max_length=30,null=True)
front_axis = models.CharField(max_length=30,null=True)
front_tire_diam = models.IntegerField(null=True)
rear_tire_diam = models.IntegerField(null=True)
front_tire_width = models.IntegerField(null=True)
rear_tire_width = models.IntegerField(null=True)
collection_desc = models.CharField(max_length=30,null=True)
bench_desc = models.CharField(max_length=30,null=True)
Total_weight = models.IntegerField(null=True)
def __str__(self):
return self.modelid, self.model_desc
With a form based on that model:
class FormAltaSlotModel(ModelForm):
class Meta:
model = Slotmodels
fields = ['modelid','model_desc','categoryid','shopid','brandid','reference','history','year','purchase_price',
'actual_price','limited_edition','color','number','livery','sponsor','scale','engine','eng_position',
'crown','pinion','crown_bnd','pinion_bnd','active','chasis','rear_axis','front_axis','front_tire_diam',
'rear_tire_diam','front_tire_width','rear_tire_width','collection_desc','bench_desc','Total_weight']
help_texts = {
}
widgets = {
'history': Textarea(attrs={'cols': 30, 'rows': 2}),
'model_desc': Textarea(attrs={'cols': 30, 'rows': 2})
}
When I instance the form to create a record, is everything ok!. It is important to say that I have three foreignkey fields so when I render the form , the list values of the model referenced appear in the screen. And, the values are recorded properly (in the related Id fields).
The point is when I tried to update a record previously recorded. In the screen appear the descriptions and the list is not appearing, then the values that are passed to the form are descriptions instead of the codes, so the message "Select a valid choice. That choice is not one of the available choices.", appear for the three foreignkey fields that are 'categoryid','shopid','brandid'.
I have tried to fix it, but with no success. Thanks in advance!

Here I tried to do full CRUD with your MODEL & MODELFORM
view.py
def InsertData(request):
my_data = Slotmodels.objects.all() # Show data of Student Table
if request.method == 'POST':
form = FormAltaSlotModel(request.POST,request.FILES)
if form.is_valid():
form.save()
messages.success(request,'Student Successfully Inserted')
return redirect('/')
else:
form = FormAltaSlotModel()
context= {'form':form,'my_data':my_data}
return render(request,'home.html',context)
def UpdateData(request,modelid):
my_data = Slotmodels.objects.all() # Show data of Student Table
set_student = Slotmodels.objects.get(modelid=modelid)
if request.method == 'POST':
form = FormAltaSlotModel(request.POST,request.FILES,instance=set_student)
if form.is_valid():
form.save()
messages.success(request,'Student Successfully Updated')
return redirect('/')
else:
form = FormAltaSlotModel(instance=set_student)
context= {'form':form,'my_data':my_data}
return render(request,'home.html',context)
def DeleteData(request,modelid):
set_student = Slotmodels.objects.get(modelid=modelid)
set_student.delete()
messages.success(request,'Student Successfully Deleted')
return redirect('/')
urls.py
urlpatterns = [
path('', InsertData,name='insert_data'),
path('up/<int:modelid>/', UpdateData,name='update_data'),
path('del//<int:modelid>/', DeleteData,name='delete_data'),
]
HTML Code
<div class="container my-5">
<div class="row">
<div class="col-12">
<form action="" method="POST">
{% csrf_token %}
{{form.as_p}}
<button type="submit">Add</button>
</form>
</div>
<div class="col-12">
<table class="table">
<thead>
<tr>
<th scope="col">No.</th>
<th scope="col">Categories</th>
<th scope="col">Shops</th>
<th scope="col">Brands</th>
<th scope="col">Actions</th>
</tr>
</thead>
<tbody>
{% for i in my_data %}
<tr>
<td>{{forloop.counter}}</td>
<td>{{i.categoryid}}</td>
<td>{{i.shopid}}</td>
<td>{{i.brandid}}</td>
<td>
Update
Delete
</td>
</tr>
{% endfor %}
</tbody>
</table>
</div>
</div>
</div>
Output

Related

If and else Statement in Boolean Field

my question seems tricky to me, but i'm certain someone could derive a solution to it. i've a boolean field, but i want to add a functionality in which when the boolean is been clicked (True), i could implement an {% if %} and {% else %} which could be, add a particular amount to the original amount, if the boolean field is True. my code is below for proper understanding...
class OrderItem(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
ordered = models.BooleanField(default=False)
item = models.ForeignKey(Item, on_delete=models.CASCADE)
paper = models.BooleanField(default=False, blank=True)
def get_final_price(self):
if self.item.discount_price:
return self.get_total_discount_price()
return self.get_total_item_price()
def coverframe(self):
return get_final_price() + 3000
class Order(models.Model):
user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE)
item = models.ManyToManyField(OrderItem)
def __str__(self):
return self.user.username
def get_total_everything(self):
total = 0
for order_item in self.item.all():
total += order_item.get_final_price()
return total
def get_total_everything_cover_paper(self):
total = 0
for order_item in self.item.all():
total += order_item.coverframe()
return total
Views
class OrderSummary(LoginRequiredMixin, View):
def get(self, *args, **kwargs):
try:
******
context = {'object':order}
??????
except ObjectDoesNotExist:
messages.error(self.request, "No active order yet, sorry!!!")
return redirect('/')
and my html
{% if object.item.paper_frame %}
<tr>
<td><b>{{object.get_total_everything_cover_paper}}</b></td>
</tr>
<tr>
{% else %}
{% if object.get_total_everything %}
<tr>
<td><b>N {{object.get_total_everything}}</b></td>
</tr>
<tr>
{% endif %}
{% endif %}

How can I show all this images in a carousel

I know beginners can ask stupid questions but that is the way trough all it.
Is it possible that i can list all this images in a carousel? or image gallery. How can i list this images easiest?
What would you suggest?
I don't want to use foreignkey because I cannot (I couldn't yet understand the save process in the views) save a separate model in a view.
Thanks a lot
class MyFamily(models.Model):
author = models.ForeignKey(Profile, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True)
update = models.DateField(auto_now=True)
title = models.CharField(max_length=100)
explanatipon = models.TextField(blank=True)
photo1 = models.ImageField(upload_to='posts/photos/')
photo2 = models.ImageField(upload_to='posts/photos/')
photo3 = models.ImageField(upload_to='posts/photos/')
photo4 = models.ImageField(upload_to='posts/photos/')
photo5 = models.ImageField(upload_to='posts/photos/')
active = models.BooleanField(default=True)
def __str__(self):
return str(self.title)[:30]
i tried to make it like #willem-van-onsem mentioned it but without success. I NEED HELP PLEASE
What did I do :
MODELS PROFILE:
class Profile(models.Model):
user = models.OneToOneField(User, on_delete=models.CASCADE)
bio = models.TextField()
updated = models.DateTimeField(auto_now=True)
created = models.DateTimeField(auto_now_add=True)
def __str__(self):
return str(self.user.username)
MODELS MYFAMILY:
class MyFamily(models.Model):
author = models.ForeignKey(Profile, on_delete=models.CASCADE)
date = models.DateField(auto_now_add=True)
update = models.DateField(auto_now=True)
title = models.CharField(max_length=100)
explanatipon = models.TextField(blank=True)
photo1 = models.ImageField(upload_to='posts/photos/')
photo2 = models.ImageField(upload_to='posts/photos/')
photo3 = models.ImageField(upload_to='posts/photos/')
photo4 = models.ImageField(upload_to='posts/photos/')
photo5 = models.ImageField(upload_to='posts/photos/')
active = models.BooleanField(default=True)
#property
def photos(self):
photos = [self.photo1, self.photo2, self.photo3, self.photo4, self.photo5]
return [photo for photo in photos if photo is not None]
def __str__(self):
return str(self.title)[:30]
VİEWS :
def photo(request):
myfamily = MyFamily.objects.filter(active=True)
context = {
'myfamily':myfamily
}
return render(request, 'posts/create-form.html')
You can return the photo's in a list:
class MyFamily(models.Model):
# …
#property
def photos(self):
photos = [self.photo1, self.photo2, self.photo3, self.photo4, self.photo5]
return [photo for photo in photos if photo is not None]
If you construct a view where you pass the MyFamily object as myfamily to the template render engine, we can generate HTML for a Bootstrap carousel:
<div id="carouselExampleSlidesOnly" class="carousel slide" data-ride="carousel">
<div class="carousel-inner">
{% for photo in myfamily.photos %}
<div class="carousel-item {% if forloop.first %}active{% endif %}">
<img class="d-block w-100" src="{{ photo.url }}" alt="First slide">
</div>
{% endfor %}
</div>
</div>
That being said, I think the modelling might be improved with an extra model. Right now one can only upload exactly five object. Normally one defines an extra model (MyFamilyPhoto) with a ForeignKey to the MyFamily in this case to allow to generate an arbitrary number of MyFamilyPhotos for each MyFamily. For an arbitrary MyFamily object, you will need to add a parameter to the url. In the view you can obtain the myfamily of the user with:
from django.contrib.auth.decorators import login_required
#login_required
def photo(request):
myfamily = MyFamily.objects.get(active=True, author__user=request.user)
context = {
'myfamily': myfamily
}
return render(request, 'posts/create-form.html')
Note: You can limit views to a view to authenticated users with the
#login_required decorator [Django-doc].

Getting table without any records

I'm new to Django REST and Angular JS, so I'm trying to understand the concepts behind them (and the integration between the two).
I'm making a REST API that should print a list of Classrooms and Students, and that's my work so far
models.py
class Classroom(models.Model):
school = models.ForeignKey(School, related_name='schools')
academic_year = models.CharField(max_length=9)
classroom = models.CharField(max_length=100)
floor = models.IntegerField(default=0)
class Meta:
unique_together = (('school', 'classroom', 'academic_year'),)
class Student(models.Model):
classroom = models.ForeignKey(Classroom, related_name='students')
first_name = models.CharField(max_length=40)
last_name = models.CharField(max_length=60)
GENDER_CHOICES = (
('M', 'Male'),
('F', 'Female'),
)
gender = models.CharField(max_length=1, choices=GENDER_CHOICES)
birthday = models.DateField()
serializers.py
class StudentSerializer(serializers.ModelSerializer):
class Meta:
model = Student
fields = ('classroom', 'first_name', 'last_name', 'gender', 'birthday')
class ClassroomSerializer(serializers.ModelSerializer):
students = StudentSerializer(many=True)
class Meta:
model = Classroom
depth = 1
fields = ('school', 'academic_year', 'classroom', 'floor', 'students')
views.py
def index(request):
return render_to_response('school_app/base.html', RequestContext(request))
class StudentViewSet(viewsets.ModelViewSet):
queryset = Student.objects.all()
serializer_class = StudentSerializer
class ClassroomViewSet(viewsets.ModelViewSet):
queryset = Classroom.objects.all()
serializer_class = ClassroomSerializer
and urls.py
router = routers.SimpleRouter()
router.register(r'classrooms', ClassroomViewSet)
router.register(r'students', StudentViewSet)
urlpatterns = router.urls
urlpatterns = [
url(r'^admin/', include(admin.site.urls)),
url(r'^api-auth/', include('rest_framework.urls', namespace='rest_framework')),
url(r'^api/classrooms/$', school_app.views.ClassroomViewSet.as_view({'get': 'list'}), name='classroom-list'),
url(r'^api/students/$', school_app.views.StudentViewSet.as_view({'get': 'list'}), name='student-list'),
url(r'^', 'school_app.views.index', name='index-page'),
]
And here's the Angular "part" of the project, with:
base.html
<body ng-app="userListApp" ng-controller="UsersController">
<table class="table table-striped">
<thead>
<tr>
<th>Classroom</th>
<th>School</th>
<th>Academic year</th>
</tr>
</thead>
<tbody>
<tr ng-repeat="classroom in classrooms">
<td>{{classroom.classroom}}</td>
<td>{{classroom.school}}</td>
<td>{{classroom.academic_year}}</td>
</tr>
</tbody>
</table>
</body>
And app.js
var userListApp = angular.module('userListApp', ['ngResource']);
userListApp.controller('UsersController', function ($scope, Classroom) {
Classroom.query().then(function (result) {
console.log(result);
$scope.classrooms = result.classrooms;
}, function (result) {
alert("Error: No data returned");
});
});
userListApp.factory('Classroom', [
'$resource', function($resource) {
return $resource('/api/classrooms/:id', {
classrooms: '#classrooms'
});
}
]);
I think there's something wrong in the script, but I can't realize what part I'm missing. I'm not sure about the routing either.
I'm getting only the table without the records. Any thoughts?

edit and update the row in database using django

models.py
class Author(models.Model):
first_name = models.CharField(max_length=30)
last_name = models.CharField(max_length=40)
email = models.EmailField()
age = models.IntegerField()
def __unicode__(self):
return "{0} {1} {2} {3} {4}".format(
self, self.first_name, self.last_name, self.email, self.age)
class Book(models.Model):
book_name=models.CharField(max_length=30)
publisher_name=models.CharField(max_length=40)
author=models.ForeignKey(Author)
def __unicode__(self):
return "{0} {1} {2}".format(
self.pk, self.book_name, self.publisher_name)
forms.py
class AuthorForm(ModelForm):
class Meta:
model = Author
BookFormset = inlineformset_factory(Author, Book,
fields=('book_name', 'publisher_name'), extra=1,
can_delete=False)
urls.py is
admin.autodiscover()
urlpatterns = patterns('',
url('^$', index),
url('^index/$', index),
url('^addbook/$', addbook),
url('^book_detail/$', book_detail, 'book_summary'),
url('^editbook/(?P<book_id>\d+)/$', editbook) ,
url('^deletebook/(?P<book_id>\d+)/$',deletebook) ,
url(r'^admin/', include(admin.site.urls)),
)
I need to perform edit and update the row in database,i did it by using single table.But using two table have some confusion how to take 2nd table using that particular id.I am using forms in this.Can you help me in this to write codes in views.py.Example for doing the same using two table is no where i seen.
Thanks
def update_book(request, book_id):
author = get_object_or_404(Author, pk=author_id)
form = AuthorForm(instance=author)
book_formset = BookFormset(instance=author)
if request.method == 'POST':
form = AuthorForm(request.POST, instance=author)
if form.is_valid():
author = form.save(commit=False)
book_formset = BookFormset(request.POST, instance=author)
if book_formset.is_valid():
author.save()
book_formset.save()
return redirect('/index/')
return render_to_response('updatebook.html',{
'form': form, 'formset': book_formset
},context_instance=RequestContext(request))
<div align="center">
<tr>
<form method="POST">
{% csrf_token %}
<h5>Author:</h5>
{{ form.as_p }}
<h5>Book:</h5>
{{ formset.as_p }}
<input type="submit" value="submit">
</form>
</tr>
</div>

(1242, 'Subquery returns more than 1 row') error in Django?

I have a model like this in Django:
class File(models.Model):
users = models.ForeignKey(User)
file_name = models.CharField(max_length=100)
type = models.CharField(max_length=10)
source = models.CharField(max_length=100)
start_date = models.TextField()
end_date = models.TextField()
duration = models.TextField()
size = models.TextField()
flag = models.TextField()
#delete_date = models.CharField(max_length=100, null=True, blank=True)
class Share(models.Model):
users = models.ForeignKey(User)
files = models.ForeignKey(File)
shared_user_id = models.IntegerField()
shared_date = models.TextField()
I am trying to extract the file shared by logged in user. I simply query in Share
file_s = Share.objects.filter(users_id=log_id)
This extracts the file shared by logged in user. Since, now I know which file is shared by logged in user I tried to get the file information from file table:
shared_file = File.objects.filter(users_id=file_s)
But this is returning:
DatabaseError at /shared_by_me/
(1242, 'Subquery returns more than 1 row')
#my_views
def shared_by_me(request):
log_id = request.user.id
username = request.user.username
#shared_file = File.objects.filter(users_id=file)
file_s = Share.objects.filter(users_id=log_id)
shared_file = File.objects.filter(users_id=file_s)
#b = Share.objects.filter(users_id=log_id)
return render_to_response('shared_by_me.html', {'shared_by_me':shared_file, 'username':username}, context_instance=RequestContext(request))
#my_template
{% for choice in shared_by_me %}
<tr class="oddclass">
<td><input type="checkbox" name="choice" id="choice{{ forloop.counter }}" value="{{ choice.id }}" /></td>
<td><label for="choice{{ forloop.counter }}">{{ choice.file_name }}</label></td>
<td>{{ choice.type }}</td>
<td>{{ i.size }}</td>
<td>{{ i.end_date }}</td>
</tr>
{% endfor %}
What am I doing wrong?
Because file is not a model but a queryset you should use __in, something like:
shared_file = File.objects.filter(users_id__in=file_s)

Resources