Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Do I need to replace old virtual env with new inside django project?
I had to run an old django project in a new virtual environment to see if I could make migrations as it wouldn't work for the original virtual env. In this other virtual env I already just had a basic project so I think it's ok to reuse the name. However, my old project still has the old virtual environment in the project directory. Should I delete it, and replace with this new one, or just continue running project in new environment without adding new virtual env to the project? -
how to prepare a good JSON file - django
Hope you are doing well ! I don't know how to make a good queryset in my views.py here this is my models.py class Evenement(models.Model): EVENEMENT_CHOICES = ( ("déposé","déposé"), ("reçu","reçu"), ("expédié","expédié"), ("affecté","affecté"), ("livré","livré"), ("echec de livraison","echec de livraison"), ) mail_item_fid = models.ForeignKey(mail_item,on_delete=models.CASCADE, related_name='mail_item_fid_evenement') from_office = models.ForeignKey(Office,on_delete=models.CASCADE, related_name='office_Evt_evenement') date_Evt = models.DateField() status = models.CharField(max_length=50,choices=EVENEMENT_CHOICES) agent_delivery_cd = models.ForeignKey(Delivery_Agent,on_delete=models.CASCADE,blank=True, null=True ,related_name='agent_evenement') def __str__(self): return '{}, {}, {}, {} '.format(self.mail_item_fid,self.from_office,self.date_Evt,self.status) I want a json file like below : Date : 15/06/2020 from_post : X affecte : 100 J+0 : 50 J+1 : 25 J+2 : 25 Date : 15/06/2020 from_post : Y affecte : 1000 J+0 : 400 J+1 : 250 Date : 15/06/2020 from_post : Z affecte : 150 J+0 : 25 J+1 : 50 Date : 16/06/2020 from_post : X affecte : 1000 J+0 : 500 J+1 : 250 J+2 : 25 Date : 16/06/2020 from_post : Y affecte : 1050 J+0 : 400 J+1 : 250 Date : 16/06/2020 from_post : Z affecte : 1000 J+0 : 25 J+1 : 50 I should do the day difference between two status 'affecte' and 'livre' , for example I have -
Django React How to fix Access-Control-Allow-Origin error when redirecting to login page
It appears that when visiting the port 3000 run by npm, the request is redirected to the login page and and the access gets blocked by CORS: Access to XMLHttpRequest at 'http://localhost:8000/accounts/login/' (redirected from 'http://localhost:8000/api/doits') from origin 'http://localhost:3000' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. My settings: CORS_ORIGIN_ALLOW_ALL = True CORS_URLS_REGEX = r'^/api/.*$' MIDDLEWARE = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'django.middleware.common.CommonMiddleware', ... INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # 3rd party apps 'corsheaders', 'rest_framework', 'crispy_forms', ... What am I missing? I am running Django 1.11 and django-cors-headers 3.2 -
Python loop execution time measurement doesn't add up
I'm trying to measure the execution time of this loop. I start one timer outside the loop, and another one inside (start_time_2 and start_time), and then summing then respectively (all_time_2 and all_time). Now please correct me if I'm wrong, but the two should be exactly, or at least around the same result, no? Currently I'm using timedelta to calculate the elapsed time. I also tried time.time(), but it gave the same result. all_time ends up with a value around 7 seconds, while all_time_2 ends up around 0.06 seconds. I'm absolutely desperate at this point, so any help is much appreciated! The code: start_time_2 = time.monotonic() for result in text_search_recommended: start_time = time.monotonic() search_values_length = len(search_values) - 1 search_matched = [] for value2 in search_values: if value2 != value: county_str = get_county_by_id(all_counties, result['county_id']) if value2.lower() in result['service_name'].lower() or value2.lower() in result['city'].lower() or value2.lower() in result['traits'].lower() or value2.lower() in result['type_of_cars'].lower() or value2.lower() in county_str.lower(): search_matched.append(True) if len(search_matched) == search_values_length: if not result in recommended_services: recommended_services.append(result) end_time = time.monotonic() all_time = all_time + timedelta(seconds=end_time - start_time) end_time_2 = time.monotonic() all_time_2 = all_time_2 + timedelta(seconds=end_time_2 - start_time_2) -
What are the steps which i need to follow connection of my website with different website's api using mulesoft in django framework?
i need to develop a website where i need to connect it with different website's using api connectivity ,I am using django framework and want to use mulesoft for api connection ? Can the work be done and what are the steps ? -
Django rest - Update Nested Related data
I'm trying to update my nested serialized data with Django rest. I have nested data like below: [ { "id": 1, "name_eng": "Mongkol Borei", "name_kh": "មង្គលបុរី", "province": { "id": 1, "name_eng": "Banteay Meanchey", "name_kh": "បន្ទាយមានជ័យ" } } ] And My code in ModelViewset def partial_update(self, request, *args, **kwargs): instance = self.queryset.get(pk=kwargs.get('pk')) instance.name_eng = self.request.data.get( 'name_eng', instance.name_eng) instance.name_kh = self.request.data.get( 'name_kh', instance.name_kh) province = instance.province # return HttpResponse(instance.province.pk) province.name_kh = self.queryset.get( 'province', instance.province.name_kh) serializer = self.serializer_class( instance, data=request.data, partial=True) serializer.is_valid(raise_exception=True) serializer.save() return Response(serializer.data) But what i got is error too many values to unpack (expected 2). Still no clue what goin' on.. I'll appreciate of all ur help.. Thanks:)) -
How to learn Machine learning fundamentals?
I want to start learning machine learning.So, I am 16yr old and learnt the basics of python.Can anyone tell me the resources from where should I learn machine learning and maths behind it?(Maths is very Important) -
How to store id in database but to show name in modelchoicefield in Django?
Here is my code in forms.py manager_idd=forms.ModelChoiceField(label="Manager",widget=forms.Select(attrs={"class":"form- control"}),queryset=Manager.objects.all().values_list('id','name',named=True) I am trying to show names in choice field but want to get id of selected name, as this is a foreign key in database. I want to save it as an id in database but to show as name in choice field. How can i do that? -
Django manytomany fields are not included in api call
models: class Light(models.Model): name = models.CharField(max_length=255, default="neues Licht", null=False, blank=False) percentage = models.IntegerField(default=0, null=False, blank=False) def __str__(self): return self.name class LightGroup(models.Model): name = models.CharField(max_length=255, default="neue Gruppe", null=False, blank=False) lights = models.ManyToManyField(Light,related_name='groups') def __str__(self): return self.name views: def get(self, request, *args, **kwargs): lights = Light.objects.all().values() lights_list = list(lights) return JsonResponse(lights_list, safe=False) result: [{"id": 2, "name": "light 1", "percentage": 3}] How do I include the groups in the jsonresponse? The connection does show up when viewing groups in the admin panel. But even when I try to read from the LightGroup Model, the associated Lights do not show up. -
How to convert a string into datetime with format directives from another Timezone with Python 3
I have function in my Django application that pulls informations from SSH. I get a raw date string like the following (French language): 'mar. 27 mars 2012 17:51:42 CEST' My issue is that I need to convert this string to a datetime object before passing it to update one of my model, but I get an error. ssh_output = 'mar. 27 mars 2012 17:51:42 CEST' my_datetime = datetime.datetime.strptime(ssh_output,"%a. %d %B %Y %H:%M:%S CEST") Above code throws an exception: time data 'mar. 27 mars 2012 17:51:42 CEST' does not match format '%a. %d %B %Y %H:%M:%S CEST' I'm confused because locale.getlocale() outputs: " ('fr_FR', 'UTF-8') But testing datetime format with datetime.datetime.now().strftime("%a %d %B %Y %H:%M:%S %Z") outputs (English language): Wed 08 July 2020 15:46:11 Also, all date format directives seems correct (plus literal strings '.' and 'CEST'): %a : Weekday as locale’s abbreviated name. %d : Day of the month as a zero-padded decimal number. %B : Month as locale’s full name. %Y : Year with century as a decimal number. %H : Hour (24-hour clock) as a zero-padded decimal number. %M : Minute as a zero-padded decimal number. %S : Second as a zero-padded decimal number. So it seems that … -
NoReverseMatch Error Reverse for 'profile' with no arguments not found
Please somebody anybody help please, know that these question has been answered a lot of times but am new to django and don't know how to get around this in my code. Am following a tutorial and that builds a vlog with django. Everythin works fine but then i wanted to modify it and dispaly the posts written by a user aon their profile page so that others can see it. i passed a variable to the original url that lead to the page and then also modify my views that only rendered a html template to include posts from the user. it works the post are listed the way i want but after i go to the update profile page and update on submit the button that was supposed to redirect to the profile page returns an error NoReverseMatch at /update_profile/ Reverse for 'profile' with no arguments not found. 1 pattern(s) tried: ['profile/(?P<username>[^/]+)/$'] My urls.py file from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static from django.contrib.auth import views as auth_views from users import views as user_views urlpatterns = [ path('admin/', admin.site.urls), path('register/', user_views.register, name='register'), path('profile/<str:username>/', user_views.profile, name = 'profile'), path('update_profile/', … -
Hidden Username and Password in Django Comments not saving
I want to hide the username and email section of the comment area when a user is commenting, but after doing that ( or doing what I thought is something like that) the comment isn't being displayed. forms.py class CommentForm(forms.ModelForm): class Meta: model = Comment exclude = ('post', 'publish', 'active') widgets = { 'name': forms.HiddenInput, 'email': forms.HiddenInput, } the part of the views where the comment is if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): new_comment = comment_form.save(commit=False) # Save Comment without adding to db # The post field under Comment model has not been field # so we add the current post we are in to the post field new_comment.post = post new_comment.name = request.user.username new_comment.email = request.user.email new_comment.save() # save new comment to database comment_form = CommentForm() else: comment_form = CommentForm() the whole view containing things unrelated to this post(maybe it might be needed) def detail_display(request, year, month, day, post_slug, tag_slug=None): list_display(request) # to make use of the posts and tag variables new_comment = None post = get_object_or_404(Post, status = 'publish', publish__year = year, publish__month = month, publish__day = day, slug = post_slug ) comments = post.comments.filter(active=True) if request.method == 'POST': comment_form = CommentForm(request.POST) if comment_form.is_valid(): new_comment … -
Image and files are not loading from media folder in djnago --- TypeError: serve() got an unexpected keyword argument 'documents_root'
Image and other media files are not loading from database and media folder, I got these errors-- TypeError: serve() got an unexpected keyword argument 'documents_root' Internal Server Error: /media/default_img.jpg I tried everything it isn't working , all media settings are correct as per i know, all code is given below please see, can it be a problem with other things like django or python files? This is a model section-- class Media(models.Model): media_img = models.ImageField(upload_to='image', default='default_img.jpg') media_file = models.FileField(upload_to='documents', default='default_file.pdf') This is a views section-- def home(request): media_suff = Media.objects.all() return render(request, 'home.html', {'media_suff': media_suff}) This is a html template- {% for media in media_suff %} <div class="container "> <div class="jumbotron"> <img src="{{ media.media_img.url }}" style="float: right; margin: 10px" width=300px height=300px> <embed src="{{ media.media_file.url }}" width="300px" height="300px" /> </div> </div> {% endfor %} This is in url - from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', views.home, name='home'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) This is in settings -- MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
How i convert image in hexadecimal Code in django
How I use image in below code please tell me because its Need Hexadecimal code i dont underestimate what can i do ............................................................................................................................................................................................................................ I want to use image its place in this code which is get text response from button code in my views:. views.py def likePost(request): user= request.user pk=request.POST.get("post_id",'') post_obj=Post.objects.get(pk=pk) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like,created=Like.objects.get_or_create(user=user,post_id=pk) if not created: if like.value =='Like': like.value ='Unlike' else: like.value ='Like' like.save() return redirect('user_homeview:userview') return HttpResponse("Liked") def post_serialized_view(request): data=list(Post.objects.values()) return JsonResponse(data,safe=False) where i want to change code which line template.html const likeText=$(`.like-btn${post_id}`).text() if(trim=='like'){ $(`.like-btn${post_id}`).html('unlike') from which button get id below jquery code template.html In my template Where i am using jquery and javascript :; template.html <form method="POST" action="{% url 'user_homeview:like_dislike_post'%}" class="like-form" id="{{i.id}}" > {% csrf_token %} <input type="hidden" name='post_id' id='post_id' value="{{i.pk}}"> <button id="like" class="like like-btn{{ i.id }}"> {% if request.user in i.liked.all%} <img src='{% static "images\like.png" %}' class="mt-2 settin"></button> {% else %} <img src='{% static "images\unlike.jpg" %}' class=" settin"> {% endif %} </button> <script> $(document).ready(function(){ $('.like-form').submit(function(e){ e.preventDefault(); console.log('Works done') const post_id=$(this).attr('id') console.log(this) console.log(post_id) const likeText=$(`.like-btn${post_id}`).click().image() console.log(likeText) const trim = $.trim(likeText) console.log(trim) const url =$('.like-form').attr('action') console.log(url) $.ajax({ type: 'POST', url:url, data:{ 'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(), 'post_id':post_id, }, success:function(){ console.log('success') $.ajax({ type:'GET', url:'http://127.0.0.1:8000/user_homeview/serilized/', success:function(response){ console.log(response) $.each(response,function(index,element){ … -
How do I send user input through AJAX to Django REST API and return result after function API calculation?
I want to learn creating RESTful API's and having AJAX communicating between the backend and frontend, and would like to do it using Python. I know Python pretty well but have troubles to understand the structure and flow of web applications and how F/E and B/E communicate with each other. Due to this, I would like my website to communicate with my backend RESTful API using AJAX (for educational purposes only. My example application With his in mind, I want to create a simple web application (website) that counts the number of occurrences of a word in a larger text area that users put in. The sequential use case will be: User (client) enters a word to be examined in a textfield: "Hello" (input="text") User (client) enters one or many paragraphs to look into: "Hello my name is Charles" (input="textarea") User (client) presses "Submit"-button User (client) receives an updated text (asynchronously) with the number of occurrences of his word in the entered paragraph(s): "The word 'Hello' occurred 1 time in your text!" (asynchronously modified tag) My problem and questions The website is done with two fields and one button. Now here's my problem: How does the AJAX integration and workflow … -
Relative media paths in TextFields for S3
I have a load of models that have TextFields which (sometimes) contain links to images which the users have uploaded when they edited those fields. So a field might contain something like this:- This is my image <img src="/media/uploads/myimage.jpg"> This works fine at the moment, as all of my media is being served from a directory on my web server by nginx. However, I want to move all my user-uploaded media to Amazon S3 and not serve media from my server. I've got everything working for the models that have images in ImageFields, as they just work out the path for the image using the django-storages API. But the images that are stored as above inside TextFields won't work any more, as they are relative paths, not S3 paths. Is there a way to make this work without having to edit all the contents of all of the TextFields to change the img path to be the full S3 path? Not only does that seem like a very laborious process (even if I can do it programmatically) but what if I subsequently want to change to another storage service? I'll have to do it again! It would be better if … -
select an random page with django
i'm trying select a random page with Django but i don't know how call the function. i tried call with a url but dont work views.py: def random_page(request): entries = util.list_entries() # list of wikis selected_page = random.choice(entries) return render(request, "encyclopedia/layout.html", { "random_page": selected_page }) urls.py: from . import views app_name = "encyclopedia" urlpatterns = [ path("", views.index, name="index"), path("wiki/<str:page_title>", views.wiki_page, name="wiki_page"), path("create", views.add_entry, name="add_entry"), path("search", views.search, name="search"), path("wiki/edit/<str:page_title>", views.edit_page, name="edit_page") ] layout.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <title>{% block title %}{% endblock %}</title> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.4.1/css/bootstrap.min.css" integrity="sha384-Vkoo8x4CGsO3+Hhxv8T/Q5PaXtkKtu6ug5TOeNV6gBiFeWPGFN9MuhOf23Q9Ifjh" crossorigin="anonymous"> <link href="{% static 'encyclopedia/styles.css' %}" rel="stylesheet"> </head> <body> <h2>Wiki</h2> <form action="{% url 'encyclopedia:search' %}" method="POST"> {% csrf_token %} <input class="search" type="text" name="q" placeholder="Search Encyclopedia"> </form> <a href="{% url 'encyclopedia:index' %}">Home</a> <a href="{% url 'encyclopedia:add_entry' %}">Create New Page</a> <a href=wiki/{{ random_page }}>Random Page</a> {% block body %} {% endblock %} </body> </html> thank you in advanced -
TemplateDoesNotExist at / learning_logs/index.html
Im following a tutorial about Django and I got this error and I dont know why its happening since Im following a book tutorial, I didnt have any error until now and I checked every piece of code, maybe its because Im using a new versio of Django? This is settings import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'rxgiz!*92qwfw%@6k1@#zh0=g@x1g8uzre0dpl@_5e(wpzvlpe' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ # My apps 'learning_logs', # Default django apps. 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] 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', ] ROOT_URLCONF = 'learning_log.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], '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', ], }, }, ] WSGI_APPLICATION = 'learning_log.wsgi.application' # Database # https://docs.djangoproject.com/en/3.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } # Password validation # https://docs.djangoproject.com/en/3.0/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { 'NAME': 'django.contrib.auth.password_validation.UserAttributeSimilarityValidator', }, { 'NAME': 'django.contrib.auth.password_validation.MinimumLengthValidator', }, … -
Reverse Relationship in django 'QuerySet' object has no attribute 'name'
I have two models called car and producer. The two models have many to one relation between them. class Producer(models.Model): name = models.CharField(max_length=30) def __str__(self): return self.name class Car(models.Model): name = models.CharField(max_length=20) producer = models.ForeignKey(Producer, on_delete=models.CASCADE) def __str__(self): return self.name here When i try to query the reverse relationship. Producer.objects.filter(car__name='Mini') then it return a queryset object <QuerySet [<Producer: BMW>]> when i try to assign the queryset object to a variable and fetch the name field result then it gives error. obj1 = Producer.objects.filter(car__name='Mini') In [6]: obj1.name --------------------------------------------------------------------------- AttributeError Traceback (most recent call last) <ipython-input-6-5155cb2773b4> in <module> ----> 1 obj1.name AttributeError: 'QuerySet' object has no attribute 'name' what could be the reason for this error -
Multiple redirects to one site with different parameters in http request in Django
Sorry for asking so many questions... But I have another one! Briefly, how to handle multiple redirects to one site with different parameters in http body. In my code I have a for loop with http redirect... It suppose to loop and do redirects with different parameters so many times as I have different parameters. But it just do one time redirect and goes to this web site, so I end up with only one redirect instead of multiple ones. I really do interested in simple sequential redirects, nothing difficult like parallel multi-threading, but still I cannot find answer on this topic. My code in view looks like this: for code in codes: print(code) base_url = 'https://base_url/' code_part = 'code={}'.format(code) url = '{}?{}'.format(base_url, code_part) return redirect(url) I thought about enveloping this into parent-child function, which will process itself so many times as the structure of list goes, but I think I will end up with the same result as in normal for loop. Also I saw redirects application, but I am not sure if it helps me with this exact task. And it doesn't matter how I implement it, but as soon as I call redirect, program quits to external … -
django not sending a email [closed]
i am trying to send a password_reset email from django with the original method that django have, but it is not working: from servicios.inicio.models import Users from ventor.components.permisology import AnonymousRequired from servicios.inicio.forms.passreset import PassForm from rest_framework.decorators import api_view from rest_framework.decorators import permission_classes from rest_framework.decorators import renderer_classes from rest_framework.renderers import JSONRenderer from rest_framework.response import Response from django.http import JsonResponse @api_view(['POST', 'GET', 'PUT']) @permission_classes([AnonymousRequired]) @renderer_classes([JSONRenderer]) def password_reset(request, format=None): return Response(proceso(request)) def proceso(request): form = PassForm(request.data) if form.is_valid(): if Users.objects.filter(email=form.cleaned_data['email']): return form_valid(form) else: return {'success': False,'message': 'El Email seleccionado no corresponde a ninguna cuenta asociada.'} else: return form_invalid(form) def form_valid(form): sus = {'success':True, 'message':''} try: print("ENTREEE") super().form_valid(form) except: sus = {'success': False,'message': 'Ocurrió un error inesperado al enviar el Email'} print(sus) return sus def form_invalid(form): return {'success': False,'message': 'El Email introducido es inválido.'} The method it supossed to send the email with super().is_valid(form) sending the form but it doesnt work!.. Any ideas? Thanks! -
Django filter with field from serializer
I want to filter a query from a field that come from the serializer View : class PublicationListViewSet(viewsets.ReadOnlyModelViewSet): pagination_class = None serializer_class = PublicationListSerializer def get_queryset(self): queryset = Publication.objects.all().order_by('-date') supId = self.request.query_params.get('id', None) if supId is not None: queryset = queryset.filter(Q(authors__id__iexact=supId)) # Here authors must come from the serializer return queryset Serializer : class PublicationListSerializer(serializers.ModelSerializer): country = CountrySerializer() authors = serializers.SerializerMethodField() class Meta: model = Publication fields = ( 'id', 'title', 'date', 'conference', 'city', 'country', 'authors', 'file_pdf', 'file_pdf_is_public', 'file_ppt', 'file_ppt_is_public') def get_authors(self, obj): return PublicationSupervisorSerializer(obj.get_authors(), many=True).data When I try to filter, it said "Cannot resolve keyword 'authors' " I'm pretty new with this and I can't find a way to resolve it. Do someone have a solution for this filtering ? -
How to hide calendar under the menu bar when scrolling
I am using the following calendar with Django: https://xdsoft.net/jqplugins/datetimepicker/ Problem is that when scrolling down the page, Month and Year calendar components goes over my menu-bar. There is a way to fix this ? maybe to override some css or in HTML/Javascript ? -
How to access environment variable from html or js in Django
Here set environment variables using os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'myapp.settings') I want to display some values in UI. Is there any way to access values from DJANGO_SETTINGS_MODULE ?? -
Two ways of loading csv file, which one is faster when a lot of people visit the website
I am using django with Postgresql. Right now I am trying to load CSV file with around 2MB and use this data to add markers on the google maps. I have two possible solutions: One, I save CSV in the file system, every time when I load the page i will access the csv and pass it into django template. Another way is to save CSV file in the database and retrieve from database when i load the page. When there are lots of people visit the website, which way would be better (which way is faster)? Thanks!