Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Uploading an image from form and displaying that image without refreshing the page
For my project I am trying to make a post through ajax by prompting the user to fill out a form with an animal type, img upload, and description. Right now when the user fills out all 3 fields and submits the post, the animal type and description shows up in the admin page but the image file does not and it is also not uploaded to the /images/ file as specified within my model code. class Post(models.Model): BISON = 'Bison' WOLF = 'Wolf' ELK = 'Elk' BLACKBEAR = 'Black Bear' GRIZZLY = 'Grizzly Bear' MOOSE = 'Moose' MOUNTAINLION = 'Mountain Lion' COYOTE = 'Coyote' PRONGHORN = 'Pronghorn' BIGHORNSHEEP = 'Bighorn Sheep' BALDEAGLE = 'Bald Eagle' BOBCAT = 'Bobcat' REDFOX = 'Red Fox' TRUMPETERSWAN = 'Trumpeter Swan' YELLOWBELLIEDMARMOT = 'Yellow-bellied Marmot' RIVEROTTER = 'River Otter' LYNX = 'Lynx' SHREW = 'Shrew' PIKA = 'Pika' SQUIRREL = 'Squirrel' MULEDEER = 'Mule Deer' SANDHILLCRANE = 'Sandhill Crane' FLYINGSQUIRREL = 'Flying Squirrel' UINTAGROUNDSQUIRREL = 'Uinta Ground Squirrel' MONTANEVOLE = 'Montane Vole' EASTERNMEADOWVOLE = 'Eastern Meadow Vole' BUSHYTAILEDWOODRAT = 'Bushy-tailed Woodrat' CHIPMUNK = 'Chipmunk' UINTACHIPMUNK = 'Uinta Chipmunk' WHITETAILEDJACKRABBIT = 'White-tailed Jackrabbit' BEAVER = 'Beaver' AMERICANMARTEN = 'American Marten' MOUNTAINCHICKADEE = 'Mountain Chickadee' BOREALCHORUSFROG … -
HTML Calendar Appearing Under Footer
I've created an HTML Calendar for my django app. However when I add it to one of my templates it adds it underneath my footer. I'm not understanding why this would happen. {% extends "bf_app/app_bases/app_base.html" %} {% block main %} {% include "bf_app/overviews/overview_nav.html" %} <div class="flex justify-between mx-10"> <a href="{% url 'calendar_overview_context' previous_year previous_month %}">< {{ previous_month_name }}</a> <a href="{% url 'calendar_overview_context' next_year next_month %}">{{ next_month_name }} ></a> </div> <div class="grid grid-cols-1 md:grid-cols-3 px-4"> <table> <thead> <tr> <th class="text-left">Transaction</th> <th class="text-left">Amount</th> <th class="text-left">Date</th> </tr> </thead> {% for transaction, tally in monthly_budget.items %} <tr> <td>{{ transaction }}</td> <td class="{% if tally|last == "IN" %}text-green-700{% else %}text-red-700{% endif %}"> {{ tally|first|floatformat:2 }} </td> <td>{{ transaction.next_date|date:"D, d M, Y" }}</td> </tr> {% endfor %} </table> </div> <div> {{ calendar }} </div> {% endblock %} I pretty much followed this tutorial: https://www.huiwenteo.com/normal/2018/07/24/django-calendar.html Is there something I'm missing? This to my understanding should be above the footer like everything else I've created. -
How to sort Django's list_display of a function using admin_order_field?
class ProductAdmin(admin.ModelAdmin): def got_inactive_variation(self, obj): res = obj.active_variation.__func__(obj) var_list = [i for i in res] active_list = [] for i in var_list: active_list.append(i.is_active) if False in active_list: return 'Yes' else: return 'No' got_inactive_variation.admin_order_field = "???" got_inactive_variation.short_description = 'Got Inactive Variation' list_display = ( 'product_name', 'product_description', 'price', 'stock', 'is_available', 'category', 'created_date', 'sku', 'got_inactive_variation') As the code above, I want to be able to sort the got_inactive_variation, but what should I put in the right side of admin_order_field? -
Django form_valid not passing params to CreateView
In my django project, I'm trying create a 'submit post' page using CreateView. It works, but with a dropdown menu for the author of the post. I would like to have the author automatically added to the post. According to the (documentation)[https://docs.djangoproject.com/en/4.1/topics/class-based-views/generic-editing/], I should use a form_valid method to add the author to the form. This does not work, even though it's copied directly from the documentation. I've tried adding 'author' to the fields in the PostCreate class, and that only adds the author dropdown box to the form. Views.py: class PostCreate(LoginRequiredMixin, CreateView): model = Post fields = ['image', 'description'] success_url = '/' template_name: 'post_form.html' def form_valid(self, form): self.author = self.request.user return super().form_valid(form) changing to self.author = self.request.user.pk does not work, either. Models.py: class Post(models.Model): image = models.ImageField() description = models.TextField(null=True ) author = models.ForeignKey(User, on_delete=models.CASCADE) when looking at the debug error, I can see the author param is not passed, resulting in a NOT NULL constraint failed. -
Complex Django search engine
I want my Django search engine to be able to handle typos on the title of the item I would display. For example if the user does the search 'stacoverflow' I would search for 'stackoverflow'. I would then apply other filters I already have and could display the results. What would be the best way to do this and how could I do it? Consider some specific strings and then change their values, how? My Models: class Product(models.Model): author = models.ForeignKey(User, default=None, on_delete=models.CASCADE) category = models.ForeignKey(Category, default=None, on_delete=models.PROTECT) title = models.CharField(max_length=120, unique=True) # ... My views: def is_valid_queryparam(param): return param != '' and param is not None def FilterView(request): qs = Product.objects.all() categories = Category.objects.all() title_contains_query = request.GET.get('title_contains') id_exact_query = request.GET.get('title_exact') title_or_author_query = request.GET.get('title_or_author') view_count_min = request.GET.get('view_count_min') view_count_max = request.GET.get('view_count_max') date_min = request.GET.get('date_min') date_max = request.GET.get('date_max') category = request.GET.get('category') if is_valid_queryparam(title_contains_query): qs = qs.filter(title__icontains=title_contains_query) elif is_valid_queryparam(id_exact_query): qs = qs.filter(id=id_exact_query) elif is_valid_queryparam(title_or_author_query): qs = qs.filter(Q(title__icontains=title_or_author_query) | Q(author__username__icontains=title_or_author_query)).distinct() #... if is_valid_queryparam(category) and category != 'Choose...': qs = qs.filter(category__name=category) context = { 'queryset': qs, 'categories': categories } return render(request, 'search/filter_form.html', context) My templates: <form method="GET" action="."> <div> <input type="search" placeholder="Title contains..." name="title_contains"> </div> <div> <input type="search" placeholder="ID exact..." name="id_exact"/> </div> <div> <input type="search" … -
flush=True - Not working most of the time
so I thought that the flush=True function will force the print function to print information, however, most of the time it doesn't work. I'm using Django and I'm always going to the route, which contains these print functions, that are supposed to return the print function but nothings prints out.. any ideas? An example: def jsonresponse2(request, username): if request.method == 'GET': username = request.session['_auth_user_id'] Current_User = User.objects.get(id=username) #List of who this user follows followingList = Follower.objects.filter(follower=int(Current_User.id)) UsersInfo = [] for user in followingList: singleUser = User.objects.filter(username=user.following).values( 'username','bio', 'profile_image','id') print(f'This is singleUser {singleUser}',flush=True) UsersInfo += singleUser print(f'This is UsersInfo {UsersInfo}',flush=True) else: return JsonResponse({'Error':'Method Not Allowed!'}) return JsonResponse({'UsersInfo':list(UsersInfo)}) -
Django-leaflet: map getBounds returning [object Object]
I am using django-leaflet to display a map in a template, where the goal is to only display the coordinates of the visible area of the map when the user moves the map. For this I'm using the getBounds() method, but the function only returns [Object Object]. template.html: {% load leaflet_tags %} {% block extra_head %} {% leaflet_js %} {% leaflet_css %} {% endblock %} {% block body %} {% leaflet_map "extent" callback="map_init" %} {% endblock %} {% block extra_script %} <script> function map_init (map, options) { map.on('moveend', function() { alert(map.getBounds()); }); } </script> {% endblock %} Why is not showing the coordinates? -
No module named 'debug_toolbarnews'
I did the following to install django-debug-toolbars pip install django-debug-toolbar added to middleware classes: 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', "debug_toolbar.middleware.DebugToolbarMiddleware" ] Added INTERNAL_IPS: INTERNAL_IPS = [ "127.0.0.1", ] 4.Added debug_toolbar to installed apps Code in urls: urlpatterns = [ path('',include('news.urls')), path('admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns = [ path('__debug__/', include('debug_toolbar.urls')) ] + urlpatterns i am getting "No module named 'debug_toolbarnews'" errors -
How to make creating an array with using two models more efficient?
I want to create an array for a specific need. I have some parameters and I call a model (ProcessType) with this and filter the model with them. After that, I call another model with a time filter and I have to choose the objects that have the same case_type (string) name as the ProcessType. I created a function for that but it's very slow. How can I make it more efficient? def case_groups(self, date_1, date_2, process_group): cases = Case.objects.filter(date_created__range=[date_1, date_2]) process_types = ProcessType.objects.filter(reporting_group__option=process_group) report_group = [] for i in cases: for j in process_types: if j == i.case_type: report_group.append(i) print(report_group) return report_group -
How do I fix the error that django keeps giving me when I try to click to update my form?
I have tried many different ways, including class based views to make a user able to edit the form they completed. I get the same error no matter what I try and can't get to the bottom of it. I tried to post just enough code below so it is readable. Here are the errors: Exception Type: NoReverseMatch Exception Value: Reverse for 'update' with arguments '('',)' not found. 1 pattern(s) tried: ['update/(?P[^/]+)/$'] Exception Location: /Users/name/Desktop/Django/env/lib/python3.9/site-packages/django/urls/resolvers.py in _reverse_with_prefix, line 677 In template /Users/name/Desktop/Django/dv_project/myapp/templates/base.html, error at line 12 models.py class StepOne(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) title = "STEP 1: Safety during a violent incident" box1 = models.CharField(max_length=100, null=True) box2 = models.CharField(max_length=100, null=True) box3 = models.CharField(max_length=100, null=True) box4 = models.CharField(max_length=100, null=True) box5 = models.CharField(max_length=100, null=True) box6 = models.CharField(max_length=100, null=True) def __str__(self): return self.title class StepOne(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, null=True) title = "STEP 1: Safety during a violent incident" box1 = models.CharField(max_length=100, null=True) box2 = models.CharField(max_length=100, null=True) box3 = models.CharField(max_length=100, null=True) box4 = models.CharField(max_length=100, null=True) box5 = models.CharField(max_length=100, null=True) box6 = models.CharField(max_length=100, null=True) def __str__(self): return self.title forms.py class StepOneForm(forms.ModelForm): box1 = forms.CharField() class Meta: model = StepOne #which model we want to use as a model for our model form fields= … -
This error shows up in Django: DoesNotExist at /settings Django problem
Hi I am trying to create a variable in setting.html for my django project and everything is fine until I add this sentence: user_profile = Profile.objects.get(user=request.user) And then it gives me: DoesNotExist at /settings I am fairy new to Django and this is my first django project. This is the views.py This is the models.py Setting.html urls.py settings.py -
Complex Django search engine
I want my Django search engine to be able to handle typos on the title of the item I display. For example if the user does the search 'stacoverflow' I would search for 'stackoverflow'. I would then apply other filters I already have and could display the results. What would be the best way to do this and how could I do it? Consider some specific strings and then change their values, how? -
Refactor Business Logic From View To Model
I've got a django view with a small amount of business logic in it. However it would be useful to use this information elsewhere so it feels like something that I could put into a model however I'm not entirely sure how to go about doing this. Mainly because I need specific user data. This is what I have so far: views.py def create_budget(self, context): starting_point = BudgetStartingPoint.objects.filter(owner=self.request.user) running_tally = starting_point[0].starting_amount budget_dict = {} for transaction in self.get_queryset(): if transaction.income_type == "IN": running_tally += transaction.transaction_amount else: running_tally -= transaction.transaction_amount budget_dict[transaction] = [running_tally, transaction.income_type] context['budget'] = budget_dict models.py class BudgetTransaction(models.Model): """ Individual transaction for Budget """ transaction_types = [ ('fixed', 'Fixed'), ('extra', 'Extra'), ] income_types = [ ("IN", "Income"), ("OUT", "Expense"), ] frequencies = [ ('weeks', 'Weekly'), ('fort', 'Fortnightly'), ('4week', 'Four Weeks'), ('months', 'Monthly'), ('years', 'Yearly'), ] today = datetime.today().date() id = HashidAutoField( primary_key=True, salt=f"transaction{settings.HASHID_FIELD_SALT}" ) owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, help_text="Owner of the item" ) category = models.ForeignKey(BudgetCategory, on_delete=models.CASCADE, default=1, null=True) transaction_type = models.CharField(max_length=40, choices=transaction_types, default=1) transaction_name = models.CharField(max_length=100, null=False) transaction_amount = models.FloatField(null=False, default=100) income_type = models.CharField(max_length=20, choices=income_types, default="IN") next_date = models.DateField(null=False, default=today) frequency = models.CharField(max_length=20, choices=frequencies, default=1) complete = models.BooleanField(default=False) def __str__(self): return self.transaction_name class Meta: ordering = ['next_date'] … -
JsonField in DRF
I have a model like below that include JsonField: class Animal(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_field=15) data = models.JSONField() the data field structure is like below: [ { "age":"15", "color":white, ... }, { ... ... } ] And my goal is to show this model in DRF like below: [ { "id": 1, "name": "Bell", "data": [ { "age":"15", "color":"white", ... }, { ..., ... } ] } ] But when i use JsonFeild in my model my data generated liKe: [ { "id": 1, "name": "Bell", "data": "[{\"age\":\"15\",\"color\":\"white\",...},{\...,|... }]" } ] It's converted to string and have \ in characters. My serializer: class AnimalSerializer(serializers.ModelSerializer): class Meta: model = Animal fields = "__all__" -
Django/ AUTH_USER_MODEL refers to model 'home.******' that has not been installed
I checked all the answers but could not achieve a result after trying everything. I wanted to create model with AbstractUser in the home app which I was already using not created for only this purpose .After creating the class (mentioned as *****) I created AUTH_USER_MODEL = 'home.*******' in settings file and also created the 'home.apps.HomeConfig', in Installed Apps part. But still getting the error. What should I do? I would also like to ask which might be connected to my problem. I may not created the home app while in virtual env is it causes a problem in anyway? Thank you for your answer. Im new at django please dont judge and if the question is not appopriate please guide me. -
Django Assign Different ForeignKeys to Different Forms in a Formset
Summary I need to figure out how can I process a formset in a view in a way where instances of the formset can be assigned different foreign keys. Design Requirement #1 I am working with a design requirement where the user should click a button to add a PollQuestion form to the site. The button can be clicked multiple times to add multiple PollQuestion forms, and on submit, the view will handle creating PollQuestion instances that are related to the same Poll object via foreign key. Implementation I am currently using a modelfactory_formset and DOM manipulation with JavaScript to dynamically append PollQuestion forms to the DOM, and on submit are processed in the view as a formset. This is working fine. Design Requirement 2 Design also wants the ability to dynamically add PollOption forms to the PollQuestion form with an HTML button. One submit button will send the data from both PollQuestion and PollOption forms to the view for processing. Implementation Again I am using a dynamic formset modelfactory_formset for the PollOption forms. An "Add Option" button appends a PollOption form to the DOM. This works fine if I have just one PollQuestion. Problem But if I have more … -
How to insert data and update data in One to One Relation in DRF and React Js
I have two models User and Profile which is related by One to One relation. I have registered users who can login and if profile is not created for user, then user can create one profile (using POST) and if profile is created then user can update their profile (using PATCH). Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True, related_name='profile') locality = models.CharField(max_length=70, null=True, blank=True) city = models.CharField(max_length=70, null=True, blank=True) address = models.TextField(max_length=300, null=True, blank=True) pin = models.IntegerField(null=True, blank=True) state = models.CharField(max_length=70, null=True, blank=True) profile_image = models.ImageField(upload_to='user_profile_image', blank=True, null=True) Serializer.py class ProfileSerializer(serializers.ModelSerializer): class Meta: model= Profile fields = ['user', 'locality','city','address','pin','state','profile_image'] Views.py class UserProfileDataView(APIView): renderer_classes = [UserRenderer] permission_classes = [IsAuthenticated] def get(self, request, format=None): serializer = ProfileSerializer(request.user.profile, context={'request': request}) return Response(serializer.data, status=status.HTTP_200_OK) def post(self, request, format=None): serializer = ProfileSerializer(data= request.data, context={'user': request.user}) serializer.is_valid(raise_exception=True) serializer.save() return Response ({ 'msg':'Data Updated Successfully'},status=status.HTTP_201_CREATED ) def patch(self, request, format=None): item = Profile.objects.get(user = request.user) serializer = ProfileSerializer(item ,data = request.data, partial=True, context={'user': request.user.profile}) serializer.is_valid(raise_exception=True) serializer.save() return Response({'msg':'Profile Updated Successfull'}, status = status.HTTP_200_OK) API using Redux Toolkit editProfile: builder.mutation({ query: (access_token, actualData ) => { return { url:'editprofile/', method:'PATCH', body:actualData, headers:{'authorization' : `Bearer ${access_token}`, 'Content-type':'application/json'} } } }), createProfile: builder.mutation({ query: (access_token, actualData ) => { … -
Session Authentication for Delete Request with Django Rest Framework
I am trying to modify a Django application to use the Django Rest Framework (DRF). I can get everything to work fine with the exception of the authentication mechanism. To illustrate, consider the following function in views.py which deletes one entry from the database: @api_view(['DELETE']) def api_delete_cert(request, cert_name): .... # delete certificate cert_name from database The entry in url.py for this function is: path('<str:cert_name>/api_delete_cert', views.api_delete_cert, name='api_delete_cert'), During testing, I access this function from the client side using curl with a command like: curl -i -X "DELETE" http://localhost:8000/editor/abcd/api_delete_cert This works fine but, of course, there is no authentication mechanism. I would like to use Session Authentication whereby the client logs in and then saves the session ID locally (in a cookie) and then sends it to the server with each subsequent request. For this purpose, I have extended my views.py to have a login function: @api_view(['POST']) def api_login(request): if ('username' in request.POST) and ('password' in request.POST): username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) # Save user's ID in the session return Response(status=status.HTTP_202_ACCEPTED) return Response(status=status.HTTP_403_FORBIDDEN) I have then modified the delete in views.py function to become: @api_view(['DELETE']) @authentication_classes([SessionAuthentication]) def api_delete_cert(request, cert_name): … -
How can i after registration get jwt tokens (djangorestframework)
from django.conf.urls.static import static from django.contrib import admin from django.urls import path, include from rest_framework_simplejwt.views import TokenObtainPairView, TokenRefreshView, TokenVerifyView from InternetShop import settings from InternetShopApp.views import * urlpatterns = [ path('admin/', admin.site.urls), path('api/v1/products/', ProductsAPIList.as_view()), path('api/v1/products/<int:pk>/', ProductsAPIUpdate.as_view()), path('api/v1/productsremove/<int:pk>/', ProductsAPIRemove.as_view()), path('api/v1/auth/', include('djoser.urls')), path('api/v1/token/', TokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/v1/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), path('api/v1/token/verify/', TokenVerifyView.as_view(), name='token_verify'), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I need when user successfully register on api/v1/auth/ get jwt tokens in json answer -
django how to tell if send mail fails - and sending mail via AWS SES
I'm trying to link up to AWS SES, but the message (the login email confirmation message) isn't going out. That is the AWS SES monitor says there were no rejects (or sends). How do I figure out what is going wrong? I've tried two ways to send email: django-ses with the config as: EMAIL_BACKEND = 'django_ses.SESBackend' AWS_ACCESS_KEY_ID = 'wouldnt_you_like_to_know' AWS_SECRET_ACCESS_KEY = 'not_telling' and I've tried it as a simple client: EMAIL_HOST = 'email-smtp.us-east-1.amazonaws.com' EMAIL_HOST_USER = 'yada_yada' EMAIL_HOST_PASSWORD = 'shh_it_is_secret' EMAIL_PORT = 587 EMAIL_USE_TLS = True The console just shows: [12/Aug/2022 16:15:46,877] - Broken pipe from ('127.0.0.1', 57644) Content-Type: text/plain; charset="utf-8" MIME-Version: 1.0 Content-Transfer-Encoding: 7bit Subject: [LVM System] Please Confirm Your E-mail Address From: Literacy Volunteers of MA <noreply@lvm.org> To: michael@hotmail.com Date: Fri, 12 Aug 2022 20:15:49 -0000 Message-ID: <166033534901.17800.6503664761440235634@Nibbitz> Hello from LVM System! You're receiving this e-mail because user noone has given your e-mail address to register an account on example.com. To confirm this is correct, go to http://127.0.0.1:8000/accounts/confirm-email/MQ:1oMb4O:sZoI4Z5UUvYXcXLiEGdZUfH5nnt2QO7jJ6iZ1L6zG48/ Thank you for using LVM System! example.com ------------------------------------------------------------------------------- [12/Aug/2022 16:15:49] "POST /accounts/login/ HTTP/1.1" 302 0 [12/Aug/2022 16:15:49] "GET /accounts/confirm-email/ HTTP/1.1" 200 1817 [12/Aug/2022 16:15:49] "GET /static/css/project.css HTTP/1.1" 304 0 [12/Aug/2022 16:15:49] "GET /static/js/project.js HTTP/1.1" 304 0 Thanks for the help. -
How to get a src image link instead of Django tag when fetching through jQuery?
I am trying to get value from django template to my external js file. It works well when in html template the data would be text like <h3 class="username">{{ user.first_name }} {{ user.last_name }}</h3> and js file code, var username = $(this).children().text(); But incase of image, it gives me the Django tags. Following is the html code, <img id="my_img" src="{{user.picture_url}}"> and js file code, profile_pic = $('#my_img').attr('src'); WHAT OUTPUT I EXPECT ? http://127.0.0.1:8000/media/profile_image/blog-img1_Pw8NJQm_trt743z.jpg WHAT OUTPUT I OBSERVED ? {{user.picture_url}} Please let me know how can I achieve the expected output. Thanks. -
djnago drf update field if all user read it
so i have this djnago rest framework views that filter latestbooks=True and return latest books and if user view book i have other funtion to remove book from latestbook by making latestbooks=False , it's works fine with one user now i have more users if the first one read the book it will remove from latestbook and other users won't be able to see it how i can remove book from latestbook only after all usres read it views.py class LatestBokks(ListAPIView): queryset = Book.objects.filter(latestbooks=True,blacklist=False).order_by('-date') serializer_class = BookSerial pagination_class = None models.py class Book(models.Model): title = models.CharField(max_length=255,unique=True) description = models.TextField(max_length=4000) alternative_name = models.CharField(max_length=200) author = models.CharField(max_length=500) type = models.CharField(max_length=20) book_slug = models.SlugField(max_length=200) image_file = models.ImageField(blank=True) image_url = models.URLField(blank=True) blacklist = models.BooleanField(default=False) latestbooks= models.BooleanField(default=False) date = models.DateTimeField(auto_now_add=True) duplicated = models.IntegerField(null=True,blank=True) -
Django Web App with Selenium download location heroku
I have the following problem, i have a selenium bot which download a file from a website and save it on local, he save on "C:\Users\name\Downloads", but on heroku i dont know where to put. chrome_options.add_experimental_option("prefs", { "download.default_directory": "C:\\Users\\name\\Downloads", "download.prompt_for_download": False, "download.directory_upgrade": True, "safebrowsing_for_trusted_sources_enabled": False, "safebrowsing.enabled": False } ) What can i add on heroku on 'download.default_directory', and how i can access the document (what path)? Thank you -
How to pass a list to the value of an input
I have the following input: <input type="hidden" id="accesspoint_node_attribute" name="accesspoint_node_attribute" value="name,military_organization,commander"> As can be seen, I'm passing three elements in value (name,military_organization,commander) However, the last element (commander) is a select multiple, so it can have more than one value. However, I can only pass one value. <select name="accesspoint_military_organization" id="accesspoint_military_organization" multiple> {% for om in oms %} <option value="{{om.Id}}">{{om.name}}</option> {% endfor %} </select> Any suggestions on how to pass all select values? -
Cors errors on Django apps
I'm trying to build a Django app with a react frontend and was trying to work out why I keep getting cors errors on my browser when I host it on the server. After reading up a bunch on this I figured out that I need to configure the following in the settings.py after installing django cors headers: ALLOWED_HOSTS = "127.0.0.1", "localhost:8000", "localhost" CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CORS_ORIGIN_ALLOW = True CORS_ORIGIN_WHITELIST = [ "http://127.0.0.1:5501", "http://127.0.0.1:5500", "http://localhost:8000", "http://127.0.0.1:8000", ] CSRF_TRUSTED_ORIGINS = [ "http://127.0.0.1:5501", "http://127.0.0.1:5500", "http://localhost:8000", "http://127.0.0.1:8000", ] CORS_ALLOW_HEADERS = [ "accept", "accept-encoding", "authorization", "content-type", "dnt", "origin", "user-agent", "x-csrftoken", "x-requested-with", ] INSTALLED_APPS = [ "corsheaders", "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "rawWikiData.apps.RawwikidataConfig", ] MIDDLEWARE = [ "corsheaders.middleware.CorsMiddleware", "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", ] But I still get this error when I try to access the webpage from one of the frontend pages that I'm hosting using the static paths of django. Here is the error: Cross-Origin Request Blocked: The Same Origin Policy disallows reading the remote resource at http://localhost:8000/getSentenceData/. (Reason: CORS request did not succeed). Status code: (null). Uncaught (in promise) Object { message: "Network Error", name: "AxiosError", code: "ERR_NETWORK", config: {…}, request: XMLHttpRequest, response: …