Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Need identification of response code from gunicorn log
In one of my django view, when the event is triggered from the ajax, my gunicorn is logged like this: May 11 18:47:39 ip-172-31-39-123 gunicorn[15164]: - - [11/May/2020:18:47:39 +0530] "POST /broadcast_in_msg/9/6 HTTP/1.0" 200 402 "http://<test-domain>/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_15_3) AppleWebKit/605.1.15 (KHTML, like Gecko) Version/13.0.5 Safari/605.1.15" I notice there is response code 200, but to the right of 200 I see 402, can someone please tell me if that 402 has to do anything POST /broadcast_in_msg/9/6 HTTP/1.0" 200 402 <----** -
Not being able to display comments in template
I'm making a Post and Comment model by taking reference from internet. i created and Post and Comment model and it looks ok in django admin panel. i can add post and also a comment to any particular post. but getting trouble when I'm trying to display the comment under the post in templates(under post detail views). PLEASE HELP models.py class Post(models.Model): author = models.ForeignKey(User,on_delete=models.CASCADE) title = models.CharField(max_length=100) content = RichTextField() tags = models.CharField(max_length=50,blank=True,null=True) date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.title def get_absolute_url(self): return reverse('post-detail',kwargs={'pk':self.pk}) class Comment(models.Model): post = models.ForeignKey(Post,on_delete=models.CASCADE) author = models.ForeignKey(User,max_length=50,on_delete=models.CASCADE) text = models.TextField() create_date = models.DateTimeField(default=timezone.now) def get_absolute_url(self): return reverse('discuss') views.py class PostDetailView(DetailView): model = Post def add_comment_to_post(request,pk): return get_object_or_404(Post,pk=pk) if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post= post comment.save() return redirect('post-detail',pk=post.pk) else: form = CommentForm() return render(request, 'discuss/comment_form.html',{'form':form}) def comment_remove(request,pk): comment = get_object_or_404(Comment,pk=pk) post_pk = comment.post.pk comment.delete() return redirect('post-detail', pk=post_pk) post_detail.html {% extends 'index.html' %} {% block content %} <article class="media content-section"> <div class="medaia-body"> <img class="rounded-circle article-img" src="{{ object.author.profile.image.url }}" alt="image not found"> <div class="article-metedata"> <a class="mr-2" href="{% url 'user-posts' object.author.username %}">{{object.author}}</a> <small class="text-muted">{{ object.date_posted|date:"F d, Y"}}</small> </div> <h2 class="article-title">{{ object.title }}</h2> <img class="query-img" src="{{ object.image.url }}" alt="image not found"> <p … -
Setting up Django email verification: NOT NULL constraint failed: auth_user.password
I am currently setting up the django_email_verification package (link to the instructions) to send out according email verifications once the user signs up at my page. I followed the instructions but something seems to be bugged. I run all migrations, there is nothing left to migrate right now. It seems that Django can't import any methods from django_email_verification since my IDE underlines it in red at all? Error: Environment: Request Method: POST Request URL: http://127.0.0.1:8000/register/ Django Version: 3.0.6 Python Version: 3.8.0 Installed Applications: ['django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'calculator', 'accounts', 'django_email_verification', 'six'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\utils.py", line 86, in _execute return self.cursor.execute(sql, params) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\backends\sqlite3\base.py", line 396, in execute return Database.Cursor.execute(self, query, params) The above exception (NOT NULL constraint failed: auth_user.password) was the direct cause of the following exception: File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Jonas\Desktop\CFD\CFD\accounts\views.py", line 30, in registerPage user = get_user_model().objects.create(username=username, password=password, email=email) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\manager.py", line 82, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\Users\Jonas\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\db\models\query.py", line 433, in create obj.save(force_insert=True, … -
Django profile edit permission
I have a problem, I would like to make sure that only the logged-in judge or speaker can edit their own profile, I'm not quite sure if I should change it in templates or in view. Thank you for all your advice, I'm new to all this this is my update view for judges @allowed_users(allowed_roles=['judges']) def updateJudges(request, pk): judge = Judges.objects.get(id=pk) form = JudgesForm(instance=judge) if request.method == "POST": form = JudgesForm(request.POST, instance=judge) if form.is_valid(): form.save() return redirect('ksm_app:detail', judge.id) context = {'form':form} return render(request, 'ksm_app/judges_form.html', context) and this is my update debatant view def updateDebatants(request, pk): debatants = Debatants.objects.get(id=pk) form = DebatantsForm(instance=debatants) if request.method == "POST": form = DebatantsForm(request.POST, instance=debatants) if form.is_valid(): form.save() return redirect('ksm_app:debatants_detail', debatants.id) context = {'form':form} return render(request, 'ksm_app/debatants_form.html', context) I just want to make that every user will see their profile but only one user can edit his own profile -
Django navigation dropdown search function
My first post on here i'm looking for some help with a customer portal i'm creating. Built with Django accessing mssql databases. Currently i'm struggling getting the nav menu working in a readable way i can either get it to show all the customers or none of them, I am trying to get a search function so when the user has entered 3 or more characters it then returns matching entries below as links. dropdown menu picture I'm currently trying with javascript, this is from inspecting the page: // Filter function myFunction() { var input, filter, a, i, prefix, link; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); prefix = <QuerySet ['customer1', 'customer2', ***several hundred entires***]> if filter.value.length > 3 { prefix.style.visibility = "visible"; } else { prefix.style.visibility = "hidden"; } } } } css template: <div class="w3-dropdown-content w3-bar-block w3-card w3-blue" id="myDIV"> <input class="w3-input w3-padding w3-blue w3-text-orange" type="text" placeholder="Search.." id="myInput" onkeyup="myFunction()"> <!-- {% for l in prefix %} <a href="/customers/?link={{ l }}">{{ l }}</a> {% endfor %} --> </div> If i use the above forloop i just get a massive output of all the database entries preloading the database entries for use in the template: def customer_page_dropdown(request): prefix = customers.objects.using('navdb').order_by("customer").values_list('customer', flat=True).distinct() # … -
I want to Execute the python method by clicking on Html Button....in my django project
NoReverseMatch at /studentUpdate/ Reverse for 'student_update' not found. 'student_update' is not a valid view function or pattern name. I am explaining the code very simply Here is the code for the html button named update at the end of the form by clicking on that I want to execute python method called student_update <form id="form" method="POST" action="{% url 'students' %}"> {% csrf_token %} <div class="form-group"> <label >Student ID:</label> <input type="text" name="sid" required="required" class="form-control"/> </div> <div class="form-group"> <label>First name:</label> <input type="text" name="firstname" class="form-control"/> </div> <div class="form-group"> <label>Last name:</label> <input type="text" name="lastname" class="form-control"/> </div> <div class="form-group"> <label>Department:</label> <input type="text" name="department" class="form-control" required="required"/> </div> <div class="form-group"> <label>Section:</label> <input type="text" name="section" class="form-control"/> </div> <div class="form-group"> <label>Year:</label> <input type="text" name="year" class="form-control"/> </div> <div class="form-group"> <button name="save_book" id="save_book" type="submit" class="btn btn-primary" href="{% url 'student_update' %}"> <span class="glyphicon glyphicon-save"> </span> Update </button> </div> </form> > Here is my url.py file from django.conf.urls import url, include from . import views from django.urls import path, re_path urlpatterns = [ url(r'^index$', views.index), url(r'^student_update/(\d+)/$', views.student_update, name="updt_stud") ] Finally Here is my views.py file from django.shortcuts import render, redirect from django.http import JsonResponse from django.db.models import Sum from datetime import date from datetime import datetime from django.contrib.auth.decorators import login_required from django.http import … -
Django Query ManyToMany with Custom Through Table Field Data
I've been trying to figure this one out for a while now but am confused. Every ManyToMany relationship always goes through a third table which isn't that difficult to understand. But in the event that the third table is a custom through table with additional fields how do you grab the custom field for each row? Here's a sample table I made. How can I get all the movies a User has watched along with the additional watched field and finished field? This example assumes the user is only allowed to see the movie once whether they finish it or not so there will only be 1 record for each movie they saw. class Movie(models.Model): title = models.CharField(max_length=191) class User(models.Model): username = models.CharField(max_length=191) watched = models.ManyToMany(Movie, through='watch') class Watch(models.Model): user = models.Foreignkey(User, on_delete=models.CASCADE) movie = models.Foreignkey(Movie, on_delete=models.CASCADE) watched = models.DateTimeField() finished = models.BooleanField() Penny for your thoughts my friends. -
How to receive rating in django and how to render it to front-end?
I have two class inside my model and these two models are : from django.db import models from accounts.models import * from django.core.validators import MinValueValidator, MaxValueValidator # Create your models here. class Products(models.Model): name = models.CharField(max_length=50) img = models.ImageField(upload_to='productImage') CATEGORY = ( ('Snacks','Snacks'), ('Juice','Juice'), ) category = models.CharField(max_length=50, choices=CATEGORY) description = models.TextField() price = models.FloatField() review = models.TextField() def no_of_rating(self): rating = Rating.objects.filter(product=self) return len(rating) def avg_rating(self): sum = 0 ratings = Rating.objects.filter(self) for rating in ratings: sum += rating if len(ratings>0): return sum//len(rating) else: return 0 rating = avg_rating(self) # This Line did not work for me def __str__(self): return self.name class Rating(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) stars = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)]) def __str__(self): return str(self.product)+"---"+str(self.user) I want to store the average rating of the product in the Product model/table, how can I perform this operation as I am not able to doing that by my code manly by calling that function. How to store each product's average value in the product module. and while I am trying to resolve it by directly calling the method of that product model am getting this below error: "TypeError at /products 'Products' object is not iterable" Is there any way … -
Django - Pass Session Variables From One View To Another ('request' is undefined)
I have looked at this (django variable of one view to another from session), but I believe the desired outcome is quite different. I have two views in my views.py file: projectcreation and projectconfirm. After the user fills out a form in the projectcreation view, I want them to be directed to a confirmation page that gives a read-only view of the variables before proceeding with the project creation. My views.py file looks like this: from django.shortcuts import render from django.http import HttpResponse from .projectform import ProjectForm from .projectconfirm import ProjectConfirm def projectcreation(request): if request.method == 'POST': form = ProjectForm(request.POST) if form.is_valid(): request.session['projectname'] = form.cleaned_data['client'] + "-" + form.cleaned_data['stage'] + "-" + form.cleaned_data['purpose'] request.session['computeapi'] = form.cleaned_data['computeapi'] request.session['deploymentmanapi'] = form.cleaned_data['deploymentmanapi'] request.session['storagecompapi'] = form.cleaned_data['storagecompapi'] request.session['monitorapi'] = form.cleaned_data['monitorapi'] request.session['loggingapi'] = form.cleaned_data['loggingapi'] return render(request,'projectconfirm.html') else: form = ProjectForm() return render(request, 'projectform.html', {'form': form}) def projectconfirm(request): if request.method =='POST': print("Now beginning deployment...") else: form = ProjectConfirm() return render(request, 'projectconfirm.html', {'form': form}) The problem I'm facing and admittedly not understanding is how to load the session variables in the projectconfirm.py script. I thought something like the following would work, but it's complaining that 'request' is an undefined variable: from django import forms from django.shortcuts import render … -
Take Mutiple image by Django
''' views.py, This works fine. But i can take only one image for my blog and it also save in my db. But i want to take multiple image for my blog post. That's not working and it shows error. How to take multiple image and save it in my database. ''' class IndexView(View): def get(self, request, *args, **kwargs): slide = Slider.objects.all() blogslide = BlogSlider.objects.all() post_form = PostForm() paginator = Paginator(blogslide, 3) page = request.GET.get('page') blogslide = paginator.get_page(page) return render(request, 'index.html', {'slide': slide, 'blogslide': blogslide, 'post_form': post_form}) def post(self, *args, **kwargs): post_form = PostForm(self.request.POST, self.request.FILES or None) if post_form.is_valid(): title = post_form.cleaned_data['title'] sub_title = post_form.cleaned_data['sub_title'] description = post_form.cleaned_data['description'] image = post_form.cleaned_data['image'] p = BlogSlider( description = description, image = image, title = title, sub_title = sub_title, user = self.request.user, ) p.save() return redirect('/') ''' models.py ''' class BlogSlider(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) image = models.ImageField() title = models.CharField(max_length = 100) sub_title = models.CharField(max_length = 20) description = models.TextField(null=True, blank=True) slug = models.SlugField(null=True, blank=True) def __str__(self): return self.title ''' forms.py ''' class PostForm(ModelForm): image = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = BlogSlider fields = ('title', 'sub_title', 'description',) -
join() argument must be str or bytes, not 'dict'
I am completely new to Django and influxdb. I am trying to retrieve data from influxdb and pass it to a html file. My views.py file is pasted below from django.shortcuts import render from django.http import HttpResponse from influxdb import InfluxDBClient from datetime import datetime client = InfluxDBClient(host='localhost', port=8086) client.switch_database('db1') def index(request): print(request.GET) data_from_web_page = request.GET if data_from_web_page.__contains__('locationid'): date_from = data_from_web_page.get('datefrom') date_fr = datetime.strptime(date_from, "%Y-%m-%d") date_to = data_from_web_page.get('dateto') date_t = datetime.strptime(date_to, "%Y-%m-%d") location_id = data_from_web_page.get('locationid') result = client.query('Select "day", "date", "ghi" From "' + location_id + '" where day>= '+str(date_fr.day)+' and month>= '+str(date_fr.month)+ ' and day<= '+str(date_t.day)+' and month<= '+str(date_t.month)) #print("DATA from Database", result) return render(request, "yourapp/yourtemplate.html", {'d': result}) #return HttpResponse({'d':result}, 'maps_app/table.html', content_type=text/html") return render(request,'maps_app/index.html') I am able to retrieve data from the database. But when I try to render it I get the following error. Internal Server Error: / Traceback (most recent call last): File "/usr/local/lib/python3.7/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.7/site-packages/django/core/handlers/base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/aishwarya/Desktop/DjangoApp/task1/maps_app/views.py", line 19, in index return render('maps_app/table.html',{'d':result}) File "/usr/local/lib/python3.7/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/usr/local/lib/python3.7/site-packages/django/template/loader.py", line 61, in … -
django models ForeignKey on_delete set custom default
I have a model subscription where the class is defined as below, class Subscription(TimestampedModel): ... notification = models.ForeignKey( 'settings.NotificationPreference', on_delete=models.SET(get_default_reminder), null=True ) ... I would like to set the default notification: id if the foreign model is deleted, Upon some research found the set method which could be used to achieve the same, referring https://docs.djangoproject.com/en/2.1/ref/models/fields/#django.db.models.SET I could understand the implementation, However i am now stuck as the default notification is going to be per user based. My get_default_reminder function is as below, def get_default_reminder(): return NotificationPreference.objects.get(user_id=user_id, name='Default Notification') The problem here is I do not understand how to pass the user_id to get the user specific default notification id. -
How to check redirect in Django while testing in Django
I want to write a unit test than checks where I was redirected. There are 2 behaviours depending on number of players in a room. I want to check this function: @login_required def game_join(request, id): game = Game.objects.get(pk=id) if game.players_ready == game.max_players: return redirect('home',name="full") else: return redirect('detail', game.id) Test: def test_join_empty_room(self): game = Game.objects.create(name='empty',host='dottore',is_played=False,max_players=4,players_ready=0) self.join_url_empty = reverse('game_join', args=[game.id]) response = self.client.get(self.join_url_empty, follow=True) print(response.redirect_chain) self.assertEquals(response.status_code,200) Test answer is ok. Redirect chain: [('/player/login?next=/game/1/join', 302)] So it gives me no info, since url patterns are like this: path('<int:id>/', detail, name = 'detail'), path('<int:id>/join', game_join, name = 'game_join'), So correct answer should be sth like: http://127.0.0.1:8000/game/64/ How to do that correctly? -
mysqlclient error when moving django project from windows to Centos
up till now, I was using windows for my django project along with xampp to host my test database for the project. I now need to move to Centos and continue the rest of the project (due to unavoidable cirumstances). My understanding is : I should be able to use lampp for my test database along with my django project. (However, I'm not sure about how to do it) I'm currently stuck at installing mysqlclient I'm doing pip install mysqlclient gives me error compilation terminated. error: command 'gcc' failed with exit status 1 -
Django 2.2 reverse lookup NoReverseMatch error
I am porting an old project from an older version of django to django 2.2 and python 3.6.8. I am running into an issue resolving a page that includes a reverse lookup link and getting this error django.urls.exceptions.NoReverseMatch: Reverse for 'views.users_staff' not found. 'views.users_staff' is not a valid view function or pattern name. It looks to me like it can't find the view using the reverse url I have in my urls.py file but I can't figure out how it needs to be written. Here is what I have right now. html template: {% if user.isManager %} <tr> <td class="field">staff list</td> <td class="value"><a href="{% url 'views.users_staff' env user.hid %}">Link</a> </tr> <tr> <td class="field">org chart</td> <td class="value"><a href="{% url 'views.users_staff' env user.hid %}?org=1">Link</a> </tr> {% endif %} This page specifically does an LDAP call for a user and if the user is a manager it includes these links on the page to their direct reports. urls.py from django.urls import path, re_path from . import views urlpatterns = [ # path(r'^media/(?P<path>.*)$', views.static.serve, {'document_root': os.path.join(settings.DJANGO_PROJECT_ROOT, 'user_search/media')}), # re_path(r'^$', views.index, name=index), re_path(r'^user/$', views.users_default, name='users_default'), re_path(r'^user/(?P<env>(production|certification|uat|integration|development))/$', views.users, name='users'), re_path(r'^user/(?P<env>(production|certification|uat|integration|development))/(?P<hid>[0-9]+)/$', views.users_staff, name='users_staff')**, re_path(r'^ud_data_extract/$', views.uddataextract, name='uddataextract'), The path for views.users works fine when the specific user does … -
Django 3 - How can I dynamically load choices of a CharField in a CBV from another table (foreign key)?
A user creates one or more objects of class VO. Afterwards, they might want to add one or more VE to one VO. I tried to realize this with Class Based Views (CBVs). models.py: class VE(models.Model): name = models.CharField(max_length=255, blank=False) vo = models.ForeignKey(VO, on_delete=models.CASCADE) class VO(models.Model): name = models.CharField(_("Description"), max_length=255, blank=False) owner = models.ForeignKey(User, on_delete=models.CASCADE) How can I now make sure that the CreateView for VE has a dropdown/previously filled out field for VO? To be more specific, I want the user to only select a VO which he owns (self.request.user == owner). Is this at all possible with CBVs in Django 3 or do I have to create a custom method which uses render()? I hope I formulated that question somewhat understandable. If not, please let me know and I'll provide additional needed information. Thanks -
Django count views using, django-hitcount
I did break my head to implement django-hitcount on my blog. I could do the views count works, but are happening an error to access in my administration page. Following the code and the error image: Thank you. urls.py from django.contrib import admin from django.conf import settings from django.conf.urls.static import static from django.urls import path, include from blog.views import index, blog, post urlpatterns = [ path('admin/', admin.site.urls), path('', index, name='home'), path('blog/', blog, name='post-list'), path('post/<id>/', post, name='post-detail'), path('ckeditor', include('ckeditor_uploader.urls')), path('hitcount/', include(('hitcount.urls', 'hitcount'), namespace='hitcount')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) views.py from django.shortcuts import render, get_object_or_404, redirect, reverse from .models import Post, Author from django.db.models.aggregates import Count from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger from hitcount.models import HitCount from hitcount.views import HitCountMixin ... def post(request, id): category_count = get_category_count() most_recent = Post.objects.order_by('-timestamp')[:3] popular_posts = Post.objects.order_by('-hit_count_generic__hits')[:3] post = get_object_or_404(Post, id=id) hit_count = HitCount.objects.get_for_object(post) hit_count_response = HitCountMixin.hit_count(request, hit_count) count_hit = True if request.method == "POST": return redirect(reverse("post-detail", kwargs={ 'id': post.pk })) context = { 'post': post, 'hit_count': hit_count, 'category_count': category_count, 'popular_posts': popular_posts, 'views': Post.objects.get(pk=1), # views.hit_count.hits # views.hit_count.hits_in_last(days=7) } return render(request, 'blog/post.html', context) post.html {% extends 'blog/base.html' %} {% load static %} {% load hitcount_tags %} {% block content %} <body> <div class="container"> <div class="row"> <div class="col-md-8"> … -
Render a html file in Django
I read the document about django tutorial. Now I want to read my html and display it. So I start a project and start a app myapp_page. The folder structure is blow. I render my html file in the views. There is "Hello world" in this html file. I set the path in the urls.py. And I add the folder path in the settings.py. But the html didn't show in the 127.0.0.1:8000/myapp_page/ How to display my custom html file? How does the django manage the path? I am confuse. -
Alter the parameter name during serialization
I am having struggles with the alteration on the parameter name during serialization with DRF. My input would be a JSON with some parameters: { "limit": 10, "type": "group", [...] } and my serializer looks like: class RankSerializer(serializers.Serializer): limit = serializers.IntegerField(default=100, min_value=1) type = serializers.CharField() def validate_type(self, t): # validation But this doesn't sound right. Type is a reserved keyword in Python so I don't want to use it as a parameter name. I'd like to somehow map it to i.e result_type or something like this. I already tried using the source= parameters as follows: result_type = serializers.CharField(source='type') but this doesn't seem to work on non-model inputs. I cannot rename the parameter on the frontend level. I'd appreciate any tips regarding this issue. Cheers. -
How to take and store product rating in django?
I have two class inside my model and these two models are : from django.db import models from accounts.models import * from django.core.validators import MinValueValidator, MaxValueValidator # Create your models here. class Products(models.Model): name = models.CharField(max_length=50) img = models.ImageField(upload_to='productImage') CATEGORY = ( ('Snacks','Snacks'), ('Juice','Juice'), ) category = models.CharField(max_length=50, choices=CATEGORY) description = models.TextField() price = models.FloatField() review = models.TextField() def no_of_rating(self): rating = Rating.objects.filter(product=self) return len(rating) def avg_rating(self): sum = 0 ratings = Rating.objects.filter(self) for rating in ratings: sum += rating if len(ratings>0): return sum//len(rating) else: return 0 rating = avg_rating(self) # This Line did not work for me def __str__(self): return self.name class Rating(models.Model): product = models.ForeignKey(Products, on_delete=models.CASCADE) user = models.ForeignKey(User, on_delete=models.CASCADE) stars = models.IntegerField(validators=[MinValueValidator(1),MaxValueValidator(5)]) def __str__(self): return str(self.product)+"---"+str(self.user) I want to store the average rating of the product in the Product model/table, how can I perform this operation as I am not able to doing that by my code manly by calling that function. How to store each product's average value in the product module. and while I am trying to resolve it by directly calling the method of that product model am getting this below error: "TypeError at /products 'Products' object is not iterable" template error -
django : How can I give a huge initial value contents inside the form?
To make initial contract form, I'd like to make a form with huge initial value like below. Of course it doesn't work. How can I give a looooong initial value with perfect space and line break with django form? class CreateFromationPlanFormVC(forms.ModelForm): class Meta: model = models.FormationPlan fields = ("content",) widgets = { "content": forms.TextInput( attrs={"placeholder": "내용", "style": "width: 100%; height: 10em"} ), } def __init__(self, *args, **kwargs): super(CreateFromationPlanFormVC, self).__init__(*args, **kwargs) self.fields["content"].label = "내용" self.fields[ "content" ].initial = ( "The standard Lorem Ipsum passage, used since the 1500s "Lorem ipsum dolor sit amet, consectetur adipiscing elit, sed do eiusmod tempor incididunt ut labore et dolore magna aliqua. Ut enim ad minim veniam, quis nostrud exercitation ullamco laboris nisi ut aliquip ex ea commodo consequat. Duis aute irure dolor in reprehenderit in voluptate velit esse cillum dolore eu fugiat nulla pariatur. Excepteur sint occaecat cupidatat non proident, sunt in culpa qui officia deserunt mollit anim id est laborum." Section 1.10.32 of "de Finibus Bonorum et Malorum", written by Cicero in 45 BC "Sed ut perspiciatis unde omnis iste natus error sit voluptatem accusantium doloremque laudantium, totam rem aperiam, eaque ipsa quae ab illo inventore veritatis et quasi architecto beatae vitae dicta sunt … -
Select Related With Multiple Conditions
Using the Django ORM is it possible to perform a select_related (left join) with conditions additional to the default table1.id = table2.fk Using the example models: class Author(models.Model): name = models.TextField() age = models.IntegerField() class Book(models.Model): title = models.TextField() and the raw sql SELECT 'Book'.*, 'Author'.'name' FROM 'Book' LEFT JOIN 'Author' ON 'Author'.'id' = 'Book'.'author_id' AND 'Author'.'age' > 18 ;<---this line here is what id like to use via the ORM I understand that in this simple example you can perform the filtering after the join, but that hasn't worked in my specific case. As i am doing sums across multiple left joins that require filters. -
How to fill a django model form little bit in frontend and a bit in backend?
This is my view function def add(request): q_form = QuestionForm() option_form = modelformset_factory(Option,fields=('text' , 'option_image' , 'is_correct')) o_form = option_form(queryset=Option.objects.none()) if request.method == 'POST': type_custom = request.POST.get("type_custom") date_custom = request.POST.get("year_custom") date_custom = date_custom+"-04-20" crct_opts = request.POST.get("form-TOTAL_FORMS") if type_custom == "SC": q_form = QuestionForm(request.POST , request.FILES) q_form.type = type_custom q_form.no_of_crct_opts = crct_opts q_form.date_asked = date_custom q_form.date_asked = date_custom print(q_form.type) if q_form.is_valid(): q_form.save() print("saved") return redirect('index') else: print("not Saved") return redirect('index') return render(request,'add_question/add.html' , context) This is my forms.py from django import forms from practice.models import Question from practice.models import Option from django.forms import ModelForm import django.forms.widgets class QuestionForm(ModelForm): class Meta: model = Question fields = ['question_image', 'subject', 'topic', 'exam_type' , 'date_asked', 'type' , 'secondary_image' , 'no_of_crct_opts' ,'max_marks', 'negative_marks' , 'scheme_string'] So I am just filling out some fields in my template and some fields I want to fill in the view function when the data is posted from the extra post data that I am getting. So as you can see in the view function I am extracting some post data and the processing it a bit then I want to add that data to the fields that I didn't make available on actual form in the template. So this is … -
what actually it is doing (data=request.data)?
''' def post(self,request): serializer=NameSerializers(data=request.data) if(serializer.is_valid): name=serializer.data.get('name') msg='hello {} Wish you happy New Year'.format(name) return Response({'msg':msg}) return Response(serializer.errors,status=400) ''' my first questions are data=request.data is it getting the data the client app has been sending in JSON. serializer.is_valid is the inbuild function of serializer class to check the data we have received is valid data or not? serializer.data.get('name') and what this line is doing ? -
In my Django Project, I am Trying to execute the python method in by hitting the html button
When i am hitting the edit button of my studentUpdate.html file then i am geting following Error:- NoReverseMatch at /studentUpdate/ Reverse for 'update_student' with no arguments not found. 1 pattern(s) tried: ['update_student/(\d+)/$'] Some one help me. > Here is my studentUpdate.html {% extends 'app.html' %} {% block body %} <div> <div class="alert alert-info">All Students</div> <button id="show_book" type="button" class="btn btn-success"> <span class="glyphicon glyphicon-circle-arrow-left"> </span> Back </button> <div id="edit_form"></div> <div id="book_form" > <div class="col-lg-3"></div> <div class="col-lg-6"> <form id="form" method="POST" action="{% url 'students' %}"> {% csrf_token %} <div class="form-group"> <label >Student ID:</label> <input type="text" name="sid" required="required" class="form-control"/> </div> <div class="form-group"> <label>First name:</label> <input type="text" name="firstname" class="form-control"/> </div> <div class="form-group"> <label>Last name:</label> <input type="text" name="lastname" class="form-control"/> </div> <div class="form-group"> <label>Department:</label> <input type="text" name="department" class="form-control" required="required"/> </div> <div class="form-group"> <label>Section:</label> <input type="text" name="section" class="form-control"/> </div> <div class="form-group"> <label>Year:</label> <input type="text" name="year" class="form-control"/> </div> <div class="form-group"> <button name="save_book" id="save_book" type="submit" class="btn btn-primary" href="{% url 'update_student' %}"><span class="glyphicon glyphicon-save"></span> Update </button> </div> </form> </div> </div> </div> {% endblock %} {% block scripts %} <script> $(document).ready(function () { $('#table').DataTable(); }); $(document).ready(function () { $('#add_book').click(function () { $(this).hide(); $('#show_book').show(); $('#book_table').slideUp(); $('#book_form').slideDown(); $('#show_book').click(function () { $(this).hide(); $('#add_book').show(); $('#book_table').slideDown(); $('#book_form').slideUp(); }); }); }); $('.editButton').on('click', function () { var id = $(this).attr('data-id'); …