Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
TypeError Error during template rendering
I'm facing this error when I add ForeignKeys in my Order table enter image description here Here are my tables enter image description here But when I remove the those ForeignKeys it works fine without giving an error... enter image description here enter image description here ...But I also can't access other tables enter image description here -
Getting None instead of Value from HTML form (Django)
Here below my HTML-template <form action="{% url 'test-data' %}" method="POST" name="test" enctype="multipart/form-data"> {% csrf_token %} <h2> {{ result }} </h2> <div class="d-flex justify-content-center"> <button type="submit" class="btn btn-primary">Show</button> </div> </form> my View.py def show_result(request): if request.method == "POST": result = request.POST.get('test') return HttpResponse(result) By pressing the button 'Show' I got None instead of {{ result }} value. So, how I can get a Value inside curly brackets? Thanks a lot for any help. -
Unable to POST data with the Django REST Framework : Not Found
I'm trying to figure out why the Django REST Framework throws a 404 Not Found when I POST data with the code below, because when I load the browsable API with the URL it correctly displays the object list with the HTML form to POST data. The Django project that serve the API run in a Docker container as well as the client, but in a separate Docker host. How could I fix the issue ? Server Console logs django-1 | Not Found: /api/strategy/target/ django-1 | [26/Sep/2022 14:27:05] "POST /api/strategy/target/ HTTP/1.1" 404 23 project/project/urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path("api/strategy/", include("strategy.urls")), ] strategy/urls.py from django.urls import path, include from rest_framework import routers from strategy.api.views import TargetViewSet router = routers.DefaultRouter() router.register("target", TargetViewSet, basename="targets-list") urlpatterns = [ path('', include(router.urls)), ] strategy/views.py from rest_framework import viewsets from strategy.api.serializers import TargetSerializer from rest_framework.decorators import permission_classes from rest_framework.permissions import IsAdminUser # Create new model @permission_classes([IsAdminUser]) class TargetViewSet(viewsets.ModelViewSet): serializer_class = TargetSerializer queryset = Target.objects.all() Client res = requests.post("http://1.2.3.4:8001/api/strategy/target/", data=data, headers={'Authorization': 'Bearer {0}'.format(token)} ) -
Django Integrity Error at /accounts/login/ 1364, "Field 'id' doesn't have a default value"
I get the Django error when clicking on log in. Unfortunately I don't know which table is causing the problem. My complete error: IntegrityError at /accounts/login/ (1364, "Field 'id' doesn't have a default value") Request Method: POST Request URL: http://127.0.0.1:8000/accounts/login/ Django Version: 4.0.6 Exception Type: IntegrityError Exception Value: (1364, "Field 'id' doesn't have a default value") Exception Location: c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\MySQLdb\connections.py, line 254, in query Python Executable: c:\xampp\htdocs\django\ksfexpert\env\Scripts\python.exe Python Version: 3.10.0 Python Path: ['C:\xampp\htdocs\django\ksfexpert\src', 'C:\Users\kit\AppData\Local\Programs\Python\Python310\python310.zip', 'C:\Users\kit\AppData\Local\Programs\Python\Python310\DLLs', 'C:\Users\kit\AppData\Local\Programs\Python\Python310\lib', 'C:\Users\kit\AppData\Local\Programs\Python\Python310', 'c:\xampp\htdocs\django\ksfexpert\env', 'c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages'] Server time: Mon, 26 Sep 2022 14:46:52 +0000 Traceback Switch to copy-and-paste view c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\django\db\backends\utils.py, line 89, in _execute return self.cursor.execute(sql, params) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\django\db\backends\mysql\base.py, line 75, in execute return self.cursor.execute(query, args) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\MySQLdb\cursors.py, line 206, in execute res = self._query(query) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\MySQLdb\cursors.py, line 319, in _query db.query(q) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\MySQLdb\connections.py, line 254, in query _mysql.connection.query(self, query) … Local vars The above exception ((1364, "Field 'id' doesn't have a default value")) was the direct cause of the following exception: c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\django\core\handlers\exception.py, line 55, in inner response = get_response(request) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\django\core\handlers\base.py, line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\django\views\generic\base.py, line 84, in view return self.dispatch(request, *args, **kwargs) … Local vars c:\xampp\htdocs\django\ksfexpert\env\lib\site-packages\django\utils\decorators.py, line … -
How İs it possible apply filtering to the imported data while using django-import-export package
By applying Form (not using Admin Panel) it is possible for users to import their data in xlsx format to the models practically. I have two models Task & Item. Each Task object has many Item objects in it. When it is intended to import a data file which includes mixed data, namely more than one tasks created by different user with their items, Django-import-export utility import all of them. But in some cases it is required to limit the import process by allowing the tasks which are created by the user itself and not whole task data. Can I overcome this issue by appling filter to data? def importData(request,pk): if request.method == 'POST': #query = Item.objects.filter(task_id = pk) item_resource = ItemResource() dataset = Dataset() new_items = request.FILES['importData'] imported_data = dataset.load(new_items.read(), format='xlsx') result = item_resource.import_data(dataset, dry_run=True) if not result.has_errors(): item_resource.import_data(dataset, dry_run=False) converted = str(pk) return HttpResponseRedirect('http://127.0.0.1:8000/'+'checklist/task/'+ converted + '/') else: return HttpResponse('Your Data is not Proper ! Please Try Again...') return render(request, 'checklist/import.html')enter code here class Task(models.Model): user = models.ForeignKey(User, verbose_name="Kullanıcı", on_delete=models.CASCADE, null=True, blank=True) title = models.CharField(verbose_name="Kontrol Listesi Başlığı", max_length=200) description = models.TextField(verbose_name="Açıklama", null=True, blank=True) complete = models.BooleanField(verbose_name="Tamamlandı mı?", default=False) created = models.DateTimeField(auto_now_add=True, verbose_name='Kayıt Tarihi') update_date = models.DateTimeField(auto_now=True, verbose_name='Son Güncelleme') … -
How to use your own database for user authentication [closed]
I'am have created database with user data: class Users(models.Model): login = models.CharField(max_length=32, blank=False, unique=True, verbose_name='Login') password = models.CharField(max_length=255, blank=False, verbose_name='Password') email = models.EmailField(max_length=255, unique=True, verbose_name='Email') balance = models.IntegerField(verbose_name='Balance', null=True) class Meta: verbose_name = 'Users' verbose_name_plural = 'Users' ordering = ['id'] def __str__(self): return self.login I wanna use this database for register and auth. But not default database by django. What should I do? -
AttributeError: 'FieldInstanceTracker' object has no attribute 'saved_data'
Problem with a post_save signal? class Book(models.Model): class = models.ForeignKey(Class, on_delete=models.CASCADE, null=False) library = models.ForeignKey(Library, on_delete=models.CASCADE, null=False) created_at = models.DateTimeField(auto_now_add=True) tracker = FieldTracker() def update_service(sender, instance, **kwargs): if not library.exists(): book.delete() post_save.connect(update_service, sender=Library) lib/python3.7/site-packages/model_utils/tracker.py in set_saved_fields(self, fields) 106 self.saved_data = self.current() 107 else: --> 108 self.saved_data.update(**self.current(fields=fields)) 109 110 # preventing mutable fields side effects AttributeError: 'FieldInstanceTracker' object has no attribute 'saved_data' -
AttributeError when attempting to get a value for field `country` on serializer
I'm running into the following error, and been stuck on it the last two weeks. I don't know what it could possibly mean by 'int' object has no attribute 'country' in my case, and country exists in my serializer and model. If I remove country from the serializer, I get the same error with post_code. I haven't got a clue what could be going wrong Got AttributeError when attempting to get a value for field `country` on serializer `AddressSerializer`. The serializer field might be named incorrectly and not match any attribute or key on the `int` instance. Original exception text was: 'int' object has no attribute 'country' View: class Address(generics.RetrieveUpdateDestroyAPIView): permission_classes = [AddressPermission] queryset = Addresses.objects.all() def get_object(self): try: if self.request.COOKIES['access_token'] is not None: obj = get_object_or_404(self.get_queryset(), user=NewUser.objects.get(id=jwt.decode(self.request.COOKIES['access_token'], settings.SECRET_KEY, algorithms=["HS256"])['user_id'])) self.check_object_permissions(self.request, obj) return obj except: return status.HTTP_401_UNAUTHORIZED serializer_class = AddressSerializer Serializer: class AddressSerializer(serializers.ModelSerializer): class Meta: fields = ('country', 'organization_name', 'administrative_area', 'sub_administrative_area', 'locality', 'post_code', 'thoroughfare', 'premise') model = Addresses Model: class Addresses(models.Model): country = models.CharField(max_length=2) organization_name = models.CharField(max_length=150, null=True, blank=True) # State/Province administrative_area = models.CharField(max_length=150, null=True, blank=True) # County/District/Municipality sub_administrative_area = models.CharField(max_length=150, null=True, blank=True) locality = models.CharField(max_length=150, null=True, blank=True) post_code = models.CharField(max_length=12) # the actual street address thoroughfare = models.CharField(max_length=95) # … -
Best practice to resolve Now() vs timezone.now() sync differences across databse and web workers?
I have a checkconstraint on a django model, applied on a PostgreSQL database: from django.db import models from django.db.models import CheckConstraint, Q, F from django.db.models.functions import Now class Event(models.Model): mydate = models.DatetimeField() class Meta: constraints = [ CheckConstraint( check = Q(mydate__lte=Now()), name = 'check_my_date', ), ] The constraint ensures that mydate can not be in the future, but constraining it to be less than Now() which returns the start of the transaction time on the PostgreSQL server. I set mydate programmatically in the app: from django.utils import timezone now = timezone.now() myevent = Event.objects.create(mydate=now) However, this will often fail the checkconstraint. I assume this is because the setup I am using is Heroku, with a separate PostgreSQL and worker (app) instance. The PostgreSQL Now() timestamp appears to run a few seconds behind the web worker. What is best practice to sync/resolve this conflict? -
How to properly prefetch_related in django
One query is more than 10 times faster than the other, it looks like prefetch_related has no effect. How to do it correctly? # 400ms test = PZItem.objects.all().aggregate(Sum('quantity')) # 4000ms test = PZ.objects.prefetch_related('pzitem_set').aggregate(Sum('pzitem__quantity')) -
Need Help in django form widgets
I am in a middle of a project. I need help in using widgets. I have a Model for which i want a model form : My model is : class Appointments(models.Model): doctor = models.ForeignKey(Doctor, on_delete=models.CASCADE) patient = models.ForeignKey(Patient, on_delete=models.CASCADE) app_time = models.DateTimeField() diognoses = models.TextField(max_length=1000, null=True, blank=True) prescriptions = models.TextField(max_length=250, null=True, blank=True) class Meta: unique_together = ('doctor', 'patient', 'app_time') def __str__(self): st = str(self.patient.user.name)+str(self.doctor.user.name) return st The corresponding model form is : class AppointmentBookForm(forms.ModelForm): app_time = forms.DateTimeField(widget=forms.SplitDateTimeWidget()) class Meta: model = Appointments fields = ['doctor','app_time'] Now for app_time I have split the date and time field which is already working fine. Now I want a dropdown for date and a suitable widget for time. The time should contain only hours and minutes. And Finally I also want to provide the options for timing depending on the date and doctor. -
SQLite to PostgreSQL Transfer - Connection Refused: Is the server running on that host and accepting TCP/IP connections?
Goal: Be able to solve for "Is the server running on that host and accepting TCP/IP connections?" error message. I have recently moved my Django database from SQLite to PostgreSQL following the steps on this link. When I run python manage.py runserver, I have no problems. I am launching the site through Heroku via GitHub, which deploys successfully. When I clicked on the Heroku site, I initially got a 500 error, which when I turned Debug = True, I received the following headline message: Exception Type: OperationalError at / Exception Value: connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused Is the server running on that host and accepting TCP/IP connections? The port of 5432 is correct. From what I have read, the issue comes from listen_addresses needing to be * but I cannot find this file on my Mac. I tried changing "Host name / address" to "*" from "localhost" in pgAdmin4 - this did not work. Full excerpt below: Environment: Request Method: GET Request URL: https://sherbert.herokuapp.com/ Django Version: 4.1.1 Python Version: 3.10.6 Installed Applications: ['posts', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'whitenoise.runserver_nostatic', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Template error: In template … -
How to upload image from request.POST in django
I have a class 'product' with a field Imagefield called 'image'. I want to make an upload form for change the image. product.image= request.POST.get('image',product.image) In this mode, i'm able to change the image with a new one, but if i don't want to change it, the image uploaded before doesn't exists anymore. In the db, the field 'image' is empty. def update_product(request,id): templ="products/update_product.html" ctx={} product= Product.objects.get(id=id) if product.type == "computer": computer= Computer.objects.get(product_id=id) ctx={ "prodotto":product, "computer":computer} if product.type == "smartphone": smartphone= Smartphone.objects.get(product_id=id) ctx={ "prodotto":product, "smartphone":smartphone} if request.method=="POST": product.image = request.FILES.get('image',product.image) product.name= request.POST.get('name',product.name) product.product_code=request.POST.get('product_code',product.product_code) product.productor=request.POST.get('productor',product.productor) product.color=request.POST.get('color',product.color) product.size=request.POST.get('size',product.size) product.weight=request.POST.get('weight',product.weight) product.price= request.POST.get('price',product.price) quantity= int(request.POST.get('quantity',product.quantity)) if quantity>0: product.available=True else: product.available=False product.quantity=quantity product.save() if product.type == "computer": computer.display_size=request.POST.get('display_size',computer.display_size) computer.display_resolution=request.POST.get('display_resolution',computer.display_resolution) computer.cpu=request.POST.get('cpu',computer.cpu) computer.ram=request.POST.get('ram',computer.ram) computer.disk_size=request.POST.get('disk_size',computer.disk_size) computer.disk_type=request.POST.get('disk_type',computer.disk_type) computer.operating_system=request.POST.get('operating_system',computer.operating_system) computer.graphic_card=request.POST.get('graphic_card',computer.graphic_card) computer.battery_autonomy=request.POST.get('battery_autonomy',computer.battery_autonomy) computer.additional_function=request.POST.get('additional_function',computer.additional_function) computer.save() if product.type =="smartphone": smartphone.display_size=request.POST.get('display_size',smartphone.display_size) smartphone.cpu=request.POST.get('cpu',smartphone.cpu) smartphone.ram=request.POST.get('ram',smartphone.ram) smartphone.disk_size=request.POST.get('disk_size',smartphone.disk_size) smartphone.operating_system=request.POST.get('operating_system',smartphone.operating_system) smartphone.battery_autonomy=request.POST.get('battery_autonomy',smartphone.battery_autonomy) smartphone.camera= request.POST.get('camera',smartphone.camera) smartphone.additional_function=request.POST.get('additional_function',smartphone.additional_function) smartphone.save() return redirect('home') return render(request,template_name=templ,context=ctx) -
How I can implement this logic in Django where seller user can only sale products and buyer can only buy product?
I have scenario in which seller can only sale products while buyer can only buyer products I am new in Django I have no idea how can i implement this logic? -
Django template doesn't display dictionary elements
I have a dictionary named Rooms. I am sending the dictionary elements to home.html Views.py from django.shortcuts import render # Create your views here. rooms = [ {'id': 1, 'name': 'Lets learn Python!'}, {'id': 2, 'name': 'Front-End Developer'}, {'id': 3, 'name': 'Back-End Developer '}, ] def home(request): context = {'rooms': rooms} return render(request, 'base/home.html', context) def rooms(request, pk): room = None for i in rooms: if i['id'] == int(pk): room = i context = {'room': room} return render(request, 'base/room.html', context) home.html {% extends 'main.html' %} {% block content %} <h1>Home Template</h1> <div> <div> {% for room in rooms %} <div> <h5>{{room.id}} -- <a href="/room/{{room.id}}">{{room.name}}</a></h5> </div> {% endfor %} </div> </div> {% endblock content %} Home.html displays <h5> text but does not display the dictionary elements.I have tried renaming context variable. -
Django queryset: annotate with calculated value
I am making a very simple notification system for my website, powered by a Django REST Framework API. It's for sending website updates and things to all users, everyone gets the same notifications, and they can then mark it as read / archive it. I have come up with the following model: class Notification(models.Model): title = models.CharField(max_length=255) text = models.TextField() type = models.CharField(max_length=255, blank=True) read_by = models.ManyToManyField(User, blank=True, related_name="read_notifications") archived_by = models.ManyToManyField(User, blank=True, related_name="archived_notifications") created_at = models.DateTimeField(auto_now_add=True, db_index=True) updated_at = models.DateTimeField(auto_now=True) So there is no receiver field or something like that, as all users get all notifications anyway. Now I am trying to write the view logic, notably the following 2 things: only fetch non-archived notifications made after the user was created, and add a calculated "is_read" field to it, in a way that doesn't do extra queries for every single notification / user combination. The query looks like this now: queryset = Notification.objects .order_by("-created_at") .filter(created_at__gt=self.request.user.created_at) .exclude(archived_by=self.request.user) This does indeed filter out archived queries as expected, and I think it's doing it without an extra query for every notification: SELECT "notifications_notification"."id", "notifications_notification"."title", "notifications_notification"."text", "notifications_notification"."type", "notifications_notification"."created_at", "notifications_notification"."updated_at" FROM "notifications_notification" WHERE ("notifications_notification"."created_at" > 2022-09-26 12:44:04.771961+00:00 AND NOT (EXISTS(SELECT 1 AS "a" FROM … -
Overwriting save method to create entry in related table automatically django
After registration email with email confirmation is sent to a new user. I created model UserWithConfirmation with new field is_email_confirmed. I was following this https://docs.djangoproject.com/en/4.1/topics/auth/customizing/#extending-the-existing-user-model. I want to have UserWithConfirmation created for each new user when user is saved. For now I have sth like this. from django.db import models from django.contrib.auth.models import User class UserWithConfirmation(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, related_name="user_with_confirmation") is_email_confirmed = models.BooleanField(default=False) def __str__(self): return self.user.username class User: def save(self, *args, **kwargs): super().save(*args, **kwargs) create_user_with_confirmation(User) def create_user_with_confirmation(user): UserWithConfirmation(user=user) UserWithConfirmation.save() How to make it works? -
django REST framework - AttributeError: 'ResetPasswordRequestSerializer' object has no attribute 'id'?
I am trying to set-up RequestPasswordResetAPI endpoint. # Serializer class ResetPasswordRequestSerializer(serializers.Serializer): email = serializers.EmailField(min_length=2) class Meta: fields = ['email'] def validate(self, data): print(data) # Check if email exists if data.get('email', ''): try: # Get the user user = User.objects.get(email=data.get('email', '')) print(f"User from validate {user}") return user except: print('exception') raise serializers.ValidationError("Email is not registered") raise serializers.ValidationError("Email is not registered") api.py class ResetPasswordRequesAPI(generics.GenericAPIView): serializer_class = ResetPasswordRequestSerializer def post(self, request, *args, **kwargs): print('make request') serializer = self.get_serializer(data=request.data) print('first line done') serializer.is_valid(raise_exception=True) # user = serializer.save() user = serializer.validated_data print(user) user = ResetPasswordRequestSerializer( user, context=self.get_serializer_context()) print(f"user is {user}") uidb64 = urlsafe_base64_encode(user.id) token = PasswordResetTokenGenerator().make_token(user) print(f"second user is {user}") print(token) At the uidb64 = urlsafe_base64_encode(user.id) I get: AttributeError: 'ResetPasswordRequestSerializer' object has no attribute 'id' When I look at the output of various print(user) statements I have added all over: user: ResetPasswordRequestSerializer(<User: john>, context={'request': <rest_framework.request.Request: POST '/api/auth/reset_password/'>, 'format': None, 'view': <accounts.api.ResetPasswordRequesAPI object>}) Trying to understand why: # In serializer user = User.objects.get(email=data.get('email', '')) Is only giving the User without id and other fields. When I try to generate token for reset I get more AttributeErrors. -
Specifying view function in Django
I'm practicing in Django and I want to know how requests and view mechanisms work correct in Django. I started an app called ghcrawler in my django project. I designed like it has to send responses that recevied from localhost/ghcrawler and localhost/ghcrawler/results So this is the urls.py in ghcrawler/ app folder. from django.urls import path, include from .views import main_view, results_view urlpatterns = [ path('', main_view.as_view() , name='ghcrawler'), path('ghresults', results_view.as_view(), name='getresults') ] localhost/grcrawler page works well as expected. I just want to wire the requests coming to localhost/ghcrawler/results to getresults() function in results_view class defined in views.py, however it doesn't even write the 'h1' to the console ghcrawler/views.py: from django.views.generic import TemplateView from django.shortcuts import render from django import forms from django.http import HttpResponse from .github_requester import search_user class main_view(TemplateView): template_name = 'ghcrawler.html' # Handle the post request received from /ghcrawler/ def post(self, request, *args, **kwargs): if request.method == 'POST': user = search_user(request.POST.get("username", "")) if user == None: print("User not found.") else: print(user) return HttpResponse("OK") class results_view(TemplateView): template_name = 'ghresults.html' def getresults(self, request, *args, **kwargs): print('h1') -
Exception Type: OperationalError at /admin/firstapp/employee/ Exception Value: no such column: firstapp_employee.user_id
Hi i'm new to django & was trying to migrate my model when i received this error.Any suggestions? this is my models.py (i'm trying to create one to one relationship b/w user & Employee model) from django.db import models from django.contrib.auth.models import User # Create your models here. class Employee(models.Model): First_Name = models.CharField(max_length=200,blank=False,null=False) Last_Name = models.CharField(max_length=200) DOB = models.DateField() Primary_skill=models.TextField(max_length=1000) user = models.OneToOneField(User,on_delete=models.CASCADE,default='') def __str__(self): return self.First_Name -
Call django context_processor without request as normal function
I have a model and when I create a new record it must send a signal to the context_processor to display a popup in the Django admin site telling the user that there is a new record in that model that has been created. -
How to change the value stored in name based on previous input from user in html?
Good day. I am building a website using python django. I am trying to change a value in a table in the database containing student marks based on the student number(row) and assignment name(column). I have a function in views.py that uses if else statements to change the value which works fine as long the name="A1" is fixed to A1 (in the html code below) or fixed to any other assignment name but I have multiple assignment names ranging from A1 to A6. I would would like to change the value of name based on what assignment the user selects the html code: <h1>Fill in student assignment marks below</h1> <form action= "" method="POST">{% csrf_token %} <input type="text" class="field" placeholder="student ID" name="student"> <label for="name">Choose an Assignment:</label> <select name="name" id="name"> <option value="A1">A1</option> <option value="A2">A2</option> <option value="A3">A3</option> <option value="A4">A4</option> <option value="A5">A5</option> <option value="A6">A6</option> </select> <input type="text" class="field" placeholder="percentage" name="A1"> <button type="submit" class="btn">save</button> </form> The following is the view.py function to update the table: def upload_A_marks(request): if request.method == 'POST': student = request.POST['student'] name = request.POST['name'] print(name) if name == 'A1': A1 = request.POST["A1"] new_Amark = MarksTable.objects.get(student=student) new_Amark.A1 = A1 new_Amark.save() if name == 'A2': A2 = request.POST["A2"] new_Amark = MarksTable.objects.get(student=student) new_Amark.A2 = A2 … -
Apache2 not redirecting non-www request to www
I am trying to redirect my all non-www requests to www. Here is my apache config setting. RewriteEngine on RewriteCond %{SERVER_NAME} =example.com [OR] RewriteCond %{SERVER_NAME} =www.example.com RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] -
whenever i click on add more button only first data is storing into database [closed]
<input type="text" name="quantity" id="quantity" placeholder="QUANTITY"> <!-- <label for="phone">phone</label><br> --> <!-- <input type="text" name="phone" id="quantity-type" style="width:180px;"> --> <select name="quantity_type" id="quantityType"> <option value="kg">Kg</option> <option value="ton">Ton</option> <option value="peices">No's</option> </select> </div> <div> <select name="brand_name" id="brand_name" class="brand_name" onChange="check(this);"> <option value="Shyam Steel Industries Ltd.">Shyam Steel Industries Ltd.</option> <option value="JSW ( Jindal South West ) Steel Ltd.">JSW ( Jindal South West ) Steel Ltd.</option> <option value="Tata Steel Ltd.">Tata Steel Ltd.</option> <option value="Steel Authority of India (SAIL)">Steel Authority of India (SAIL)</option> <option value="Essar Steel Ltd.">Essar Steel Ltd.</option> <option value="Jindal Steel and Power Ltd.">Jindal Steel and Power Ltd.</option> <option value="VISA Steel">VISA Steel</option> <option value="SRMB Steel">SRMB Steel</option> <option value="Electro Steel">Electro Steel</option> <option value="MESCO Steel">MESCO Steel</option> <option value="Kamdhenu Steel">Kamdhenu Steel</option> <option value="Rathi">Rathi</option> <option>others</option> </select> <input id="other-div" name="brand_name" style="display:none;" placeholder="Enter Brand Name*"> <button class="addNewProd" id="addNewProd" type="button">+Add more</button> <div id="newProduct"></div> </div> </div> </div> enter image description here function addHtml(event) { console.log(event.target) let parentDiv = event.target.parentElement; console.log(parentDiv) count += 1; console.log(count) let html = `<div id="prodcount-${count}"> <select name="materials" id="prodVariety">{% for m in material_data %}<option value="{{m.variety_name}}">{{m.variety_name}}</option>{% endfor %}</select><br><input type="text" name="phone" id="quantity" placeholder="QUANTITY"><select name="quantity_type" id="quantityType" ><option value="ton">Ton</option><option value="cft">CFT</option><option value="kg">KG</option></select><br><select name="brand_name" id="brand_name" onChange="check2(this);"> <option value="Shyam Steel Industries Ltd.">Shyam Steel Industries Ltd.</option> <option value="JSW ( Jindal South West ) Steel Ltd.">JSW ( Jindal South West ) Steel Ltd.</option> … -
Des the django queryset annotation performs before slicing
I basically wanted to know, the order of execution for Django queryset actions annotation and slicing. Let Books is a model with around 1000 values in it. some_books = Books.objects.annotate( test_field=some-actions.... ).filter( some-other-filters )[:100] When I perform the above query, would the annotation of test_field will perform only for 100(sliced) objects or it will perform for all the objects matching with filters and then do the slicing?