Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - reload template after post request
My template does not reload immediately after hitting button for post request. But I know the request worked fine because if I load the page manually (with link) I can see it changed correctly. Any ideas? I understand the problem is in the render of post method... def profile(request, user): this_user = request.user profileuser = get_object_or_404(User, username=user) posts = Post.objects.filter(user=profileuser).order_by('id').reverse() followed = Follow.objects.filter(followed=profileuser) following = Follow.objects.filter(following=profileuser) all_followed = len(followed) all_following = len(following) paginator = Paginator(posts, 10) if request.GET.get("page") != None: try: posts = paginator.page(request.GET.get("page")) except: posts = paginator.page(1) else: posts = paginator.page(1) try: both_follow = Follow.objects.filter(followed=profileuser, following=request.user) except: both_follow == False context = { "posts": posts, "profileuser": profileuser, "all_followed": all_followed, "all_following": all_following, "both_follow": both_follow, "this_user": this_user, } if request.method == "GET": return render(request, "network/profile.html", context) if request.method == "POST": if both_follow: both_follow.delete() both_follow == False else: f = Follow() f.followed = profileuser f.following = request.user f.save() both_follow == True return render(request, "network/profile.html", context) And the html is: <p> <button type="button" class="btn btn-success" data-toggle="modal" data-target="#followed">{{ all_followed }} Followers </button> <button type="button" class="btn btn-success" data-toggle="modal" data-target="#following">{{ all_following }} Following </button> </p> {% if profileuser != this_user %} {% if both_follow %} <form action="{% url 'profile' profileuser %}" method="POST"> {% csrf_token %} <button … -
UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte in django
I want to get the list of posts api through the get request.But after writing the code, I sent the get request and the following error appears. Traceback Traceback (most recent call last): File "C:\Users\kurak\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\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response response = response.render() File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\renderers.py", line 100, in render ret = json.dumps( File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\utils\json.py", line 25, in dumps return json.dumps(*args, **kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 234, in dumps return cls( File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\utils\encoders.py", line 50, in default return obj.decode() UnicodeDecodeError: 'utf-8' codec can't decode byte 0xff in position 0: invalid start byte In the previous code, we received it normally without any decoding errors, and this problem occurs after modification. What's the problem? Here's my code. views.py class CreateReadPostView (ModelViewSet) : serializer_class = PostSerializer permission_classes = [IsAuthenticated] queryset = Post.objects.all() def perform_create (self, serializer) : serializer.save(author=self.request.user) def list (self, request) : posts = Post.objects.all() data … -
Django-haystack & solr : Increase the number of results
I have this function : def search_books(request): search_text = request.POST.get('search_text') if search_text: books = SearchQuerySet().filter(content=search_text).filter(quantite__gte=0) else: books = [] return render_to_response("search/search.html", {'books': books}) By default it returns only 20 results, is there a way to increase that number? Thanks. -
Have a django reverse to a url with PK <int:pk>
I was following This Tutorial to set up payment with PayPal my problem is with the paypal_dict as it contains this paypal_dict = { ... 'return_url': 'http://{}{}/{}'.format(host, reverse('payment_done')), ... } and my payment_done URL needs to have an id for the trade itself, I'm not sure how can i have a pk within this Here is my full URLs.py ... # Payment path('payment/process/<int:trade_id>/', payment_views.payment_process, name="payment_process"), path('payment/done/<int:trade_id>/', payment_views.payment_done, name="payment_done"), ... My full process_paypal def payment_process(request, trade_id): trade = get_object_or_404(Trade, id=trade_id) host = request.get_host() paypal_dict = { 'business': settings.PAYPAL_RECEIVER_EMAIL, # todo WHO TO PAY 'amount': Decimal(trade.price), 'item_name': trade.filename, 'invoice': str(trade.id), 'currency_code': 'USD', 'notify_url': 'http://{}{}'.format(host, reverse('paypal-ipn')), 'return_url': 'http://{}{}/{}'.format(host, reverse('payment_done')), 'cancel_return': 'http://{}{}'.format(host, reverse('home')), } form = PayPalPaymentsForm(initial=paypal_dict) return render(request, 'payment/payment_process.html', {'trade': trade, 'form': form}) -
Django Tweepy API.friends clarification
I have an app that fetches friends and followers from a logged user then serves them on an html table. I had the the following code checking for entries that were neither on update and deleted them. # Setup Twitter API instance of logged User api = get_api(user) me = api.me() # Fetch logged User's friends user_friends = api.friends(me.screen_name, count=200) # Fetch logged User's followers user_followers = api.followers(me.screen_name, count=200) # Check for excess entries and delete them if any existing_contacts = Contact.objects.filter(user=user) for contact in existing_contacts: if contact not in user_friends and contact not in user_followers: contact.delete() I decided to use cursor method in order to provide scalability but after changes current code is deleting all contacts. Probably cause it doesn't find the object in any of the lists. Any ideas? # Setup Twitter API instance of logged User api = get_api(user) me = api.me() # Fetch logged User's friends user_friends = tweepy.Cursor(api.friends, me.screen_name, count=200).items() # Fetch logged User's followers user_followers = tweepy.Cursor(api.followers, me.screen_name, count=200).items() # Check for excess entries and delete them if any existing_contacts = Contact.objects.filter(user=user) for contact in existing_contacts: if contact not in user_friends and contact not in user_followers: contact.delete() models.py class Contact(models.Model): twitter_id = models.CharField(max_length=30) profile_image_url … -
ConnectionError(<urllib3.connection.HTTPConnection object at 0x7f70f408b3c8>: Failed to establish a new connection
I am trying to build a social network with django. Every thing was working perfectly. then I changed some code in two views. one in post like_unlike_post view and profile detail view. I added SingleObjectMixin and formviwe with detail view so that people can like and comment on post when visiting others profile. after that I notice this error occurs everytime I try to login or update something. I have no idea what causing this error. Can anyone help me with this. here is my profile detail and update view from django.http import HttpResponseRedirect from django.contrib.auth import get_user_model from django.contrib.auth.mixins import LoginRequiredMixin from django.urls import reverse from django.shortcuts import get_object_or_404, redirect, render from django.utils.translation import gettext_lazy as _ from django.views import View from django.views.generic import DetailView, RedirectView, UpdateView, FormView from django.views.generic.detail import SingleObjectMixin from .models import Profile from posts.forms import PostModelForm, CommentModelForm from posts.models import Post from relationships.models import Relationship User = get_user_model() class ProfileDetailView(LoginRequiredMixin, DetailView): model = Profile slug_field = "slug" slug_url_kwarg = "slug" form_class = CommentModelForm queryset = Profile.objects.prefetch_related('posts__likes', 'friends', 'posts__comment_posted', 'posts__comment_posted__user') def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) sender_profile = get_object_or_404(Profile, id=self.request.user.id) receiver_profile = get_object_or_404(Profile, id=self.object.id) frnd_btn_state = Relationship.objects.relation_status( sender=sender_profile, receiver=receiver_profile, ) context['frnd_btn_state'] = frnd_btn_state context['frnd_req_rcvd'] = Relationship.objects.invitation_recieved( … -
Is theirany way to view the hashed password from Django
I have a an application developed in Django and using BaseUserManger model. When I looking to my database and admin panel password has been hashed. But I want to know what exactly in the password field. Is there any way to know the password? Please try to answer this question if anyone knows..! -
Django related_name not working while using self reference in many-to-many field
I'm currently trying to create following relationship between users, so I used a many-to-many field in the User model to reference itself. class User(AbstractUser): followers = models.ManyToManyField('self', related_name='following') def __str__(self): return self.username However, when I tested this model using shell and trying to access the related_name, it reported error has occurred. >>> u1 = User.objects.get(pk=1) >>> u1.following.all() Traceback (most recent call last): File "<console>", line 1, in <module> AttributeError: 'User' object has no attribute 'following' Now I'm really confused, and really need help or alternative ways of doing this. -
How read a file from Django when using docker?
I run Django in docker and I want to read a file from host. When I test os.stat(path), "No such a file or directory" error returned. The path is something like this '/home/user/file.txt'. Is there any idea that how can I access to host from a running container? thanks -
Django ORM group by week day and sum the day of each separately
I am having trouble to query based on weekday. This is my models: class Sell(models.Model): total_sell = models.IntegerField() date = models.DateField(auto_now_add=True) and this is my query: weekly_sell = Sell.objects.annotate( weekday=ExtractWeekDay('date'), total=Sum('total_sell') ).values( 'weekday', 'total' ) But data i am getting and it is not my expected. Like I have an entry in the table Sunday sell 4 Sunday sell 7 Friday sell 10 So i am expecting it should return these data: [ [ { "weekday": 7, "total": 11 }, { "weekday": 6, "total": 0 }, { "weekday": 5, "total": 10 }, { "weekday": 4, "total": 4 }, { "weekday": 3, "total": 0 }, { "weekday": 2, "total": 0 }, { "weekday": 1, "total": 10 }, ] ] But problem is, it not returning data that way i want, It is returning these: [ [ { "weekday": 7, "total": 4 }, { "weekday": 7, "total": 5 }, { "weekday": 5, "total": 10 }, ] ] I don't know what's wrong with this. Can anyone please help me in this case? -
Setting custom css classes for input container in django form
I have implemented something and I want to know if I did it right or there is a better way to do it. I will describe everything I did. if there's any problem, please excuse me it is my first time to ask questions. I want to implement a form like following with django forms <form id="register-form" class="mt-3"> <div class="py-6 relative"> <label for="email">Email</label> <input type="email" class="form-control" name="email" required=""> <ul class="errorlist" id="error-list-3" aria-hidden="false"> <li>This value is required.</li> </ul> <i class="fa fa-times error" aria-hidden="true"></i> <i class="fa fa-check success" aria-hidden="true"></i> </div> <div class="py-3 relative"> <label for="password">Password</label> <input type="password" id="password" class="form-control" name="password" required=""> <ul class="errorlist" id="error-list-3" aria-hidden="false"> <li>This value is required.</li> </ul> <i class="fa fa-times error" aria-hidden="true"></i> <i class="fa fa-check success" aria-hidden="true"></i> </div> <div class="py-3 relative"> <label for="repeatPassword">Repeat Password</label> <input type="password" class="form-control" name="repeatPassword" required=""> <ul class="errorlist" id="error-list-3" aria-hidden="false"> <li>This value is required.</li> </ul> <i class="fa fa-times error" aria-hidden="true"></i> <i class="fa fa-check success" aria-hidden="true"></i> </div> <div class="mt-4 text-center"> <button type="" class="btn btn-blue">register</button> </div> </form> At first I tried to implement it with django custom widget, like below class CustomInputWidget(forms.Widget): template_name = 'widgets/input.html' input_type = 'text' div_css_classes = '' input_css_classes = '' label = '' def __init__(self, attrs=None, div_css_classes=None, input_css_classes=None, label=None): super().__init__(attrs) if div_css_classes: self.format_div_css_classes(div_css_classes) if … -
Importing a table in SQLite from a .csv-file leads to unicode replacement characters
I am working on a Django (version 3.1) project and am using a SQLite3 database. I am importing tables in the database from a .csv-file. I am using SQLiteBrowser for a tool. After importing the database-table it is full of unicode replacement characters (black diamond with question mark). Prior to importing the table I saved the .csv-file with UTF-8 encoding. From the documentation I understand that SQLite databases are always UTF-8 encoded. So my feeling is that this should not happen. Now there is either something very fundamental or something very simple that I don't understand. I hope somebody can enlighten me. I don't know what else to post to illustrate my question. If need something more please ask. -
db takes duplicate data in Django
I'm creating a social login system in djangorestframework. In my db i'm getting duplicate value entry even i validate the serializers. if social_id exits in db then it must show false message that social_id already exits in db. but in case it's take duplicate entry.... Any help, would be much appreciated. serializers.py : class CreateSocialUserSerializer(serializers.ModelSerializer): social_id = serializers.CharField(allow_blank=True) device_type = serializers.CharField(allow_blank=True) device_token = serializers.CharField(allow_blank=True) login_type = serializers.CharField(allow_blank=True) # username = serializers.CharField(allow_blank=True) #password = serializers.CharField(allow_blank=True) social_img = serializers.CharField(allow_blank=True) email = serializers.CharField(allow_blank=True) phone_number = serializers.CharField(allow_blank=True) country_code = serializers.CharField(allow_blank=True) token = serializers.CharField(read_only=True) first_name = serializers.CharField(allow_blank=True) last_name = serializers.CharField(allow_blank=True) class Meta: model = User fields = ['social_id','device_type','device_token','login_type', 'email','phone_number', 'country_code','token','first_name','last_name', 'social_img'] def validate(self,data): logger.debug(data) social_id = data['social_id'] email = data['email'] device_type = data['device_type'] device_token = data['device_token'] login_type = data['login_type'] #password = data['password'] # username = data['username'] phone_number= data['phone_number'] country_code = data['country_code'] social_img = data['social_img'] if not social_id or social_id =='': raise APIException400({ 'success' : 'False', 'message' : 'Please provide social id' }) userdata_qs = User.objects.filter(social_id__iexact=social_id) if userdata_qs.exists(): raise APIException400({'success': 'False', 'message': 'User with this social_id is already exists. Please login.'}) else: pass return data def create(self,validated_data): # username = validated_data['username'] email = validated_data['email'] phone_number = validated_data['phone_number'] country_code = validated_data['country_code'] login_type = validated_data['login_type'] social_id = validated_data['social_id'] … -
Django Heroku, server does not support SSL, but SSL was required
I have a Django application deployed to Heroku and Postgres, I'm trying to add pgbouncer to scale the app a bit, but I'm getting this error: django.db.utils.OperationalError: server does not support SSL, but SSL was required as a lot of other questions say, the problem is the SSL in django-heroku package. So I tried to approaches, first: adding to the end of setting file the following: del DATABASES['default']['OPTIONS']['sslmode'] the error is still being raised, so I took django-heroku settings function and modified it to disable SSL directly in there def custom_settings(config, *, db_colors=False, databases=True, test_runner=True, staticfiles=True, allowed_hosts=True, logging=True, secret_key=True): # Database configuration. # TODO: support other database (e.g. TEAL, AMBER, etc, automatically.) # Same code as the package # CHANGING SSL TO FALSE config['DATABASES'][db_color] = dj_database_url.parse(url, conn_max_age=MAX_CONN_AGE, ssl_require=False) if 'DATABASE_URL' in os.environ: logger.info('Adding $DATABASE_URL to default DATABASE Django setting.') # Configure Django for DATABASE_URL environment variable. config['DATABASES']['default'] = dj_database_url.config(conn_max_age=MAX_CONN_AGE, ssl_require=False) logger.info('Adding $DATABASE_URL to TEST default DATABASE Django setting.') and calling it: django_heroku_override.custom_settings(config=locals(), staticfiles=False, logging=False) but that didn't work as well, I'm still getting the original error adding Procfile just for complicity: web: bin/start-pgbouncer daphne rivendell.asgi:application --port $PORT --bind 0.0.0.0 -v2 worker: python manage.py runworker channel_layer -v2 -
How to access dynamically generated id of my HTML file in CSS and JS file associated to it
I am creating a blog page in HTML. In the backend I'm using Django. I have created a general HTML template for every post. In Django admin when I upload the image and other data, I'm getting it in Frontend and setting the id of each post dynamically using an autogenerated id coming from Backend. My HTML template is this <div class="row"> {% for blog in blogs_post %} <div class="col-sm-3 offset-sm-1 col-12" id="{{ blog.id }}"> <div class="row"> <div class="col-12"> <img src="{{ blog.image }}" alt=" {{ blog.tittle }}" class="img-fluid"> </div> <div class="col-12"> <h3>{{ blog.tittle }}</h3> <p class="d-none" id="card-body"> <h6>{{ blog.description }}</h6> </p> {% if blog.url %} <a href="{{ blog.url }}" type="submit" role="button" class="btn btn-info">Read more</a> {% endif %} </div> </div> </div> {% endfor %} </div> I want to use this id="{{ blog.id }}" In my CSS file and JS file to uniquely identify each post and apply changes to them. Like if I click one card all the cards should not expand but only the card I clicked will expand. For that I need the dynamically set id to be accessed in my CSS file and JS file. How can I achieve it please help! -
How to get the latest record in the database using django
I have two models, PurchaseOrder and PurchaseOrderdetail, I just want to know how do i get the latest record save in the PurchaseOrder by filtiring the PurchaseOrderdetail , this is my models.py class CustomerPurchaseOrder(models.Model): .... inputdate = models.DateTimeField(auto_now_add=True, verbose_name="OrderSubmittedDateTime") .... class CustomerPurchaseOrderDetail(models.Model): .... customer_Purchase_Order = models.ForeignKey(CustomerPurchaseOrder, on_delete=models.SET_NULL, null=True, blank=True, verbose_name="CustomerPurchaseOrder") this is my views.py allrelatedProduct = CustomerPurchaseOrderDetail.objects.filter(profile__in=client.values_list('id')).latest('customer_Purchase_Order__inputdate') this is the error i get 'CustomerPurchaseOrderDetail' object is not iterable my full traceback Template error: In template C:\Users\USER\Desktop\LastProject\OnlinePalengke\customAdmin\templates\customAdmin\clientAdmin.html, error at line 341 'CustomerPurchaseOrderDetail' object is not iterable 331 : <h1>My Account</h1> 332 : 333 : <div class="grid"> 334 : <div class="grid__item medium-up--two-thirds"> 335 : 336 : <div class="content-block"> 337 : 338 : <h2>Order History </h2> 339 : 340 : <div class="scrollable-container"> 341 : {% for history_product in allrelatedProduct %} 342 : 343 : <table class="responsive-table cart-table"> 344 : <thead class="cart__row visually-hidden"> 345 : <th colspan="2">Product</th> 346 : <th>Quantity</th> 347 : <th>Total</th> 348 : </thead> 349 : <tbody id="CartProducts"> 350 : <tr class="cart__row responsive-table__row"> 351 : <td class="cart__cell--image text-center"> Traceback: File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\exception.py" in inner 34. response = get_response(request) File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 115. response = self.process_exception_by_middleware(e, request) File "C:\Users\USER\AppData\Local\Programs\Python\Python37-32\lib\site-packages\django\core\handlers\base.py" in _get_response 113. response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\USER\Desktop\LastProject\OnlinePalengke\customAdmin\decorators.py" in wrapper_func 42. return … -
Django group by field and get all items related to that particular field
I'm using Django 3.1.1 and I've got a News model which has a field called source_name. class News(models.Model): title = models.CharField(max_length=350) content = RichTextField(blank=True, null=True) link = models.URLField(max_length=500, unique=True) # Source source_name = models.CharField(max_length=100) I want to group each news by source_name and for each source i want to get all the news. News(title='test',source_name='AAA',...) News(title='test-1',source_name='AAA',...) News(title='test-2',source_name='AAA',...) News(title='test-B',source_name='BBB',...) News(title='test-B1',source_name='BBB',...) In the html template I want to get the following output - AAA -test -test-1 -test-2 - BBB -test-B -test-B1 It would be so easy if I could the following loops: {% for source in source_names %} {{ source }} {% for news in source %} {{news.title}} {% endfor %} {% endfor %} How can I achieve the above descriped output in the django template? Thanks -
Django : NameError: name 'X' is not defined
I don't understand why ? this is my project urls : from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('account/', include('account.urls'), name=account), ] and this is my app urls: from django.urls import path from . import views urlpattern = [ path('signup/', views.SignUp.as_view(), name=SignUp), ] Error is : NameError: name 'SignUp' is not defined Have you an idea what's the problem ? Thanks for your answer :) -
Object of type User is not JSON serializable in DRF
I am customizing the API that I give when I send the get request. The following error occurred when the get request was sent after customizing the response value using GenericAPIView. traceback Traceback (most recent call last): File "C:\Users\kurak\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\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 145, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\handlers\base.py", line 143, in _get_response response = response.render() File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\template\response.py", line 105, in render self.content = self.rendered_content File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\response.py", line 70, in rendered_content ret = renderer.render(self.data, accepted_media_type, context) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\renderers.py", line 100, in render ret = json.dumps( File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\utils\json.py", line 25, in dumps return json.dumps(*args, **kwargs) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\json\__init__.py", line 234, in dumps return cls( File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 257, in iterencode return _iterencode(o, 0) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\site-packages\rest_framework\utils\encoders.py", line 67, in default return super().default(obj) File "C:\Users\kurak\AppData\Local\Programs\Python\Python38-32\lib\json\encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' TypeError: Object of type User is not JSON serializable What's problem in my code? I can't solve this error. Please help me. Here is my code. views.py class ReadPostView (GenericAPIView) : serializer_class = PostSerializer permission_classes = [IsAuthenticated] def get (self, serializer) : serializer = self.serializer_class() posts = Post.objects.all() data = … -
django when I save a model, a group is not assigned to it
when I save to a group is not assigned to the user. def save(self,*args, **kwargs): if self.is_active: group = Group.objects.get(name = 'test') self.groups.add(group) super().save(*args, **kwargs) -
Django admin panel performance degradation
I'm facing some performance issue in admin view of my site. I am using regular Dajngo's admin panel without any special plugins and yet, when I want to open User preview it takes around 30 seconds. When investigated a bit deeper with Django Debug Toolbar I found that single User preview page requires around 270 queries, in DB where there are only 23 users total. In users list view there is only 5 queries required. According to DjDT this huge number of queries is caused by number of queries looking like this: SELECT ••• FROM "django_content_type" WHERE "django_content_type"."id" = <some number> where <some number> can change. Moreover, I see that there are 77486 voluntary, 6742 involuntary context switches. Which I suppose is just crazy big number for so small number of users. I have slightly modified User model, in a way that it is now using email instead of integer value as primary key. Other than that I have added only one integer field and that's it. Does someone has an idea what can be done to improve the performance? -
Django Unique Constraint doesn't Work on creating unique project titles for each user
So I have this project where I have several supervisors that can create projects. I want that for each supervisor they can't make a project with the same title. I tried to use UniqueConstraint but now it's not working. Supervisors can still create a project with the same title. Note: Project's supervisor is automatically assigned to the project creator. models.py class Project(models.Model): title = models.CharField(max_length=100) due_date = models.DateField() due_time = models.TimeField() supervisor = models.ForeignKey(User, default=None, on_delete=models.SET_DEFAULT) class Meta: constraints = [models.UniqueConstraint(fields=['title', 'supervisor'], name="unique title")] verbose_name = "Project" def __str__(self): return str(self.title) + "-" + str(self.supervisor) forms.py class CreateProjects(forms.ModelForm): class Meta: model = models.Project fields = ['title', 'due_date', 'due_time'] widgets = { 'due_date': DateInput() } views.py @login_required(login_url="/signin") def create_project(response): if response.user.is_staff: if response.method == 'POST': form = forms.CreateProjects(response.POST, response.FILES) if form.is_valid(): # save project to db instance = form.save(commit=False) instance.supervisor = response.user print(instance.supervisor) instance.save() return redirect('/dashboard') else: form = forms.CreateProjects(initial={'supervisor': response.user}) ctx = {'form': form, 'FullName': response.user.get_full_name} else: form = "Only Teachers can create projects" ctx = {'form': form, 'FullName': response.user.get_full_name} return render(response, "create_project.html", ctx) -
my form.is _valid() function is returning False value in django . please check the below files to know more about the issue
Below is the code in models.py file it has some fields models.py from django.db import models class Measurement(models.Model): location = models.CharField(max_length=200) destination = models.CharField(max_length=200) distance = models.DecimalField(max_digits=10, decimal_places=2) created = models.DateTimeField(auto_now_add=True) def __str__(self): return f"distance from {self.location} to {self.destination} is {self.distance}" in views.py i am tryin to insert some data from the form into the table views.py from django.shortcuts import render, get_object_or_404 from .models import Measurement from .forms import MeasurementModelForm # Create your views here. def calculate_distance_view(request): obj = get_object_or_404(Measurement,id=2) form = MeasurementModelForm(request.POST or None) if form.is_valid(): print("valid") instance = form.save(commit=False) instance.destination = form.cleaned_data.get('destination') instance.location = 'san francisco' instance.distance = 5000.00 instance.save() else: print("not valid") print(form.errors) context = { 'distance' : obj, 'form' : form, } return render(request,'measurements/main.html', context) main.html {% extends 'base.html' %} {% block title %} calculate distance {% endblock title %} {% block content %} {{ distance }} <hr> <form action="" method="post" autocomplete="off"></form> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-primary" >confirm</button> </form> {% endblock content %} in the console it is prinnting blank for form.errors python console C:\Users\vishnu.vijaykumar\Desktop\src>python manage.py runserver Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). September 26, 2020 - 13:46:55 Django version 3.1.1, … -
Request.POST.get("amount") convert to float
I have this code in my html <input type="number" value="{{total|floatformat:'2'|intcomma}}" name="total"> it display on my browser " 1,071.00 " and when i tried to convert it to float inside my views.py views.py total = request.POST.get('total') totals = float(total) print(totals) I receive this error -
Filling in database of Django in development mode using multiple ports simultaneously
I am developing a Django project with Postgresql database. I need to scrape data from online resources and save into database while in development mode. Then, I will filter out irrelevant data for deployment and get a smaller-sized database. However, web-scraping and writing into the database is too slow (you can say the online resources are huge). I need to fill in the database faster while in development mode, using a local server. Is it possible/advisable to create multiple projects, using the same database and run them on multiple ports to fill in different sections of my database simultaneously?