Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Create superuser in ktor
in django, there's manage.py createsuperuser for creating a user with elevated privileges. For ktor, I have resorted to creating a user programmatically when the app starts, (first checking if the user already exist) Is there a more elegant or standard way of doing this? I assume it would be a similar process in other frameworks, express, flask etc since they don't also have that -
I'm trying to convert a .txt file to a .pdf file, but I'm facing this problem
def txttopdf(request): if request.method == 'POST': txt = request.FILES['txt'] pdf = fpdf.FPDF() pdf.add_page() pdf.set_font("Arial", size=12) pdf.cell(200, 10, txt.read().decode('utf-8'), 0, 1) return HttpResponse(pdf.output(dest='S'), content_type='application/pdf') return render(request, 'txttopdf.html') I create the pdf file but I cannot view its content. I'm trying to convert a .txt file to a .pdf file, but I'm facing this problem. -
Django allauth: Unable to get Access token when login using google social account
I am using django allauth for google authentication. settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/5.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'django-insecure-9#c!e&s(-o9-6u^mt#w(w6s$ober^f(m45)=f)=m&zo1$dlcg&' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'allauth', # Social login App 'allauth.account', # login App 'allauth.socialaccount', # Social login App 'allauth.socialaccount.providers.google', # Google login App 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', "API", # API APP ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', "allauth.account.middleware.AccountMiddleware" ] ROOT_URLCONF = 'MassMail.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.normpath(os.path.join(BASE_DIR, 'templates')), ], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', 'django.template.context_processors.request', # requirements for django-all-auth ], }, }, ] WSGI_APPLICATION = 'MassMail.wsgi.application' # Database # https://docs.djangoproject.com/en/5.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': BASE_DIR / 'db.sqlite3', } } # Password validation # https://docs.djangoproject.com/en/5.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, { 'NAME': 'django.contrib.auth.password_validation.CommonPasswordValidator', }, { 'NAME': 'django.contrib.auth.password_validation.NumericPasswordValidator', }, ] # Google Authentication … -
Django Unit Test Fail when i test UpdateView
In my project i have UserUpdateView like this: class UserUpdateView(AuthenticationMixin, AuthorizationMixin, SuccessMessageMixin, UpdateView): '''Update User info(username, full/second name, password)''' model = User form_class = UserForm template_name = 'form.html' permission_denied_message = _("You can't change this profile, this is not you") permission_denied_url = reverse_lazy('users-detail') success_message = _('User Profile is successfully changed') success_url = reverse_lazy('users-detail') extra_content = { 'title': _('Update user'), 'button_text': _('Update'), } User model like this: class User(AbstractUser): first_name = models.CharField(max_length=150) last_name = models.CharField(max_length=150) def __str__(self): return self.get_full_name() And test for UserUpdateView: class UpdateUserTest(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create(username='tota123', first_name='Andrey', last_name='Totavich', password='lexA456132') def test_update_user(self): self.client.login(username='tota123', password='lexA456132') response = self.client.post( reverse('user-update', kwargs={'pk': self.user.pk}),{ 'username': 'tota321', 'first_name': 'Sergey', 'last_name': 'Simo', 'password1': 'lexA456132', 'password2': 'lexA456132' }) self.assertEqual(response.status_code, 302) # Redirect after successful update self.assertEqual(self.user.username, 'tota321') The tests result: self.assertEqual(self.user.username, 'tota321') AssertionError: 'tota123' != 'tota321' - tota123 ? -- + tota321 ? ++ How can i solve this problem & why model of user dont change? When i run my project localy - i can change user info, and it work, UserUpdateView works correctly. What i missing ? -
AttributeError while loading pickle file from views.py
I am getting AttributeError: Can't get attribute 'predictionFunction' on <module 'main' from location of manage.py . When I don't register the viewfunction in the url, the predictionFunction gets loaded but when I register it in the urls it shows error. For your reference here is what my views.py file looks like: api_view(['GET']) def predictLaptopPrice(request): parent_dir = os.path.abspath(os.path.join(os.path.dirname(__file__), os.pardir)) file_path = os.path.join(parent_dir, 'predictionFunction.pkl') print("File path:", file_path) with open(file_path, 'rb') as file: predictionFunction = pickle.load(file) file.close() print("Loaded prediction function:", predictionFunction) processor_speed = request.GET.get('processor_speed') ram_size = request.GET.get('ram_size') storage_capacity = request.GET.get('storage_capacity') result = predictionFunction([[processor_speed, ram_size, storage_capacity]]) return Response({'price': result[0]}, status=status.HTTP_200_OK) I searched everywhere what this error is about but don't know what is happening. -
How to filter a queryset by a many2many field
I have a Notification model which has a field called seen_users like so: from django.contrib.auth import get_user_model User = get_user_model() class Notification(models.Model): title = models.CharField(max_length=255) seen_users = models.ManyToManyField(User, blank=True) Whenever a user sees a notification (.e.g notification_obj), that user will be added to notification_obj.seen_users. Now how can I filter notifications that has not seen by a specific user like user1 In most efficient way? I've tried to query like below: class NotificationView(generics.ListAPIView): authentication_classess = [TokenAuthentication] permission_classes = [] def get_queryset(self): unseen_only = self.request.GET.get("unseen_only", "0") if unseen_only == "1": # THIS IS WHERE I GOT TROUBLES # Because other users may have seen this and its not empty return Notification.objects.filter(seen_users__in=[]) return Notification.objects.all() -
Django forms, blank line
In my Django form I have a blank line (_____) when I look at my choices, how to fix this? Trying to remove this line Here is the code special_occasion = models.CharField(max_length=11, choices=[('None', 'None'), ('anniversary', 'Anniversary'), ('date', 'Date'), ('business', 'Business')]) -
Why celery doesn't run the code and how can i fix it?
I'm developing an api in django, for this api I need to use celery to do delayed actions. eventually, the aim would be to remove data from the database after a certain period of inactivity. I've set up celery and Rabbitmq, but when I try to execute something with a print to try nothing happens. here's how I set up celery in settings.py: #celery settings import ssl CELERY_BROKER_URL = 'amqps://guest:guest@localhost:5671/' CELERY_BROKER_USE_SSL = { 'ca_certs': '/etc/rabbitmq/cacert.crt', 'keyfile': '/etc/rabbitmq/key.pem', 'certfile': '/etc/rabbitmq/cert.crt', 'cert_reqs': ssl.CERT_REQUIRED } CELERY_RESULT_BACKEND = "rpc://" here's the code I'm trying to run: from __future__ import absolute_import, unicode_literals from celery import shared_task from django.utils import timezone from datetime import timedelta #DELAY_FOR_DATA_DELETION = timedelta(days=30) # 30 jours par exemple @shared_task def delete_user(): print("test") return that's how I call the function: delete_user.apply_async(countdown=5) and here's how I set up the celery.py file: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'base.settings') app = Celery('base', broker="amqps://guest:guest@localhost:5671/") app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() I've tried to do “celery status” to see the worker status but I get this error # /home/transcendence/venv/bin/celery status Traceback (most recent call last): File "/home/transcendence/venv/lib/python3.11/site-packages/amqp/connection.py", line 515, in channel return self.channels[channel_id] ~~~~~~~~~~~~~^^^^^^^^^^^^ KeyError: None During handling of the above exception, another … -
Django: Ignore trans strings which are already translated in app directory
I use django-allauth as a third partie package in my Django project. I copied some templates from django-allauth into my template directory to modify the layout. But I did not touch the translation strings! After running makemessages this strings appears in my .po file even though it is translated in the app directory for django-allauth. (To manage my translations I use Weblate.) How can I stop this behavior? This is blowing up my .po file and is confusing the translators, because we have to notify them not to touch this string. Can I create a list of "msgid" which will ignore some strings? -
Django Admin Soft Dashboard in aws ec2 ubuntu 24.04 using pyhton 3.6.8
For my django admin panel I used django-soft-admin-panel pip for UI, as my python runtime is 3.8 it didn't run, so I downgraded by python to 3.6 and developed the project, the ui and all other things are perfectly working in local. I need to deploy the project in any of the aws services. At first I used lambda, but lambda is only for runtime >= 3.8 then I used Elastic Beanstalk, ebs is only for runtime >= 3.7 then I deployed in EC2 with nginx and gunicorn but the project and server getting crashed. Is there any solution? -
Django Rest Framework Many To Many serializer problem
I'm creating an API in Django Rest Framework and I have a problem with a ManyToMany relation. I'm trying to create an movie and assign genre to it (ManyToMany relationship between movie and genre). Here are my models: class Genre(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(null=False,blank=False,max_length=50) def __str__(self): return self.name class Movie(models.Model): id = models.IntegerField(primary_key=True,null=False,blank=False) adult = models.BooleanField(null=False,blank=False) backdrop_path = models.CharField(null=True,blank=True,max_length=200) budget = models.BigIntegerField (default=0) homepage = models.CharField(null=True,blank=True,max_length=200) original_language = models.CharField(max_length=10) original_title = models.CharField(max_length=200) overview = models.CharField(max_length=1000) poster_path = models.CharField(null=True,blank=True,max_length=200) release_date = models.DateField(null=True,blank=True,) revenue = models.BigIntegerField (default=0) runtime = models.IntegerField(null=True,blank=True) status = models.CharField(max_length=50) tagline = models.CharField(null=True,blank=True,max_length=100) title = models.CharField(max_length=200) genres = models.ManyToManyField(Genre,blank=True) def __str__(self): return self.title here are my serializers: class GenresSerializers(serializers.ModelSerializer): class Meta: model = Genre fields = ['id','name'] def create(self,validated_data): instance, _ = Genre.objects.get_or_create(**validated_data) return instance class MovieGenreSerializer(serializers.ModelSerializer): class Meta: model = Genre fields = ['id'] def create(self, validated_data): instance, _ = Genre.objects.get(**validated_data) return instance class MoviesSerializer(serializers.ModelSerializer): genres = GenresSerializers(many= True) class Meta: model = Movie fields = [ 'id', 'adult', 'backdrop_path', 'budget', 'homepage', 'original_language', 'original_title', 'overview', 'poster_path', 'release_date', 'revenue', 'runtime', 'status', 'tagline', 'title', 'genres' ] # extra_kwargs = {'id': {'read_only': True}} def create(self, validated_data): genres_data = validated_data.pop('genres', []) genresInstances = [] for genre in genres_data: genresInstances.append(Genre.objects.get(pk = … -
Issue with closing modals by clicking outside on specific page
I have implemented modals on my Django website using Bootstrap, where the modals open upon clicking buttons and close when clicking outside of them. This functionality works perfectly on most pages of my website, including the base template. However, I'm encountering an issue on my system page where the modals do not close when clicking outside of them. Here's the relevant code snippet from my base.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link rel="stylesheet" href="{% static 'styles.css' %}"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-T3c6CoIi6uLrA9TneNEoa7RxnatzjcDSCmG1MXxSR1GAsXEV/Dwwykc2MPK8M2HN" crossorigin="anonymous"> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.3.2/dist/js/bootstrap.bundle.min.js" integrity="sha384-C6RzsynM9kWDrMNeT87bh95OGNyZPhcTNXj1NW7RuBCsyN/o0jlpcV8Qyq46cDfL" crossorigin="anonymous"></script> </head> <body class="background-image-shop"> <!-- Navbar --> <nav class="main-top-navbar navbar navbar-light bg-black fixed-top navbar-custom"> <div class="container"> <div class="main-top-navbar-elements navbar-text"> <a href="{% url 'shop' %}" class="font-weight-bold text-light" style="margin-right: 20px;">Tribute |</a> <a href="{% url 'temples' %}" class="font-weight-bold text-light" style="margin-right: 20px;">Temples |</a> <a href="#" class="font-weight-bold text-light" style="margin-right: 20px;">Merchandise |</a> </div> <a href="#" class="navbar-brand">Your Logo</a> <!-- Add Product Button (visible for admin users only) --> {% if user.is_authenticated and user.is_superuser %} <button class="btn btn-outline-light" onclick="showAddProductModal()">Add Product</button> {% endif %} <!-- Search Bar --> <div class="shop-slogan"> <p>The Cards Await You!</p> </div> </div> </nav> <!-- Main content --> <div id="main-content"> <!-- Your website content here --> {% block body %} … -
Django message about waiting for process
I created app, which generate pdf file with some content. After filling form by user it is submitted and after about 10 seconds file preview is opening. I want to show message that user should wait for file after hiting Submit. When I add a meesage it shows but not earlier than download start and message it is not visible (it shows too late). Actually to show the messege I need to comment line return responce my view: def pdf_create(request): if (request.method == 'POST'): form = MsdsForm(request.POST) messages.info(request, f'''Please wait for a file.''') if (form.is_valid()): cd = form.cleaned_data # A LOT OF CODE AND THINGS HERE wchich create pdf response = HttpResponse(pdf_output, content_type='application/pdf') response['Content-Disposition'] = f"filename=some_file.pdf" return response else: form = MsdsForm() return render(request, 'msds_form.html',{'form':form}) I searched google for couple of hours and didn't find simple solution. I omit some details or it isn't simple way to do that? I don't know if it is essential in this case but I don't use models. -
Error : Conversion 'rpy2py' not defined for objects of type
I am using python R library to implement the ERGM model to a data set. I am following the below approach def ergm_process(nodes, edges): try: logger.debug(f"Passed Node: {nodes}") logger.debug(f"Edges: {edges}") # Convert node and edge data for R nodes_df = pd.DataFrame(nodes) edges_df = pd.DataFrame(edges) nodes_df['Attendance'] = pd.to_numeric(nodes_df['Attendance'], errors='coerce') if 'id' not in nodes_df.columns: logger.error("Node data must include 'id' keys") return {"error": "Node data incomplete"} # R DataFrame Conversion nodes_r = pandas2ri.py2rpy(nodes_df) # Prepare node and edge data for R node_ids = nodes_df['id'].tolist() edges_tuples = [(edge['from'], edge['to']) for edge in edges] # Log and check edge tuples if not all('from' in edge and 'to' in edge for edge in edges): logger.error("One or more edges are missing 'from' or 'to' keys") return {"error": "Edge data incomplete"} flat_edges = [item for tup in edges_tuples for item in tup] # Setup R environment from rpy2.robjects.packages import importr base = importr('base') network = importr('network', on_conflict="warn") ergm = importr('ergm', on_conflict="warn") # Pass data to R ro.globalenv['nodes'] = nodes_r ro.globalenv['node_ids'] = ro.StrVector(node_ids) ro.globalenv['edges'] = ro.IntVector(flat_edges) # Flatten list of tuples # Run R code ro.r(''' print("Node IDs:") print(node_ids) print("Edges:") print(edges) net <- network::network(matrix(edges, byrow=TRUE, ncol=2), directed=TRUE, vertices=node_ids) # Ensure each attribute is set for (attr_name in colnames(nodes)) … -
How to check if a Django Model Instance contains a foreign key or not
I need to serialize data coming from Django Audit Log Entry in such a way that when in changes field There is a Field present which has a value of foreign key I need to fetch the value of that Foreign key from database and Change the Foreign key with the value. def get_changes(self, obj): changes_data = obj.changes if changes_data: model_name = obj.content_type.model_class().name try: field_mapping = getattr(ma_activity_tracker, f"{model_name}_display_atrb") except AttributeError: field_mapping = {} changes = {} for field, (old_value, new_value) in changes_data.items(): field_name = field_mapping.get(field, field) field_object = globals().get(model_name) print(field_object.User) # if isinstance(field_object, models.ForeignKey): if isinstance(field_object,models.ForeignKey): old_related_obj = field_object.related_model.objects.filter(pk=int(old_value)).first() new_related_obj = field_object.related_model.objects.filter(pk=int(new_value)).first() old_display_value = getattr(old_related_obj, field_name) if old_related_obj else None new_display_value = getattr(new_related_obj, field_name) if new_related_obj else None old_value = old_display_value new_value = new_display_value changes[field_name] = { "Old Value": old_value, "New Value": new_value } return changes return None This is what I tried but to do but the if block never gets executed -
Postman request to django with csrf works but not with request in NextJS
I'm currently working on a login system that needs a POST request and csrf authentication, so I started to work with postman and trying to send requests and took the snippet provided by the generator: const myHeaders = new Headers(); myHeaders.append("X-CSRFToken", "OmgnDDPPS4TRcERF3XNuYw4uJ3OBSwmmSq7ktjM5wX2oT02DWuWZwX57BOOLCA3h"); myHeaders.append("Cookie", "csrftoken=OmgnDDPPS4TRcERF3XNuYw4uJ3OBSwmmSq7ktjM5wX2oT02DWuWZwX57BOOLCA3h"); const requestOptions = { method: "POST", headers: myHeaders, redirect: "follow" }; fetch("http://127.0.0.1:8000/simulazione/api/prova_token/", requestOptions) .then((response) => response.text()) .then((result) => console.log(result)) .catch((error) => console.error(error)); The request above works in postman but if I took this code and write it in nextjs a got the forbidden error [30/Apr/2024 13:11:47] "POST /simulazione/api/prova_token/ HTTP/1.1" 403 2869 These below are the django view and settings: View @csrf_protect def prova_token(request): if request.method == 'POST': return JsonResponse("hello", safe=False) Settings CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True #CSRF_COOKIE_SECURE = False CSRF_COOKIE_HTTPONLY = False SESSION_COOKIE_SECURE = False SESSION_COOKIE_SAMESITE = None ALLOWED_HOSTS = [ ] CSRF_TRUSTED_ORIGINS = ["http://127.0.0.1:3000","http://localhost:3000"] CORS_ALLOW_HEADERS = [ 'accept', 'accept-encoding', 'authorization', 'content-type', 'dnt', 'origin', 'user-agent', 'x-csrftoken', 'csrftoken', 'x-requested-with', ] CORS_ALLOW_METHODS = [ 'DELETE', 'GET', 'OPTIONS', 'PATCH', 'POST', 'PUT', ] CORS_ALLOWED_ORIGINS = [ 'http://127.0.0.1:3000', 'http://localhost:3000', ] # Application definition INSTALLED_APPS = [ 'corsheaders', 'simulazione.apps.SimulazioneConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_nextjs', 'rest_framework', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] I … -
Djano server vs apache2.4 not the same results
i have a weird problem in my django application is that im i have an application runs tools based on their scripts all scripts works fine but only one that works in django server but not in apache2 and the Unable to retrieve my generation from the parent im not sure if this is the issue but i need help on this Thank you o tried to change many things in setttings config and using the apache as admin but im not sure what causing the issue -
Hi. I'm a beginner programmer and I'm trying to write a Django website right now
The fact is that I have no experience at all and I use a tutorial from the Internet. This is a lesson: https://proglib-io.turbopages.org/proglib.io/s/p/django-s-nulya-chast-2-registraciya-avtorizaciya-ogranichenie-dostupa-2022-06-08 When I try to implement the user registration function and in fact just copy the actions of the teacher, my site gives the error: TemplateDoesNotExist at /register/ I don't understand why this is happening... I do not know what I am doing wrong, like I installed pipenv install django-crispy-forms, I only used the pip install django-crispy-forms command, because this command was not executed. I did everything according to the tutorial. -
How can we create authentication system in Django using MongoDB database?
I have a Django project where I am trying to set up authentication system with mongo db I followed various tutorials and documentation but still facing issues. I have tried with djongo module with django to connect mongo db. Also I have custom user. also tried custom authentication backend for mongo db -
Deployment: Procfile with Django Project Structure for more than one App
I need to know how you normally solve this issue. When you start a project, django creates a folder for the project and a second one inside it with the exact same name and the files like: settings.py, init.py, wsgi.py, etc. After Im done with the repo I delete one of the two folders with the same name in order to let Procfile find project.settings inside the wsgi.py. I want to be able to run the Procfile considering the original structure, because I want to learn how to create more than one app inside a project. My exact question is. How should I setup my procfile? right now is like this: web: gunicorn expenses.wsgi --log-file - But Then Procfile doesn't find expenses.wsgi This is my structure: v expenses v expenses > static __init.py asgi.py settings.py urls.py wsgi.py > finances manage.py Procfile requirements.txt runtime.txt I tried changing the Procfile from gunicorn expenses.wsgi to gunicorn expenses.expenses.wsgi but then I will tell my to change os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'expenses.settings') inside the wsgi.py I tried changing the wsgi.py from os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'expenses.settings') to os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'expenses.expenses.settings') but then it will tell me that it couldn't find the module finances. -
Djnamic checkbox, change and disabled or unhide when select
I have three columns named "passive", "discount" and "discountprice" in the rows coming from the database. I use checkbox. If the passive is full, when one of the data-x with the passive label is selected, the others will be disabled. If the discount is full, when one of the ones with the data-y discount tag is selected, the discount price of those with the same discount tag will replace the normal price. It cannot be both discounted and passive. There may be different discount groups or liability groups. I'm stuck. What I wrote was of no use. html {% for mal in mlazm %} <input class="form-check-input" type="checkbox" value="{{ mal.0 }}" name='mlzm{{ forloop.counter }}' data-price="{{ mal.3 }}" data-bprice="{{ mal.7|default:'0' }}" id="{{ mal.0 }}{{ mal.0 }}" {% if mal.4 %}disabled{% endif %}> {%endfor%} js var $checkboxes = $('.myCheckBox').change(function() { var $checked = $checkboxes.filter(':checked'); if ($checked.length >= 3) { $checkboxes.filter(':not(:checked)').prop('disabled', true); } else { $checkboxes.prop('disabled', false); } }); -
My context processor document is being a complete arse
I am literally going to scream. Why can I not get any bloody text to appear from my function in my contect-processor.py to work? I am going to scream so bloody loudly because I am fed up of Django not doing as it's told. PROJECT -|project -|careers -|models.py -|context_processor.py -|templates -|template.html #context_processors.py from .models import Careers def careers_exist(request): # Check if there are any active careers careers_available = Careers.objects.filter(active=True).exists() # Prepare the context dictionary based on availability if careers_available: header = {'header': 'Current vacancies'} else: header = {'header': 'No Vacancies'} return {'header' : header} #template.html <h2>{{ header.header }}</h2> Why is my template still blank despite doing everything correctly. What a stupid bloody thing. -
Which languange/framework should I use? [closed]
I'm getting ready to do my final project. It should be a web app that will show fitness progress by entering it into the system. The progress just given, which has to be written down by the user, will be shown in the form of a graph. I am mainly concerned about the look of the overall application, but at the same time a good backend of course with a database. The original idea was to use Python with Django and React for frontend. But recently I was recommended to use Next.js for both frontend and backend. What is your opinion on what you would use? Or do you have any other opinion? -
Photo upload app Using Flutter and Django
I want to make a (Photo Upload app ) using Flutter and Django Does anyone here have any experience using the Django / Django REST framework, as the backend for a mobile app built with Flutter which has the feature of uploading multiple photos? or anyone who built any apps like the feature of Facebook? If there are any please give me your GitHub repository link or teach me how to build this featured app or if there exists any course please suggest me. ..................... -
Choose which model manager to use when doing prefetch_related?
I have a Product model in my Django app, which uses a custom model manager where all the prefetch_related statements are made: class ProductManager(models.Manager): def get_queryset(self): return ( super() .get_queryset() .select_related("core_product") .prefetch_related("images") .prefetch_related("bundled_products") ) class Product(models.Model): _base_manager = ProductManager objects = ProductManager() # ... model fields This works fine; when I use the ORM and within the Admin the custom manager is used, preventing a whole bunch of duplicate queries. The problem is when I have another model that has a prefetch_related to the Product model: it now inherits all the prefetch_related from the Product, even though that's not necessary. It causes a whole bunch of unnecessary queries to be made. class OfferManager(models.Manager): def get_queryset(self): return ( super() .get_queryset() .select_related("flag") .prefetch_related("condition_products") .prefetch_related("limited_to_users") .order_by("-priority") ) Here the condition_products field is that Product model from above, and just by including this prefetch_related, all of its prefetch_related statements are also inherited. How can I prevent this from happening? Can I specify which object manager to use in the prefetch_related - so that is uses a "bare" manager?