Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django query from paypalipn table
I have connected my django-paypal and I have managed to make payments but it seems I can make queries from paypal_ipn table or I'm making mistakes somewhere. The below are the currect snippets of what I have done. from paypal.standard.ipn import models as paypal_models from .serializers import PaymentSerializer @api_view(['GET']) def getPaymentStatus(request): postedRef = PaymentSerializer(data=request.data) print(postedRef) paypalTxn = paypal_models.PayPalIPN #On here I'm trying to query serializer = PaymentSerializer(paypalTxn) return Response(serializer.data) The below is something that I intend to get. from paypal.standard.ipn import models as paypal_models from .serializers import PaymentSerializer @api_view(['GET']) def getPaymentStatus(request): postedRef = PaymentSerializer(data=request.data) print(postedRef) paypalTxn = paypal_models.PayPalIPN.objects.filter(invoice=postedRef).first() #Something like this serializer = PaymentSerializer(paypalTxn) return Response(serializer.data) -
Unable to change position of previous and next button and background color of carousel slide
Can't change positions of the prev and next buttons and not only that but also the background color of carousel slidebar of also unable to changed. i tried from inspecting it but can't save changes in inspect and not by entering code of those buttons. {% extends 'shop/basic.html' %} {% block css %} .carousel-indicators [data-bs-target] { background-color: #0d6efd; } .col-md-3 { display: inline-block; margin-left: -4px; } .carousel-indicators .active { background-color: blue; } .col-md-3 img{ width: 170px; height: 200px; } body .carousel-indicator li{ background-color: blue; } body .carousel-indicators{ bottom: 0; } body .carousel-control-prev-icon, body .carousel-control-next-icon{ background-color: blue; } .carousel-control-prev, .carousel-control-next{ bottom: auto; top: auto; padding-top: 222px; } body .no-padding{ padding-left: 0; padding-right: 0; } {% endblock %} From here I given id and names to the particular code above mentioned {% block body %} {%load static%} <div class="container"> {% for product,range,nSlide in allprods %} <h5 class="my-4"> {{product.0.category}} </h5> <div id="row"> <div id="demo{{forloop.counter}}" class="carousel slide my-3" data-bs-ride="carousel"> <div class="carousel-indicators"> <button type="button" data-bs-target="#demo{{forloop.counter}}" data-bs-slide-to="0" class="active"></button> {% for i in range%} <button type="button" data-bs-target="#demo{{forloop.parentloop.counter}}" data-bs-slide-to="{{i}}"></button> {% endfor %} </div> <div class="container carousel-inner no-padding"> <div class="carousel-item active"> {% for i in product %} <div class="col-xs-3 col-sm-3 col-md-3"> <div class="card align-items-center" style="width: 18rem;"> <img src='/media/{{i.image}}' class="card-img-top" … -
Username and password are always incorrect in my django AuthenticationForm
I'm trying to login user by his username and password, but when i'm trying to check form.is_valid(), it returns False. Errorlist contain error: "Please enter a correct username and password. Note that both fields may be case-sensitive.". When i don't specify my own post it's doesn't work either. I was looking for typo, but didn't found any. In internet nothing helped me at all. I tried switch form and it's fields, but error was the same. views.py from django.views.generic import * from django.views.generic import * from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth import authenticate, login, logout ... class RegisterView(CreateView): form_class = UserRegisterForm success_url = reverse_lazy('main:homepage') template_name = "accounts/register.html" def post(self, request): form = self.get_form() if form.is_valid(): user = form.save() login(request, user) return redirect("main:homepage") else: print(form.errors) return redirect("accounts:register") class LoginView(FormView): form_class = AuthenticationForm template_name = "accounts/login.html" def post(self, request): form = self.get_form() if form.is_valid(): form.clean() user = authenticate( request, username=form.cleaned_data["username"], password=form.cleaned_data["password"], ) login(request, user) return redirect("main:homepage") else: print(form.errors) print(form.cleaned_data) return redirect("accounts:login") forms.py from django import forms from django.contrib.auth import get_user_model, authenticate, login from django.contrib.auth.forms import UserCreationForm, AuthenticationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = get_user_model() fields = ['username', 'email', 'first_name'] def save(self): self.clean() user = self.Meta.model( username = self.cleaned_data['username'], email … -
Exception Type: MultiValueDictKeyError at /predict/ Exception Value: 'a'
Exception Type: MultiValueDictKeyError at /predict/ Exception Value: 'a' Code val1 = float(request.GET['a']) -
Correct way to consume 3rd party API with query in Django + React (Backend + Frontend)
I'm using Django on my backend and React on my frontend. I want to consume the OpenWeatherMap API. For security reasons, I want to keep my API key on the backend. Currently, I have this working on my Django app. When a POST request is made, the Django view renders the information required from OpenWeatherMap. How can the user type the query in React, send the query to to the backend and get the results on the frontend? I have a very hacky way of doing this currently: I POST (using axios) the city that the user enters in React to a REST API that I built in Django. The backend queries the OpenWeatherMap API with the city that the user enters and POSTs the data that it gets from OpenWeatherMaps back to my API. After this, the frontend uses a GET request on my API to show the information to the user. I'm pretty sure this isn't the correct way to do this but I couldn't find any other questions on this, and I'm pretty new to web development. -
Rendering custom html templates in Django
I am not an expert in Django, but this software is written in Django using the rest framework, and I need to make customizations to it: https://github.com/openvinotoolkit/cvat/tree/develop/cvat I need to render a custom html template, and this is what I've done so far. I created a new folder in apps called custom with these files: cvat/apps/custom/templates/custom/<name>.html (there are various html templates in custom with different "names". i.e. a.html, b.html, c.html, etc.) Other files in cvat/apps/custom: cvat/apps/custom/__init_.py cvat/apps/custom/apps.py from django.apps import AppConfig class CustomConfig(AppConfig): name = 'cvat.apps.custom' cvat/apps/custom/urls.py from django.urls import path from . import views urlpatterns = [ path('custom/<str:name>', views.CustomView), ] cvat/apps/custom/views.py from django.shortcuts import render def CustomView(request, name): return render(request, 'custom/'+name+'.html') In addition, I have modified these existing files to add the custom folder that was created in apps: https://github.com/openvinotoolkit/cvat/blob/develop/cvat/urls.py#L27 added path('custom/', include('cvat.apps.custom.urls')),: urlpatterns = [ path('admin/', admin.site.urls), path('custom/', include('cvat.apps.custom.urls')), path('', include('cvat.apps.engine.urls')), path('django-rq/', include('django_rq.urls')), ] https://github.com/openvinotoolkit/cvat/blob/develop/cvat/settings/base.py#L129 INSTALLED_APPS = [ ... 'cvat.apps.custom' ] However, when I go to http://localhost:8080/custom/custom/a I get redirected back to another page - not a.html Any advice on what I'm doing wrong? -
Django Rosetta and i18n not working with some ids in Javascript
I have a proyect with Django and I want to translate it to Spanish, English and Italian. Everything working correctly in html files, but I have a file in .js that not working correctly. There are ids that have been translated and there are ids that haven't been translated. This file, is in the folder static and its called from .html file <script src="{% url 'javascript-catalog' %}"></script> <script type="text/javascript" src="{% static 'services_steps/file.js' %}"></script> In file.js I have all ids in variables: var whatever1 = gettext("filejs_whatever1") var whatever2 = gettext("filejs_whatever2") var whatever3 = gettext("filejs_whatever3") Url.py path('jsi18n/', JavaScriptCatalog.as_view(), name='javascript-catalog'), url(r'^i18n/', include('django.conf.urls.i18n')), if 'rosetta' in settings.INSTALLED_APPS: urlpatterns += [ re_path(r'^rosetta/', include('rosetta.urls')) ] And files.po get all ids (services_steps/locale) ... #: file.js:70 msgid "filejs_whatever0" msgstr "Whatever 0" #: file.js:71 msgid "filejs_whatever1" msgstr "Whatever 1" #: file.js:72 msgid "filejs_whatever2" msgstr "Whatever 2" The commands are, in static (services_steps) folder: django-admin makemessages -d djangojs -l en_GB django-admin makemessages -d djangojs -l es_ES django-admin makemessages -d djangojs -l it_IT And in root directory django-admin compilemessages -
Django Channels: Send message from outside Consumer Class
I'm new in Python and Django, Currently, I need to setup a WebSocket server using Channels. I follow the code in this link: Send message using Django Channels from outside Consumer class setting.py ASGI_APPLICATION = 'myapp.asgi.application' CHANNEL_LAYERS = { 'default': { 'BACKEND': 'channels.layers.InMemoryChannelLayer', }, } Here is the code Consumer import json from channels.generic.websocket import WebsocketConsumer from asgiref.sync import async_to_sync class ZzConsumer(WebsocketConsumer): def connect(self): self.room_group_name = 'test' async_to_sync(self.channel_layer.group_add)( self.room_group_name, self.channel_name ) self.accept() def disconnect(self, code): async_to_sync(self.channel_layer.group_discard)( self.room_group_name, self.channel_name ) print("DISCONNECED CODE: ",code) def receive(self, text_data=None, bytes_data=None): print(" MESSAGE RECEIVED") data = json.loads(text_data) message = data['message'] async_to_sync(self.channel_layer.group_send)( self.room_group_name, { "type": 'chat_message', "message": message } ) def chat_message(self, event): print("EVENT TRIGERED") # Receive message from room group message = event['message'] # Send message to WebSocket self.send(text_data=json.dumps({ 'type': 'chat', 'message': message })) And outside the Consumer: channel_layer = get_channel_layer() async_to_sync(channel_layer.group_send)( 'test', { 'type': 'chat_message', 'message': "event_trigered_from_views" } ) The expected logics is I can received the data from the group_send in the receive on the Consumer class. So that I can send message to client. However, It's not. Can anyone here know what's I missing? Any help is very appreciated. Thanks! -
How to load a static file in django v4.0.5?
I was trying to load a static file i.e my CSS in django and i am doing evrything taught in tutorial but it isn't happening. i have my CSS inside static folder. {% 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"> <link rel="stylesheet" type="text/css" href="{% static 'main.css' %}"> <title> Django </title> </head> <body> <header> <div> <nav id="a1"> <a href="{% url 'home'%}" class="a">Home</a> <a href="{% url 'about'%}" class="a">About</a> <a href="{% url 'contact'%}" class="a">Contact</a> <a href="{% url 'courses'%}" class="a">Courses</a> </nav> </div> </header> Here, is my settings.py file as i was following tutorial, settings.py # Static files (CSS, JavaScript, Images) # https://docs.djangoproject.com/en/4.0/howto/static-files/ STATIC_URL = 'static/' STATICFILES_DIR=[ BASE_DIR,"static" ] -
How use a different language with Django?
Is it possible to customise every error message in Django? I am using a language that does not seem to be supported by Django so the translation method won't work. Also, I prefer to write my own error messages. If I have to manually change everything, is there somewhere I can see all the error messages and where they're used in Django? For example, all the error messages associated with a form or a field, such as unique, min_length, etc. -
zipped data shown in view but not in templete
row1 = [] row2 = [] categories= Kategoriler.objects.all().filter(parent_id__isnull=True).order_by('id') for x in categories: row1.append(x.title) row2.append(Kategoriler.objects.all().filter(parent_id=x.id).order_by('title')) zipped = itertools.zip_longest(row1, row2) for u, y in zipped: print(">>>>>>>>>>>>>>>", u, "<<<<<<<<<<<<<<<<<<<<") for q in y: print(q.title) context = {'segment': 'categories', "zipped": zipped} Above code prints as expected in view.py In templete; {{ zipped|length }} {% for u, y in zipped %} {{ u }}---{{ y.title }} {% endfor %} len gives 0, and loop is empty. What's the reason of it? Thank you. -
Implementing the features of "The Browsable API" from the Django REST Framework in a react app
I have a few models with a structure similar to this: class YearInSchool(Enum): FRESHMAN = 'FR' SOPHOMORE = 'SO' JUNIOR = 'JR' SENIOR = 'SR' GRADUATE = 'GR' @classmethod def choices(): return (tuple(i.name, i.value) for i in YearInSchool) class Student(models.Model): year_in_school = models.CharField( max_length=2, choices=YearInSchool.choices(), ) class MyModel(models.Model): # Some other fields here year = models.ForeignKey(Student, blank=True, null=True, on_delete=models.SET_NULL) The View I am using looks something like this: class GetStudentDetails(generics.RetrieveUpdateDestroyAPIView): class StudentSerializer(serializers.Modelserializer): class Meta: model = Student fields = '__all__' queryset = Student.objects.all() serializer_class = StudentSerializer lookup_field = 'year_in_school' If I made an API call the result would look something like this: { // Some other fields here "year_in_school": 1, } If I wanted to have the options returned from the API call as well, I would have to add an additional field like the one described in this post: https://stackoverflow.com/a/54409752/15459291 If I wanted the value of the currently selected choice instead of the primary key, I would also have to flatten the structure by adding another new field. "The Browsable API" from the Django REST Framework shows all this information and implements drop-down selectors for choice fields that have the currently selected value preselected. To me this seems like … -
How can I place header and text next to my img?
I want to add 4 images to Blog(2 columns and each one has 2 images with its header and description) of my site want to place its header and paragraph on right side of it, how can I do that? here is my css and html code: <section id="part2"> <div class="container"> <h1>Blog</h1> <div class="box"> <img src="images/img1-service.jpg" width='255' height="175"/> <h3>10 RULES TO BUILD A WILDLY</br> SUCCESSFUL BUSINESS</h3> <p>You can edit all of this text and</br> replace it with anything you have</br> to say on your blog.</p> </div> <div class="box"> <img src="images/img2-service.jpg" width='255' height="175"/> <h3>9 STEPS TO STARTING A</br> BUSINESS</h3> <p>This is a generic blog article you</br> can use for adding blog content /</br> subjects on your website.</p> </div> </div> </section> there should be 4 photos,i haven't add them yet and my css: body{ margin: 0; padding: 0; } .container{ margin:auto; overflow:hidden; } #part2 h1{ text-align:center; font-size:250%; } .box{ display: inline; text-align:center; float:left; padding:10px; width:30%; width: 33.3%; } -
Exception in thread django-main-thread Traceback
I am getting this error while trying to run my Django project. I have installed all needed libs and still do not have any clue why this error is accurring. Explored almost all the resources available on the internet and still did not get any help in solving this. Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1016, in _bootstrap_inner self.run() File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\threading.py", line 953, in run self._target(*self._args, **self._kwargs) File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\commands\runserver.py", line 134, in inner_run self.check(display_num_errors=True) File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\management\base.py", line 487, in check all_issues = checks.run_checks( File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\registry.py", line 88, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\urls.py", line 14, in check_url_config return check_resolver(resolver) File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\core\checks\urls.py", line 24, in check_resolver return check_method() File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 480, in check for pattern in self.url_patterns: File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 696, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\utils\functional.py", line 49, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\site-packages\django\urls\resolvers.py", line 689, in urlconf_module return import_module(self.urlconf_name) File "C:\Users\Dharv\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen … -
Communication of two applications
I need to make an admin panel for the Telegram's bot. I plan to implement the panel itself on Django. What I can use to get Django and the bot to communicate? -
Django ElasticSearch Rest Framework Suggesting Results duplicate title
In my database, there are lots of duplicate titles but their id is not duplicate and other properties are not duplicated. only title duplicate. I have implemented API for auto suggest but it is not currently returning duplicate results. coz, in database, most of the product are duplicate title. the duplicate title is normal but it should not return in API response for auto suggest, this is what I tried: from django_elasticsearch_dsl_drf.filter_backends import ( SuggesterFilterBackend ) from django_elasticsearch_dsl_drf.viewsets import DocumentViewSet from django_elasticsearch_dsl_drf.constants import ( SUGGESTER_COMPLETION, ) class SuggestionsAPIView(DocumentViewSet): document = ProductDocument serializer_class = ProdcutTitleSerializer filter_backends = [ SuggesterFilterBackend, ] suggester_fields = { 'title': { 'field': 'title', 'suggesters': [ SUGGESTER_COMPLETION, ], 'options': { 'size': 20, 'skip_duplicates':True, }, }, } Anyone know about this? How can I get rid of such a duplicate results? -
How to create custom permissions for django admin site
By default when I create a model Django gives permissions like add/change/delete/view If I give any of the above permission to a specific user then that user can view all the objects from that model. But I want to show them only objects linked with foreign keys. Let's Say, I have a Book model class Book(models.Model): title = models.CharField(max_length=100) author = models.ForeignKey( User, on_delete=models.CASCADE ) If I want to give authors permission, they can only view their linked books from the Django admin. How can I do that? -
Cannot run .service file even when its located in /etc/systemd/system
When I try to run the command: systemctl start myportfolio I get the following error message: Failed to start myportfolio.service: Unit myportfolio.service not found. I also checked to see if myportfolio.service was in the right directory and it was: So why wont it run properly? What seems to be the error? myportfolio.service: [Unit] Description=Serve Portfolio Site After=network.target [Service] User=root Group=root WorkingDirectory=/root/team-portfolio ExecStart=/root/team-portfolio/python3-virtualenv/bin/python/root/team-portfolio/python3-virtualenv/bin/flask run --host=0.0.0.0 Restart=always [Install] WantedBy=multi-user.target -
Django Model Instance as Template for Another Model that is populated by Models
I'm trying to create the create a workout tracking application where a user can: Create an instance of an ExerciseTemplate model from a list of available Exercise models. I've created these as models so that the user can create custom Exercises in the future. There is also an ExerciseInstance which is to be used to track and modify the ExerciseTemplate created by the user, or someone else. I'm stripping the models of several unimportant fields for simplicity, but each contains the following: class Exercise(models.Model): # Basic Variables name = models.CharField(max_length=128) description = models.TextField(null=True, blank=True) def __str__(self): return self.name class ExerciseTemplate(models.Model): # Foreign Models workout = models.ForeignKey( 'Workout', on_delete=models.SET_NULL, null=True, blank=True ) exercise = models.ForeignKey( Exercise, on_delete=models.SET_NULL, null=True, blank=True ) recommended_sets = models.PositiveIntegerField(null=True, blank=True) class ExerciseInstance(models.Model): """ Foreign Models """ exercise_template = models.ForeignKey( ExerciseTemplate, on_delete=models.SET_NULL, null=True, blank=True ) workout = models.ForeignKey( 'Workout', on_delete=models.SET_NULL, null=True, blank=True ) """ Fields """ weight = models.PositiveIntegerField(null=True, blank=True) reps = models.PositiveIntegerField(null=True, blank=True) Create a WorkoutInstance from a WorkoutTemplate. The WorkoutTemplate is made up of ExerciseTemplates. But the WorkoutInstance should be able to take the WorkoutTemplate and populate it with ExerciseInstances based on the ExerciseTemplates in the WorkoutTemplate. Here are the models that I have so far: … -
Exposing React App with Local MySQL Database to Internet Using Ngrok
I am very new to ngrok, so please bear with me. I have a very simple React test app that is using Django as a server and local MySQL database. Django pulls/inserts some info from the local database and sends to the frontend. Everything works well. What I'm trying to do is expose this local app to public Internet. I have successfully installed and configured Ngrok, established a tunnel and was able to view the app on a different computer through the address generated by Ngrok. The problem is, I was able to see only the UI that is not related to the database. All data that React pulls from the local database, was not visible when I used a different computer. My question is, is there a way to use the same app through Ngrok and get the same data from the local MySQL database that I see when I just run the app locally? I know that I can create another tunnel that exposes the port MySQL or Django are running on (3306 and 8000 respectively) but if I do this, how would I access the data through Ngrok? Would I need to change anything in React code? … -
Django - Passing an extra argument from template to urls.py to class-based view
Basically, I would like to transition from a page showing a table (which is the result of a user query), to a page where the user can edit an entry in the table (this page is built using UpdateView), and then straight back to the previous page but this time showing the table with the new update reflected. There are other posts on similar situations but none seem to show how to implement this using a class-based view, so any advice here would be most appreciated. So far I have come up with the approach below. Here, I am trying to pass a parameter holding the URL of the table page, from the template for the table page to urls.py and then onto the view. However, I don't think I am using the correct syntax in urls.py as the value of the previous_url parameter in the view is simply "previous_url". Link in the template for the table page <a href="{% url 'entry_detail' item.pk %}?previous_url={{ request.get_full_path|urlencode }}">Edit</a> URL path('entry/<int:pk>/edit/', EntryUpdateView.as_view(previous_url="previous_url"), name='entry_update'), View class EntryUpdateView(LoginRequiredMixin, UpdateView): model = Entry template_name = 'entry_update.html' fields = ('source', 'target', 'glossary', 'notes') previous_url = "" def form_valid(self, form): obj = form.save(commit=False) obj.updated_by = self.request.user obj.save() return … -
django.core.exceptions.ImproperlyConfigured: Cannot import 'mainApp'. Check that 'apps.mainApp.apps.MainappConfig.name' is correct
I have cloned this project from github and their were some modules which i needed to install which are their in the "requirements.txt" file. Earlier I was getting the errors while installing this file as well. Later i updated the versions of some module and this file run but It started backtracking and it continued for almost 12 hours then i cancelled it. And after running the manage.py filecode, it shows the following error: C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\__init__.py:102: RequestsDependencyWarning: urllib3 (1.26.4) or chardet (5.0.0)/charset_normalizer (2.0.12) doesn't match a supported version! warnings.warn("urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported " C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\requests\__init__.py:102: RequestsDependencyWarning: urllib3 (1.26.4) or chardet (5.0.0)/charset_normalizer (2.0.12) doesn't match a supported version! warnings.warn("urllib3 ({}) or chardet ({})/charset_normalizer ({}) doesn't match a supported " Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\site-packages\django\apps\config.py", line 245, in create app_module = import_module(app_name) File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'mainApp' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\DELL\AppData\Local\Programs\Python\Python310\lib\threading.py", line … -
Different between template_name and template_name_field?
class ArticleDetailView(DetailView): template_name = None template_name_field = None 1)Why template_name_field default value is None? 2)template_name vs template_name_field -
Python virtual environment does not have a scripts folder and cannot be activate
I am new at programming and I want to work with Python and meanwhile with the Django Framework. For installing a venv I use "python3 -m venv ./venv/drf" and insert this in a terminal in VS code. I found this on my research about my problem. But when I installed the venv there is not a script folder in the venv folder. For activating my venv I tried "source .venv/drf/bin/activate" but this is neither working. I am working on a mac and I installed Python previously. I even installed Django on VS code. What can I do to implement the scripts folder and activate my venv? -
How Can I Verify that Django @cached_property is Cached?
In the below example, I have questions. Example from django.utils.functional import cached_property class Product(models.Model): class ProductType(models.TextChoices): PRODUCT = 'PRODUCT', _('Product') LISTING = 'LISTING', _('Listing') my_model = models.ForeignKey(MyModel, on_delete=models.CASCADE, related_name='products') product_type = models.CharField(max_length=7, choices=ProductType.choices) class MyModel(models.Model): ... @cached_property def listing(self): return self.products.get(product_type=Product.ProductType.LISTING) Questions Is the listing property being cached on the MyModel object? I ask because it's accessing .get() of a queryset which has greater implications. Ex: instance = MyModel() instance.listing # hits db instance.listing # gets from cache? How can I set up a scenario to inspect and verify that caching of instance.listing is in-fact happening? I read to look in the __dict__ method of instance.listing.__dict__ but I don't notice anything specific.