Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django complexity of one-to-one field reverse lookup
Reverse lookup of foreign key fields takes log(n) time as stated in this question. complexity of a reverse django foreign key lookup What is the complexity of reverse lookup of one-to-one field? -
Duplicate object with django-hitcount
I want to duplicate my current object with its values. So, I need to copy all of its old values to the new object. Duplication of all old values I implemented well, but I can't make hits (views) that are created with django-hitcount. I tried to do different options, but it doesn't work. Could you please give me advice on how to build it? models.py class Blog(models.Model, HitCountMixin): slug = models.SlugField() name = models.CharField() author = models.ForeignKey( "users.CustomUser", on_delete=models.SET_NULL, null=True, blank=True, ) content = models.TextField(blank=True, null=True) bookmarkscount = models.IntegerField(null=True, blank=True, default=0) downloadscount = models.IntegerField(null=True, blank=True, default=0) hit_count_generic = GenericRelation( HitCount, object_id_field="object_pk", related_query_name="hit_count_generic_relation", ) hitcount.models.py from datetime import timedelta from django.db import models from django.conf import settings from django.db.models import F from django.utils import timezone from django.dispatch import receiver from django.contrib.contenttypes.fields import GenericForeignKey from django.contrib.contenttypes.models import ContentType from django.utils.translation import gettext_lazy as _ from etc.toolbox import get_model_class_from_string AUTH_USER_MODEL = getattr(settings, 'AUTH_USER_MODEL', 'auth.User') from .managers import HitCountManager, HitManager from .settings import MODEL_HITCOUNT from .signals import delete_hit_count @receiver(delete_hit_count) def delete_hit_count_handler(sender, instance, save_hitcount=False, **kwargs): """ Custom callback for the Hit.delete() method. Hit.delete(): removes the hit from the associated HitCount object. Hit.delete(save_hitcount=True): preserves the hit for the associated HitCount object. """ if not save_hitcount: instance.hitcount.decrease() … -
Missing 'path' argument in get() call
I am trying to test my views in Django, and when I run this i get the error from django.test import TestCase, Client from django.urls import reverse from foodsystem_app.models import discount,menu import json class TestViews(TestCase): def test_login_GET(self): client = Client response = client.get(reverse('login')) self.assertEquals(response.status_code,200) self.assertTemplateUsed(response,'foodsystem/login.html') response = client.get(reverse('login')) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^ TypeError: Client.get() missing 1 required positional argument: 'path' ---------------------------------------------------------------------- Ran 4 tests in 0.005s FAILED (errors=1) I'm not sure what I am supposed to pass as the path name. This is the code for what I am testing def login_request(request): if request.method == "POST": form = AuthenticationForm(request, data=request.POST) if form.is_valid(): username = form.cleaned_data.get('username') password = form.cleaned_data.get('password') user = authenticate(username=username, password=password) if user is not None: login(request, user) messages.info(request, f"You are now logged in as {username}.") return redirect("main:homepage") else: messages.error(request,"Invalid username or password.") else: messages.error(request,"Invalid username or password.") form = AuthenticationForm() return render(request=request, template_name="login.html", context={"login_form":form}) -
Getting (2006, 'MySQL server has gone away error) in kafka consumer in my django application
I recently written a kafka consumer in my django project which is running in the background and there's a mysql query which reads inside the consumer and the process is very light as I don't have that much of data. But I'm getting (2006, 'MySQL server has gone away) and I'm not getting why exactly it's happening and what's the solution for this? Any leads or solution for this would be highly appreciated. The below is my code:- `def job_listener(): listener = KafkaConsumer(topic, group_id=group_id, bootstrap_servers=settings.KAFKA_BOOTSTRAP_SERVERS, auto_offset_reset=settings.KAFKA_AUTO_OFFSET_RESET, enable_auto_commit=settings.KAFKA_ENABLE_AUTO_COMMIT) for message in listener: try: data = json.loads(message.value) logger.info("Data Received {}".format(data)) except Exception as e: data = None logger.error("Failed to parse the message with exception {}".format(e)) if data is not None: try: Job.objects.get(pk=data['id'] except ObjectDoesNotExist: logger.error("Keyword doesn't exist with data {}".format(data)) listener.commit({TopicPartition(topic, message.partition): OffsetAndMetadata(message.offset+1, '')}) except Exception as e: logger.error( "Failed to read data {} with exception {}".format(data, e)) listener.seek(TopicPartition(topic, message.partition), message.offset)` -
how to pass a context variable from a variable inside of an if statement?
Inside of an if statement I've check_order that I need to have as a context variable for my template, I'm getting this traceback: local variable 'check_order' referenced before assignment. How do I have it as a context variable without having to repeat the code to have it outside of the if statement? View if request.method == "POST": if request.user.is_authenticated: customer = request.user.customer check_order = OrderItem.objects.filter(order__customer=customer) if check_order: if form.is_valid(): #does logic else: messages.error(request, f"Failed") else: return redirect() context = {"check_order": check_order} -
Specific User permissions in Django
I need to make only TL and HR approve permissions for leave. how to achieve it in Django Rest framework? since am a newbie i find this scenario challenging. Help me out Techies This is my User model class User(AbstractBaseUser): email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=150, unique=True) name = models.CharField(max_length=150, blank=True) is_admin = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_HR = models.BooleanField(default=False) is_TL = models.BooleanField(default=False) updated_at = models.DateTimeField(auto_now=True) created_at = models.DateTimeField(auto_now_add=True) This is my leave request model. class Leave(models.Model): leave_type = models.CharField(max_length=50) employee = models.ForeignKey(UserDetails, on_delete=models.CASCADE) manager = models.CharField(max_length=50) applied_on = DateTimeField(auto_now_add=True) from_date = DateField() to_date = DateField() number_of_days = IntegerField() purpose = models.CharField(max_length=100) status = models.CharField(max_length=50, choices=( ('Pending', 'Pending'), ('Approved', 'Approved'), ('Rejected', 'Rejected') ),default='Pending') waiting_approval = models.BooleanField(default=True) TL_approved = models.BooleanField(default=False) TL_rejected = models.BooleanField(default=False) def approve(self): self.manager_approved = not self.manager_approved self.manager_rejected = not self.manager_rejected This is my views class LeaveManagerApproveView(APIView): def post(self, request): leave_id = request.data.get('leave_id') leave = Leave.objects.get(id=leave_id) leave.waiting_approval = False leave.manager_approved = True leave.status = 'Approved' leave.save() return Response({'successMessage': 'Leave Approved Successfully'}) In my views, i need only Hr or TL should approve or reject it? How to rock it? -
Django - Plesk - Centos7 - Apache
I have a rest-django project. The project uses plesk panel, centos 7 and apache. When I run my project, I get a python error. my site api.iyziwell.com print: #!/usr/bin/env python """Django's command-line utility for administrative tasks.""" import os import sys def main(): """Run administrative tasks.""" os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'iyziwell.settings') try: from django.core.management import execute_from_command_line except ImportError as exc: raise ImportError( "Couldn't import Django. Are you sure it's installed and " "available on your PYTHONPATH environment variable? Did you " "forget to activate a virtual environment?" ) from exc execute_from_command_line(sys.argv) if name == 'main': main() Please help me. -
Unable to load the custom template tags in django
templatetags : myapp_extras.py from django import template register = template.Library() @register.simple_tag def my_url(value,field_name,urlencode=None): url = '?{}={}'.format(field_name,value) if urlencode: querystring = urlencode.split('&') filtered_querystring = filter(lambda p:p.split('=')[0]!=field_name,querystring) encoded_querystring = '&'.join(filtered_querystring) url = '{}&{}'.format(url,encoded_querystring) return url home.html {% load myapp_extras %} . . . <div class="pagination"> <span class="step-links"> {% if page_obj.has_previous %} <a href="{% my_url 1 'page' request.GET.urlencode%}">&laquo; first</a> <a href="{% my_url page_obj.previous_page_number 'page' request.GET.urlencode%}">previous</a> {% endif %} <span class="current"> Page {{ page_obj.number }} of {{ page_obj.paginator.num_pages }}. </span> {% if page_obj.has_next %} <a href="{% my_url page_obj.next_page_number 'page' request.GET.urlencode%}">next</a> <a href="{% my_url page_obj.paginator.num_pages 'page' request.GET.urlencode%}">last &raquo;</a> {% endif %} </span> </div> settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'facligoapp' ] views.py def do_paginator(get_records_by_date,request): paginator = Paginator(get_records_by_date,10) page_number = request.GET.get('page', 1) try: page_obj = paginator.get_page(page_number) except PageNotAnInteger: page_obj = paginator.page(1) except EmptyPage: page_obj = paginator.page(paginator.num_pages) return page_obj : : if new_records_check_box_status is None and error_records_check_box_status is None: get_records_by_date = Scrapper.objects.filter(start_time__date__range=(f_date, t_date)) get_records_by_date = check_drop_down_status(get_records_by_date,drop_down_status) get_records_by_date = do_paginator(get_records_by_date,request) Based on the my templates tags when I filter the datas the url should change. But the url is not changing and template tags is not working. I had created the init.py in template tags also. Is there any solution to change the structure … -
Djagno User token is not passed in HTTP request header:-
I have created a login api using token based authentication in django rest framework.....API works fine in local setup.....But after committing the code on live server. Login done successfully but after passing that login token in headers. user is not permissible to open the next page. Here is my code:- 1) Login function @api_view(["POST"]) @permission_classes((AllowAny,)) def login(request): account = request.data.get("account") username = request.data.get("username") password = request.data.get("password") all_subs = [] for i in Subscriber.objects.all(): all_subs.append(i.username) if account in all_subs: connect_to_db(database=account) set_db_connection(account) try: if '@' in username: user = User.objects.using(account).get(email=username) else: user = User.objects.using(account).get(username=username) except: return Response({'error':'Invalid Credential'}, status=HTTP_400_BAD_REQUEST) if user.check_password(password): token, _ = Token.objects.using(account).get_or_create(user=user) user_data = User.objects.using(account).get(id=token.user_id) serializer = UserSerializer(user_data) return Response({'data': serializer.data,'token': token.key}, status=HTTP_200_OK) else: return Response({'error':'Invalid Credential'}, status=HTTP_400_BAD_REQUEST) elif account == "enggforms": try: if '@' in username: user = User.objects.get(email=username) else: user = User.objects.get(username=username) except: return Response({'error':'Invalid Credential'}, status=HTTP_400_BAD_REQUEST) if user.check_password(password): token, _ = Token.objects.get_or_create(user=user) user_data = User.objects.get(id=token.user_id) serializer = UserSerializer(user_data) return Response({'data': serializer.data,'token': token.key}, status=HTTP_200_OK) else: return Response({'error':'Invalid Credential'}, status=HTTP_400_BAD_REQUEST) else: return Response({'error':'Invalid Credential'}, status=HTTP_400_BAD_REQUEST) if username is None : return Response({'error': 'Please provide username'}, status=HTTP_400_BAD_REQUEST) elif password is None: return Response({'error': 'Please provide password'}, status=HTTP_400_BAD_REQUEST) elif account is None: return Response({'error': 'Please provide account name'}, status=HTTP_400_BAD_REQUEST) if … -
Django - AppRegistryNotReady("Models aren't loaded yet.") using cities_light library
I have installed the cities_light library in Django and populated the db with the cities as instructed in the docs. I added the app in INSTALLED_APPS and I have been able to pull the data in this simple view. All cities load as expected: def index(request): cities = City.objects.all() context = { 'cities': cities } return render(request,'templates/index.html',context) However, I am trying to create a model which has City as a foreign key, but when I run the app or try to make the migrations I get 'django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.'. from cities_light.admin import City from django.db import models class Home(models.Model): location = models.ForeignKey(City, on_delete=models.CASCADE) I suspect I might need to override the model. Would that be the case? -
How to Display the data on webpage with a search option (search by valid resource number) and use below API details for data fetching
API Details: API Reference:* https://stat.ripe.net/docs/02.data-api/announced-prefixes.html* Method: GET Origin Url: https://stat.ripe.net/data/announced-prefixes/data.json?resource= Example URL: https://stat.ripe.net/data/announced- prefixes/data.json?resource=4007 Note: The bold value will be the user’s input from the search field. Data Output format in webpage: (https://i.stack.imgur.com/x7Qsk.png) Some valid resources number (ASN) are as below. 4007 17501 9238 141177 23752 By using python/django framework please help me. I have no knowledge about how to fetch data using API. -
Django session variable change in UI everytime when new request_id is created
I want to request id differ in every page data, same as request id is in available in approve_url . index function send session variable approve_url in test function. Here is index function global j, k, approve_url @api_view(['POST', 'GET']) def index(request): # j = '' # approve_url = '' if request.method == "POST": form = InputForm(request.POST) if form.is_valid(): form.save() try: ids = form.cleaned_data['git_Id'] print(ids) obj = sql() query = f""" SELECT request_id FROM request_form_db.request_form_mymodel where git_Id= '{ids}' ; """ print(query) p = obj.fetch_query(query) print("Query Result", p) for i in p: print("Result[0] : ", i[0]) print("Result : ", p) i = i[0] j = i approve_url = f"http://127.0.0.1:8000/form/test?request_id={i}" print("Url : ", approve_url) try: send_mail( 'KSA Test Activation', approve_url, 'Noreplygcontrol@airlinq.com', ['sorav.parmar@airlinq.com'], fail_silently=False, ) except Exception as e: print("Error : ", e) except Exception as e: print("Error : ", e) request.session['ids'] = ids request.session['approve_url'] = approve_url print('Request ID Sent : ', ids) print('Approve Url Sent : ', approve_url) form = InputForm() else: form = InputForm() return render(request, 'home.html', {'form': form}) Here is test function where approve_url getting from session variable and put into UI, but res value change in previous data as well.Its not same as request_id in approve_url. the latest request id … -
Django makemigrations in production?
I'm new to Django but one concern I'm running into is whether running makemigrations as part of the production deployment process is safe/deterministic? The main reason is some 3rd party apps will create new migrations beyond the pre-defined ones, i.e. hordak for example, when a new currency is added via CURRENCIES in settings.py. Since a currency can be added anytime later and these are part of an 3rd party app the migrations are not checked in to the repo. This requires makemigrations to be run on deploy? This seems dangerous since there will be untraceable changes to the DB? Is a way to explicitly check-in to the repo 3rd party migrations? -
Css static in html use django, css no show out
main.html add {% load static %} at top and {% static 'css/main.css' %} in link css href {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>CM1</title> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-rbsA2VBKQhggwzxH7pPCaAqO46MgnOM80zW1RWuH61DGLwZJEdK2Kadq2F9CUG65" crossorigin="anonymous"> <link rel="stylesheet" type="test/css" href="{% static 'css/main.css' %}"> </head> <body> {% include "accounts/navbar.html" %} {% block content %} {% endblock content %} <hr> <h5>Our footer</h5> </body> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/js/bootstrap.bundle.min.js" integrity="sha384-kenU1KFdBIe4zVF0s0G1M5b4hcpxyD9F7jL+jjXkk+Q2h455rYXK/7HAuoJl+0I4" crossorigin="anonymous"></script> </html> **setting.py code so longer, i just skip to important things, the STATICFILES_DIRS bracket is () or [] ** import os INSTALLED_APPS = [ ... 'django.contrib.staticfiles', #<-- already have ... ] STATIC_URL = 'static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static/"), ) -
Django/Python - AssertionError: Class ThreadSerializer missing "Meta.model" attribute
Blockquote I've been trying to build the backend of a forum board for a mobile application and I've been running into an issue when trying to test the API endpoints over Postman. It says that the my ThreadSerializer class is missing the "Meta.model" attribute. My serializer code ` from rest_framework import serializers from forum.models import Thread from forum.models import Post class ThreadSerializer(serializers.ModelSerializer): class Meta: Thread_Model = Thread Thread_Fields = ['id', 'thread_id', 'title', 'desc', 'created_at'] class PostSerializer(serializers.ModelSerializer): class Meta: Post_Model = Post Post_Fields = ['id', 'post_id', 'post_content', 'post_time', 'thread_id'] Model code --- from django.db import models from django.conf import settings from Authentication.models import User # Create your models here. class Thread(models.Model): userid = models.ForeignKey(User, on_delete=models.CASCADE) thread_id = models.AutoField(primary_key=True) title = models.CharField(max_length=100) desc = models.TextField() created_at = models.DateTimeField(auto_now_add=True) class Post(models.Model): userid = models.ForeignKey(User, on_delete=models.CASCADE) thread_id = models.ForeignKey(Thread, on_delete=models.CASCADE) post_id = models.AutoField(primary_key=True) post_content = models.TextField() post_time = models.DateTimeField(auto_now_add=True) ` Any advice on how to fix this? This is the error I got on VSC and Postman. -
Django test connection strings with django-environ
At the moment we are using django-environ to store a database connection string. We are using mssql-django to connect to a Microsoft SQL Server database. Test database connection strings require more parameters - so is there a simple way to store an entire connection for a particular environment - ala test? Or perhaps a better approach? Project Code This project uses the django-environ to load a connection string from a .env file for a particular environment within a single settings.py file. This is specified by environment setting ENVIRONMENT_FILE. environments/dev.env DATABASE_URL=mssql://localhost:1433/ACME_APP_DB settings.py import environ environ.Env.DB_SCHEMES['mssql'] = 'mssql' env = environ.Env( DEBUG=(bool, False) ) BASE_DIR = Path(__file__).resolve().parent.parent ENVIRONMENT_DIR = os.path.join(BASE_DIR, "environments") ENVIRONMENT_FILE = os.environ.get("ENVIRONMENT_FILE", default=".env") ENVIRONMENT_FILE_FULL_PATH = os.path.join(ENVIRONMENT_DIR, ENVIRONMENT_FILE) root = environ.Path(__file__) - 3 environ.Env.read_env(ENVIRONMENT_FILE_FULL_PATH) env = environ.Env() DATABASES = { "default": env.db_url(), } This allows us to specify the environment for either dev or prod. We don't have any tests at the moment. Having investigated this - the alternative below allows a test database to be used when running tests against a database. Alternative This was an alternative investigation I did. We want a finer control including the driver and test database we need to specify further information. Settings Base This … -
psql: error: connection to server at "localhost"
Let me first mention I don't have admin privilege on my PC, So I could not install PostgreSQL with the normal process. I just download the binary files from here enterprisedb.com/download-postgresql-binaries, and added it to environment variable paths. My problem when I try to start a new server from pgAdmin it gives me the below error. connection to server at "localhost" (::1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? connection to server at "localhost" (127.0.0.1), port 5432 failed: Connection refused (0x0000274D/10061) Is the server running on that host and accepting TCP/IP connections? I searched a lot for a solution The first recommendation I got is to restart postgress from windows services but I couldn't find it. Second recommendation was to edit the psogress config file but also I can't find it at all they say that I can find it in the main directory of postgress. -
complex filters method in django
I am stuck with a problem where I need to send remainder emails to all users whos training is expiring in some period of time like ratio of 5/6. I have setup a scheduling system it will be filter all training programs who are expiring everyday and send them remainders. The problem I am facing is I am unable to figure out the query. This is the model I am using: class Training(models.Model): class Meta: ordering = ('-pk',) uuid = models.UUIDField(default=uuid.uuid4, editable=False) customer = models.ForeignKey('customer.Customer', on_delete=models.CASCADE, related_name='trainings') name = models.CharField(max_length=512) presentation = models.FileField(upload_to='trainings') data = models.JSONField() description = models.TextField(default='', blank=True) released = models.BooleanField(default=False) start_at = models.DateField() end_at = models.DateField() codes_file = models.FileField(null=True, max_length=1024) contact = models.EmailField(blank=True) is_archived = models.BooleanField(default=False) is_reminded = models.BooleanField(default=False) This is the query I am trying to run. trainings = Training.objects.filter(is_reminded=False, ).annotate( deadline=(datetime.today() - F('start_at')).days / (F('start_at') - F('end_at')).days, output_field=DateField() ).filter(deadline__gt=0.833) Error I am getting from this. I understand why this error is coming but I cannot figure out how to pull this data out. Internal Server Error: /testing/ Traceback (most recent call last): File "C:\Users\HP\.virtualenvs\apaa_backend-tCJa5vIy\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\HP\.virtualenvs\apaa_backend-tCJa5vIy\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\HP\.virtualenvs\apaa_backend-tCJa5vIy\lib\site-packages\django\views\decorators\csrf.py", line … -
Is querying reverse foreign keys lazy?
I need to check if user has at least one connected product of many types that we have in a system. I'm trying to make it more efficient so I added any() and made a generator for connection check. But I wonder if it still will query all reverse relationships and evaluate them. User can have a lot of products of each type. My code: def has_connected_product(self): def check_product_set_on_connected(product_sets): for product_set in product_sets: if product_set.model.__name__ == 'ShopifyProduct': yield product_set.exclude(shopify_id__isnull=True).exclude(shopify_id=0).exists() else: yield product_set.exclude(source_id__isnull=True).exclude(source_id=0).exists() return any(check_product_set_on_connected([ self.user.shopifyproduct_set, self.user.commercehqproduct_set, self.user.wooproduct_set, self.user.ebayproduct_set, self.user.fbproduct_set, self.user.googleproduct_set, self.user.gearbubbleproduct_set, self.user.groovekartproduct_set, self.user.bigcommerceproduct_set, ])) -
Upload picture with ajax in django application
I am stuck on while trying to upload a picture with ajax on a django project. I have a series of button each of them activate a different modal. In that modal I should upload a picture and it gets loaded in the correct model. My post function is working but I'd like to do that without reloading the page. HTML (only the relevant part): <tbody> {% for question in questions %} <tr> <td>{{forloop.counter}}</td> <td>{{question.id}}</td> <td>{{question}}</td> <td> <a title="{% trans "Edit Question" %}" class="btn btn-warning btn-sm" href="{% url 'administration:edit_question' pk=question.id %}"><i class="fas fa-edit"></i></a> <a title="{% trans "See Details" %}" class="btn btn-primary btn-sm ms-3" href="{% url 'administration:question_details' pk=question.id %}" ><i class="fas fa-eye"></i></a> <a title="{% trans "Delete Question" %}" href="{% url 'administration:delete_question' pk=question.id %}" id="delete_question" class="btn btn-sm btn-danger ms-3"><i class="fas fa-trash"></i></a> <button title="{% trans "Add Image" %}" class="btn btn-sm btn-success ms-3" data-bs-toggle="modal" data-bs-target="#addImageModal{{question.id}}"><i class="fas fa-file-image"></i></button> {% if question.explanation %} <a title="{% trans "Edit Explanation" %}" href="{% url 'administration:edit_explanation' pk=question.explanation.id %}" class="btn btn-sm btn-info ms-3"><i class="fas fa-edit"></i></a> <button title="{% trans "Add Explanation Image" %}" data-bs-toggle="modal" data-bs-target="#addExplanationImageModal{{question.id}}" data-questionId="{{question.id}}" class="btn btn-sm btn-secondary explanationModals ms-3"><i class="fas fa-plus"></i></button> {% else %} <a title="{% trans "Add Explanation" %}" href="{% url 'administration:add_explanation' pk=question.id %}" class="btn btn-sm btn-info ms-3"><i class="fas … -
Django return foreign key as object but use only uuid to create
I have 2 models, Subcategory and Quiz. Each quiz has one subcategory. I want to serialize the quiz to return the full subcategory object when I fetch it with get but be able to create a new quiz by passing in the uuid of the subcategory. If I use the SubcategorySerializer in the Quizserializer, I need to specify the full subcategory instead of passing just the uuid per POST. My Models: class SubCategory(BaseModel): name = models.CharField(max_length=100) category = models.ForeignKey(Category, on_delete=models.CASCADE, related_name='category') description = models.CharField(max_length=100, blank=True, null=True) class Quiz(BaseModel): name = models.CharField(max_length=100) subcategory = models.ForeignKey(SubCategory, on_delete=models.CASCADE, related_name='subcategory') description = models.CharField(max_length=100, blank=True, null=True) My Serializers: class SubCategorySerializer(serializers.ModelSerializer): category = CategorySerializer() class Meta: model = SubCategory fields = [ 'uuid', 'name', 'description', 'category', ] class QuizSerializer(serializers.ModelSerializer): subcategory = SubCategorySerializer(read_only=True) class Meta: model = Quiz fields = [ 'uuid', 'name', 'subcategory', 'description', ] When I remove the subcategoryserializer from the model, I can use the uuid of an existing subcategory to create a quiz but then it also only returns the uuid when I fetch it. When I add it back, I get the right response when I fetch it but I can't use the uuid to create it -
How to use a Bootstrap Modal to delete in Django? help me plsss
or must add to JavaScript section or not if so help me i'm a newbie so please help me HTML </head> <body> <div class="container-xl"> <div class="table-responsive"> <div class="table-wrapper"> <div class="table-title"> <div class="row"> <div class="col-sm-6"> <h2><b>Shipping</b></h2> </div> <div class="col-sm-6"> <a href="add_ship" class="btn btn-success" ><i class="material-icons">&#xE147;</i> <span>Add New Shipping</span></a> <div class="col-sm-6"> <div class="search-box"> <div class="input-group"> <input type="text" id="search" class="form-control" placeholder="Search by Name"> <span class="input-group-addon"><i class="material-icons">&#xE8B6;</i></span> </div> </div> </div> </div> </div> </div> <table class="table table-striped table-hover"> <thead> <tr> <th>ID</th> <th>Name</th> <th>Destination</th> <th>Date</th> <th>Actions</th> </tr> </thead> <tbody> {% for shipping in shipping_info %} <tr> <td>{{ shipping.shipping_id }}</td> <td>{{ shipping.driver_id.driver_fname }} {{ shipping.driver_id.driver_lname }}</td> <td>{{ shipping.destination }}</td> <td>{{ shipping.ship_date }}</td> <td> <a href="{% url 'edit_shipping' shipping.shipping_id %}" class="edit" ><i class="material-icons" data-toggle="tooltip" title="Edit">&#xE254;</i></a> <a href="#deleteEmployeeModal" class="delete" data-toggle="modal"><i class="material-icons" data-toggle="tooltip" title="Delete">&#xE872;</i></a> <a href="{% url 'view_shipping' shipping.shipping_id %}" class="" ><span class="material-icons"> visibility </span></a> </td> </tr> {% endfor %} </tbody> </table> i'm a newbie so please help me Help me plsss <form method="post" action=""> {% csrf_token %} <div id="deleteEmployeeModal" class="modal fade"> <div class="modal-dialog"> <div class="modal-content"> <form> <div class="modal-header"> <h4 class="modal-title">Delete User</h4> <button type="button" class="close" data-dismiss="modal" aria-hidden="true">&times;</button> </div> <div class="modal-body"> <p>Are you sure you want to delete these Records?</p> <p class="text-warning"><small>This action cannot be undone.</small></p> </div> <div class="modal-footer"> <input type="button" … -
use javascript to display django object
I want to implement below using javascript so row click it will get index and display object of this index. in django template this is working. {{ project.0.customer_name}} {{ project.1.customer_name}} but the below javascript are not working even I get the correct ID. var cell = row.getElementsByTagName("td")[0]; var id= parseInt(cell.innerHTML); document.getElementById('lblname').innerHTML = '{{ project.id.customer_name}}'; display django object using index in javascript. -
How can I get a total price column for CartItem model?
class Product(models.Model): name = models.CharField(max_length=80) product_image = models.ImageField(upload_to='product/product/images/%Y/%m/%d/', blank=True) price = models.IntegerField() class Cart(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) created_at = models.DateTimeField(auto_now_add=True) class CartItem(models.Model): item = models.ForeignKey(Product, null=True, on_delete=models.CASCADE) qty = models.IntegerField(default=1) cart = models.ForeignKey(Cart, null=True, on_delete=models.CASCADE) I'm trying to get an automatic total price that will be shown on check out page. I want to add a 'total_price' column on CartItem model and set the default 'item.price * qty', but when I tried to add this line to the class: total_price = models.IntegerField(default=item.price) since default value for qty is 1 but I got AttributeError: 'ForeignKey' object has no attribute 'price' error. I also tried add this to the class: @property def total_price(self): item = self.object.get(product=self.item) return self.item.price but I'm not sure which model will have the property? And when I added this method, I lost total_price column which I set its default as 0. I apologize for the lacking quality of solutions! -
Benefit of mod_wsgi daemon mode
I have written question django.urls.base.get_script_prefix returns incorrect prefix when executed by apache about the problems with providing urls for mezzanine pages (when executed by Apache the page urls were incorrectly formed). I just noticed that if I remove the mod_wsgi daemon mode from my Apache configuration the urls become correctly formed. Thus I'm asking what is the benefit of mod_wsgi doemon mode ?