Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
unable to print the username onto console in JavaScript
I have a html file with a linked js <script type="text/javascript" src="{% static 'js/cart.js' %}"> var user= '{{request.user}}' </script> and in cart.js i am trying to print the user variable but i keep getting an error saying uncaught ReferenceError user is not defined. any ideas on how to resolve this? -
Can't access django admin [closed]
I cannot open django admin. What is the solution? INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ]``` [enter image description here][1] [1]: https://i.stack.imgur.com/EGt75.png -
How to insert a search engine instead of a list in the Django model
I am creating a model and a field is presented as a list, I would like it not to be a list but a search engine, this in the administrator when I want to insert new data in my table, I would like the author part to be a search engine and not a list. from django.conf import settings from django.db import models from django.utils import timezone class Post(models.Model): author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title enter image description here I don't know if this can be done in the model. -
javascript frontend received error 414 request URI too long when fetching an image from Django backend
I have a front end application, and that sends a string to backend. The backend then fetches an image, and returns it back to frontend as a jsonresponse. From the front end, I can console.log the image, and I know that I have received it. However, I still gets the 414 URI too long error from both frontend and the backend that sends the image to frontend. The frontend request is a POST but if I change it to GET, I get the same error. Also, everything worked as expected and I do see the image being inserted inside the img tag. Still I don't get the error message. async logoDropSelect (event) { //Fetch logo from backend and display it on front end img tag const response = await fetch(`getLogo/${this.newsletterLogoDropdown.value}`, { method:'POST', credentials:'same-origin', headers:{ 'Content-Type': 'application/json', 'Accept' : 'application/json', }, redirect: 'follow', body: JSON.stringify({}), }); const responseJson = await response.json(); this.newsLetterLogo.src = `data:image/png;base64,` + responseJson['image']; this.writeTemplateToIframe(this.hiddenHTML.innerHTML); } The code on the backend class FetchLogo(NewsletterViewPermissionMixin, View): def post(self, request, restaurantLogo, *args, **kwargs): data = dict() if restaurantLogo == 'restaurant1': image = Image.open('path_to_logo1.png') image = self.resizeImage(image = image, width = 300) if restaurantLogo == 'restaurant2': image = Image.open('path_to_logo2.png') image = self.resizeImage(image = … -
Is there a difference in authentication\authorization in Django and Django Rest Framework?
I am learing Django and Django REST Framework for project I recently added authorization/authentication in the Django project, and after that created API for the app, and for that I installed DRF. -
when I export posts from django I get <django_quill.fields.FieldQuill object at 0x7f0746389840>?
I'm working on Django blog and I want to export posts and I made it work but I have a problem when exporting text because I used Quill - rich text editor. body = QuillField() And when I export posts in excel, I got this <django_quill.fields.FieldQuill object at 0x7f0746389840>. excel is looking like this, image This is resources.py from import_export import resources from .models import Post class PostResource(resources.ModelResource): class Meta: model = Post This is views.py def export_data(request): if request.method == 'POST': # Get selected option from form file_format = request.POST['file-format'] post_resource = PostResource() dataset = post_resource.export() if file_format == 'CSV': response = HttpResponse(dataset.csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="exported_data.csv"' return response elif file_format == 'JSON': response = HttpResponse(dataset.json, content_type='application/json') response['Content-Disposition'] = 'attachment; filename="exported_data.json"' return response elif file_format == 'XLS (Excel)': response = HttpResponse(dataset.xls, content_type='application/vnd.ms-excel') response['Content-Disposition'] = 'attachment; filename="exported_data.xls"' return response return render(request, 'dashboard/export.html') Any idea how to get the text in this body column? Thanks in advance! -
How to increase django/nxginx/uwsgi page load size limit?
I am using nginx and uWsgi with django (using daphne) to serve a simple one page site. I have reached a point where if I put more html objects on the page it loads to a certain point and does not load the rest. For example if I add a table with 60 rows the site loads the table up to 30 rows and nothing after that table loads. Or if I put 30 cards with text on it on the page, it loads a certain number of cards and does not load the rest of the site. If I only put 15 cards it loads the entire site. It is literally the html objects after the x amount of cards or rows that don't load. If I tap F-12 the rest of the site is just missing after the x cards or x rows. There are no errors or anything. This is what my nginx config looks like: # build_check_nginx.conf # the upstream component nginx needs to connect to upstream django { server unix:///path/to/build_check.sock; # for a file socket } # configuration of the server server { # the port your site will be served on listen 80; # … -
how to install all packages in the pipfile with pipenv in django project?
i want to install all python packages exist on the pipfile but when i run pipenv install command i received An error occurred while installing wcwidth==0.2.5 --hash=sha256:c4d647b99872929fdb7bdcaa4fbe7f01413ed3d98077df798530e5b04f116c83 --hash=sha256:beb4802a9cebb9144e99086eff703a642a13d6a0052920003a230f3294bbe784! Will try again. An error occurred while installing whitenoise==6.2.0 ; python_version >= '3.7' --hash=sha256:8fa943c6d4cd9e27673b70c21a07b0aa120873901e099cd46cab40f7cc96d567 --hash=sha256:8e9c600a5c18bd17655ef668ad55b5edf6c24ce9bdca5bf607649ca4b1e8e2c2! Will try again. Installing initially failed dependencies... [pipenv.exceptions.InstallError]: Collecting appnope==0.1.3 [pipenv.exceptions.InstallError]: Using cached appnope-0.1.3-py2.py3-none-any.whl (4.4 kB) [pipenv.exceptions.InstallError]: Collecting asgiref==3.5.2 [pipenv.exceptions.InstallError]: Using cached asgiref-3.5.2-py3-none-any.whl (22 kB) [pipenv.exceptions.InstallError]: Collecting asttokens==2.0.8 how can i fix this? -
owl-carousel items which are looped through by Django aren't displayed correctly
let me start by saying that i have only done back end programming and have never used jquery before so i don't know how to setup owl carousel properly. i have downloaded this html+css+js template for my project, it uses owl-carousel to show items from my database. i am passing all items as context from views.py to the template and am trying to show them all in a carousel. the first item works alright but the second one doesn't(i currently have only 2 items in my database) following is the code plus the picture of the current output: <section class="product_area mb-60"> <div class="container"> <div class="row"> <div class="col-12"> <div class="product_header"> <div class="section_title"> <h2>تازه رسیده ها</h2> </div> </div> </div> </div> <div class="tab-content"> <div class="tab-pane fade show active" id="glasses" role="tabpanel"> {% for product in products %} <div class="product_carousel product_column5 owl-carousel"> <div class="single_product"> <div class="product_thumb"> <a class="primary_img" href="product-details.html"> <img src="{{product.primaryURL}}" alt=""> </a> <a class="secondary_img" href="product-details.html"> <img src="{{product.secondaryURL}}" alt=""> </a> <div class="action_links"> <ul> <li class="compare"> <a href="compare.html" title="مقایسه"> <i class="icon-repeat"></i> </a> </li> <li class="quick_button"> <a href="#" data-toggle="modal" data-target="#modal_box" title="نمایش سریع"> <i class="icon-eye"></i> </a> </li> </ul> </div> <div class="add_to_cart"> <a href="cart.html" title="افزودن به سبد">افزودن به سبد</a> </div> </div> <div class="product_content"> <p class="manufacture_product"> <a href="#">{{product.name}}</a> </p> <h4> … -
getting <django.db.models.query_utils.DeferredAttribute object at 0x000001E07253C400> while trying to add new document
this is the model document class Document(AbstractItem, HitCountMixin): """Book document type to store book type item Child class of AbstractItem """ ITEM_INTERACTIVE_TYPE = ( ("yes", _("Yes")), # ("no", _("No")), ("NA", _("Not applicable")), ) DOCUMENT_TYPE = ( ("book", _("Book")), ("working paper", _("Working paper")), ("thesis", _("Thesis")), ("journal paper", _("Journal paper")), ("technical report", _("Technical report")), ("article", _("Article")), ("exam sets", _("Exam sets")) ) DOCUMENT_FILE_TYPE = ( ("ppt", _("PPT")), ("doc", _("Doc")), ("docx", _("Docx")), ("pdf", _("PDF")), ("xlsx", _("Excel")), ("epub", _("Epub")), ("rtf", _("Rtf")), ("mobi", _("Mobi")), ) collections = models.ManyToManyField( Collection, verbose_name=_("Add to these collections"), ) document_type = models.CharField( _("Document type"), max_length=40, # TODO: Change to match the exact value. choices=DOCUMENT_TYPE, ) document_file_type = models.CharField( _("Document file format"), choices=DOCUMENT_FILE_TYPE, max_length=23, default="pdf" ) document_series = models.ForeignKey( "DocumentSeries", verbose_name=_("Series"), #on_delete=models.CASCADE, on_delete=models.SET_NULL, blank=True, null=True ) education_levels = models.ManyToManyField( EducationLevel, verbose_name=_("Education Levels"), blank=True ) grades_subjects_chapters = models.ManyToManyField( GradeSubjectChapter, verbose_name=_("Grade>Subject>Chapter"), blank=True ) languages = models.ManyToManyField( Language, verbose_name=_("Language(s)"), # null=True, blank=True ) document_interactivity = models.CharField( verbose_name=_("Interactive"), max_length=15, choices=ITEM_INTERACTIVE_TYPE, blank=True, default="NA" ) # This field should be same on all other model to make searching easy in search engine. type = models.CharField( max_length=255, editable=False, default="document" ) document_total_page = models.CharField( verbose_name=_("Total Pages"), blank=True, validators=[validate_number], max_length=7 ) document_authors = models.ManyToManyField( Biography, verbose_name=_("Author(s)"), related_name="authors", blank=True, ) document_editors = … -
What is the correct way to store images in Django backend?
Hello I am new to Django, mostly experienced in Node and mongoDb, I have figured out how to store save media such as images on the Django backend. And can retrieve the image on the client/frontend side. Yet all uploaded media to the site is saved in a media/files directory in the backend in their png/jpg formats. I am a bit confused if this is how it should be saved? I thought it would be converted into bytes and saved in the sql database. Just a bit confused as in mongodb there are npm packages that convert the media into bytes and save it the database ie: images are not kept in png/jpeg format. -
Django get_absolute_url is redirecting to random blog posts
I've created a website with a blog, and I'm trying to redirect the user to the previous blog post after sending a comment. However, it redirects to random blog posts rather than the previous one. Models.py: class Comment(models.Model): post = models.ForeignKey(Post, related_name="comments", on_delete=models.CASCADE) name = models.CharField(max_length=255) comment = models.TextField() date_posted = models.DateTimeField(default=timezone.now) def __str__(self): return self.post.title and self.name def get_absolute_url(self): return reverse('post-detail', kwargs={'pk':self.pk}) Views.py: class CommentView(LoginRequiredMixin, CreateView): model = Comment template_name = 'comment.html' fields = '__all__' def form_valid(self, form): form.instance.post_id = self.kwargs['pk'] return super().form_valid(form) urls.py: path('post/<int:pk>/', PostDetailView.as_view(), name='post-detail'), -
How to send docx file in bytes to frontend in Django?
I read the file in Django side as a python file: with open("file.docx", mode="rb") as f: bytes = f.read() and I send it: from django.http import FileResponse return FileResponse(bytes) In javascript I use this function: function downloadBuffer(arrayBuffer, fileName) { const a = document.createElement('a') a.href = URL.createObjectURL(new Blob( [ arrayBuffer ], { type: 'aapplication/vnd.openxmlformats-officedocument.wordprocessingml.document' } )) a.download = fileName a.click() } However the file is corrupted. How can I get the file correctly? -
Django forms.form returning empty choice list
I have my choices added through the init method for a given forms.form as shown below: def __init__(self, user, instance=None, *args, **kwargs): super(ProductColorVariationsForm, self).__init__(*args, **kwargs) self.fields["photo"].required = False files = () for file in instance.files.all(): files = files + ((file.id, file.file.url),) self.fields['photo'].choices = files In the template, I have the select list items as expected. However, I am unable to validate the form as it complains of the selected value not being in the available choices. Printing out the choices in the custom widget, gives me an empty tuple. class JQSelectMenuInputWidget(Select): template_name = "widgets/jqselectmenu.html" def __init__(self, attrs=None, choices=(), disabled_choices=()): super(JQSelectMenuInputWidget, self).__init__(attrs, choices=choices) self.disabled_choices = disabled_choices print(choices) So my question is, why is it that the choices that are set in the init method not being pass down the widget class. -
async django CBV methods post in class CreateVIew
I am need help in using async to python django in base class view. class IndexPage(CreateView): """Page index site""" async def post(self, request, *args, **kwargs) -> object: await send_code(data['email']) return render(request, 'activate.html') return super().post(request, *args, **kwargs) If you create this function simply as a function without a class, everything works fine, but an error occurs when using the class: IndexPAge HTTP handlers must either be all sync or all async. Please help anyone who has encountered this problem, thank you. -
I want to be able to update a user's password in my React.js and Django app
Backend is Dango The front end is made with React.js. What I want to achieve it I want to users to update their registered passwords. Issue/error message If you update the password on the React.js side, it will look like the following and the update will fail. . Django side Terminal {'password': 'welcome1313'} username {'detail': [ErrorDetail(string='Invalid data. Expected a dictionary, but got str.', code='invalid')]} Bad Request: /users/12/ [15/Jan/2023 15:42:10] "PATCH /users/12/ HTTP/1.1" 400 13 React.js const MyPagePasswordUpdate = () => { const [my_password, setValue] = useState(null); const [my_ID,setMyID] = useState(null); const isLoggedIn= useSelector(state => state.user.isLoggedIn); const { register, handleSubmit, errors } = useForm(); useEffect(() => { async function fetchData(){ const result = await axios.get( apiURL+'mypage/', { headers: { 'Content-Type': 'application/json', 'Authorization': `JWT ${cookies.get('accesstoken')}` } }) .then(result => { setValue(result.data.password); setMyID(result.data.id); }) .catch(err => { console.log("err"); }); } fetchData(); },[]); const update = async (data) =>{ console.log(data) await axios.patch(`${apiURL}users/`+my_ID+'/', { headers: { 'Content-Type': 'application/json', 'Authorization': `JWT ${cookies.get('accesstoken')}` }, password:data.password, }, ).then(message => { alert("Updated!") }) .catch(err => { console.log("miss"); alert("The characters are invalid"); }); }; return ( <div> {isLoggedIn ? <div class="update-block"> <form onSubmit={handleSubmit(update)}> <label for="password">Password:</label> <input className='form-control' type="password" {...register('password')} /> <input className='btn btn-secondary' type="submit" value="Update" /> </form> <Link to="/mypage">Back to … -
How do I build a django chat app with multiple chat rooms?
I've build a real time chat app using django channels, but all the users can only connect to the same chat room even if they're in a different urls, there is only one websocket connection, I want to know how I can make it so each chat room url would be a different websocket connection. I've tried to use the following code so every url 'chat-room/<chat_room_id>' would be a different chat room, but if I go to chat-room/1 and send a message, the same message appears on chat-room/2 here is my code: consumers.py import json from channels.generic.websocket import AsyncWebsocketConsumer from asgiref.sync import async_to_sync class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.room_group_name = 'test' await self.channel_layer.group_add( self.room_group_name, self.channel_name ) await self.accept() async def receive(self, text_data): text_data_json = json.loads(text_data) message = text_data_json['message'] author = text_data_json['author'] await self.channel_layer.group_send( self.room_group_name, { 'type':'chat_message', 'message':message, 'author':author } ) async def chat_message(self, event): message = event['message'] author = event['author'] await self.send(text_data=json.dumps({ 'type':'chat', 'message':message, 'author':author })) routing.py from django.urls import re_path from . import consumers websocket_urlpatterns = \[re_path(r'ws/socket-server/', consumers.ChatConsumer.as_asgi())] urls.py from django.urls import path from . import views urlpatterns = \[path('chat-room/<int:chat_room_id>', views.chat_room, name='chat-room')] views.py from django.shortcuts import render, HttpResponse, redirect def chat_room(request, chat_room_id): if request.user.is_authenticated: return render(request, 'chat-room.html') else: return … -
django Count aggregate is not working as I intended
It's a code that reproduces the problem I experienced. models.py from django.db import models class User(models.Model): pass class Group(models.Model): users = models.ManyToManyField( User, related_name='groups', ) class Notice(models.Model): groups = models.ManyToManyField( Group, related_name='notices', ) tests.py from django.test import TestCase from tests.models import User, Group, Notice from django.db.models.aggregates import Count def print_user_count(group): count = group.users.count() annotate_count = ( Group.objects .annotate( user_count=Count('users'), notice_count=Count('notices') ) .get(id=group.id) .user_count ) print('count: %d, annotate_count: %d' % (count, annotate_count)) class ModelTestCase(TestCase): def test_(self): user1 = User.objects.create() group1 = Group.objects.create() group1.users.set([user1]) print_user_count(group1) # count: 1, annotate_count: 1 for _ in range(5): notice = Notice.objects.create() notice.groups.set([group1]) print_user_count(group1) # count: 1, annotate_count: 5 I didn't add users to the group. But the value obtained using annotate has increased from 1 to 5. Is this a bug? Or did I use something wrong? -
pytest fail on github action. TypeError: expected str, bytes or os.PathLike object, not NoneType
when run pytest on local works well. but it fail on github actions . I set secret key on github settings and uploaded .env.test to github repository both. Is it dotenv package problem? or else? What is the cause? Please give me solution thank u workflow.yml file name: Django CI on: [pull_request, push] # activates the workflow when there is a push or pull request in the repo jobs: test_project: runs-on: ubuntu-latest # operating system your code will run on steps: - uses: actions/checkout@v2 env: SERVER_ENV: "test" DEBUG: ${{secrets.SECRET_KEY}} SECRET_KEY: ${{secrets.SECRET_KEY}} DB_ENGINE: ${{secrets.DB_ENGINE}} DB_NAME: ${{secrets.DB_NAME}} USER: ${{secrets.USER}} PASSWORD: ${{secrets.PASSWORD}} POSTGRES_USER: ${{secrets.POSTGRES_USER}} POSTGRES_PASSWORD: ${{secrets.POSTGRES_PASSWORD}} POSTGRES_DB: ${{secrets.POSTGRES_DB}} HOST: ${{secrets.HOST}} PORT: ${{secrets.PORT}} CELERY_BROKER_URL: ${{secrets.CELERY_BROKER_URL}} LOG_LEVEL: ${{secrets.LOG_LEVEL}} NAVER_NEW_API_CLIENT_ID: ${{secrets.NAVER_NEW_API_CLIENT_ID}} NAVER_NEW_API_CLIENT_SECRET: ${{secrets.NAVER_NEW_API_CLIENT_SECRET}} DJANGO_ALLOWED_HOSTS: ${{secrets.DJANGO_ALLOWED_HOSTS}} - uses: actions/setup-python@v2 - name: Install Dependencies run: pip install -r requirements.txt # install all our dependencies for the project - name: Run Pytest run: pytest . # run pytest test error log Traceback (most recent call last): File "/opt/hostedtoolcache/Python/3.11.1/x64/bin/pytest", line 8, in <module> sys.exit(console_main()) ^^^^^^^^^^^^^^ File "/opt/hostedtoolcache/Python/3.11.1/x64/lib/python3.11/site-packages/_pytest/config/__init__.py", line 190, in console_main code = main() ^^^^^^ File "/opt/hostedtoolcache/Python/3.11.1/x64/lib/python3.11/site-packages/_pytest/config/__init__.py", line 148, in main config = _prepareconfig(args, plugins) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/hostedtoolcache/Python/3.11.1/x64/lib/python3.11/site-packages/_pytest/config/__init__.py", line 329, in _prepareconfig config = pluginmanager.hook.pytest_cmdline_parse( ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/opt/hostedtoolcache/Python/3.11.1/x64/lib/python3.11/site-packages/pluggy/_hooks.py", line 265, … -
Django Form and some ForeingKey fields
Please tell me, when a model has a lot of related fields with other tables, how to make a normal form with filling such a model? How do I create a form for Project? class City(models.Model): obl = models.CharField(max_length=255, choices=REGIONS, default="24", verbose_name="Регион") name = models.CharField(max_length=128, verbose_name="Город") population = models.IntegerField() class Address(models.Model): city = models.ForeignKey(City, on_delete=models.PROTECT, verbose_name="Город") street = models.CharField(max_length=255, verbose_name="Улица") numb = models.CharField(max_length=64, verbose_name="Номер дома") class Project(models.Model): manager = models.ForeignKey(User, on_delete=models.PROTECT, verbose_name="Сотрудник") address = models.ForeignKey(Address, on_delete=models.PROTECT, verbose_name="Адрес") vis = models.DateField(verbose_name="Подписан дата", blank=True) accept = models.DateField(verbose_name="Принят дата", blank=True) Maybe I need a step-by-step fill-in form -
How to update all parts of a web page containing the same object without reloading the page?
I'm using Javascript to make part of my web page editable for logged-in admin users. In one page, I have cards that display information about three people from the database. The cards contain username, skills, and bio fields. The username is also used a second time in the bio. When the edit button is clicked, the first username, skills, and the bio without the username become editable. And when I change the username and click on the save button only the first username changes. For the one in the bio to update I need to reload the page even though they have the same id in my HTML template. How can I change the second one as well without reloading the page? about.html: % extends "potbs/layout.html" %} {% load static %} {% block script %} <script src="{% static 'potbs/about.js' %}"></script> {% endblock %} {% block body %} <div class="container"> <div class="row justify-content-center"> {% for member in team_members %} <div class="col" id="border"> <!--If user is admin, show edit button--> {% if user.is_superuser %} <div class="position-relative" id="edit_button_{{member.id}}" style="display: block;"> <button class="btn btn-lg position-absolute top-0 end-0" id="edit_profile" data-id="{{member.id}}" data-username="{{member.username}}"> <i class="fa fa-edit fa-solid" style="color: white; margin-right: 5px;"></i></button> </div> {% endif %} <div class="col-xs-12 … -
django 'bool' object is not callable exception while saving models
I have user model which is like: class User(AbstractUser): auth_sub = models.CharField(max_length=200, null=True) class Meta: db_table = "auth_user" but while saving models with user.save() following exception is raised: --bool' object is not callable-- Any help? Thanks I looked all fields for this model. But only extra field is auth_sub which is not used as in-built fields for AbstractUser. -
How to create single column Filter (Choices) Drop-down (select) Django form?
Good day! I would be very grateful for any help. I have a model. There are repeating elements in one column of this model. I want to inject the result of a query into a view. The result of a query with a single column filter. That is, it turns out that I want to take from the model only those rows of the table -->> where the value is equal to the one selected from the drop-down menu (in a simple filter form). ['Gary', 'Henry', 'Shtefan', 'Villi'] For example, select only those rows in the row (empname) whose value is equal to Shtefan. Without the use of a static, manual entry in the code. Since it is possible that when the model table is replenished - with new data - there will be additions with other names. Is it possible somehow to take unique values without duplicates from the corresponding column and automatically use them in the filter? To be placed in a drop-down menu form (in a simple filter form). static class Developer(models.Model): JUNIOR = 'JR' MIDDLE = 'ML' SENIOR = 'SR' LEVEL_CHOICES = ( (JUNIOR, 'Junior'), (MIDDLE, 'Middle'), (SENIOR, 'Senior'), ) name = models.CharField(max_length=200) level = models.CharField(max_length=2, … -
Vitejs/Rollupjs/Esbuild: bundle content scripts for chrome extension
How to correctly bundle content scripts for a chrome extension using Vite.js? Content scripts do not support ES modules (compared to background service worker), so every content script javascript file should not have any import/export statements, all libraries and other external imports should be inlined in every content script as a single file. I'm currently using the following vite configuration, where I programmatically pass all my content script paths as the entry. vite.config.ts export const extensionScriptsConfig = ( entry: string[], outDir: string, mode: Env, ): InlineConfig => { const config = defineConfig({ root: __dirname, mode, build: { outDir, emptyOutDir: false, minify: false, copyPublicDir: false, target: 'esnext', lib: { entry, formats: ['es'], fileName: (_, entry) => entry + '.js', }, }, }); return { configFile: false, ...config }; }; entry contains the following paths Directory: C:\Users\code\extension\src\content-scripts Mode LastWriteTime Length Name ---- ------------- ------ ---- -a--- 15/01/2023 14:11 1135 inject-iframe.ts -a--- 15/01/2023 14:11 2858 inject.ts -a--- 14/01/2023 17:49 223 tsconfig.json The setup above works correctly - each content script is a separate file with no import. But when I try to import a node_module into inject-iframe.ts and inject.ts the following happens in the dist folder: dist\src\content-scripts\inject.js import { m as mitt } … -
Why is path imported once in Settings. py and again in urls.py in Django
I am new to Django. I noticed that path command is imported once in Settings.py and then again in Urls.py. From the name "Settings.py", I assumed that Settings.py will always get loaded first when we run a project as it contains, again as I assumed, the settings to be applied for the project. If that is correct, then why does path get imported again in Urls.py when Django already imported this once in Settings.py? If not, can you please elaborate so I understand why Settings.py and Urls.py can run independently. I did try to google to see if I could get the answer myself but did not find any. Thanks.