Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django bulk updating via F
I am trying to bulk update a number of objects for a given model. I figured I could do this via a dictionary together with F doing something like FooBar.objects.filter(...).update(order = order_dict[F('id')]) where order_dict is something like {1: 2, 2: 3, 3: 1, 4: 4} objects with id equal to 1, 2, 3, and 4 exist but it is giving me a key error: F(id) nonetheless. Why precisely does this not work? And is there some way to achieve this other than updating objects one by one or using a 3th party package? -
Serving Keras Model Using Django
I have a pre-trained keras model (in .hdf5 form) that I am planning to deploy using a Django Web-App. In my views file it is called upon when a certain POST request is passed in. I have stored in .hdf5 model in the static folder associated with my web-app. However, when i call keras.models.load_model to try and load the model from the static directory the app returns the following error: Unable to open file (unable to open file: name = '/static/model.hdf5', errno = 2, error message = 'No such file or directory', flags = 0, o_flags = 0) However, the model is clearly in my static folder so I'm not sure why the load_model function is not working to load the model. If there is some reason for this or a workaround I am not sure of it so any information regarding a solution would be helpful. I am also willing to switch to a tensorflow serving model or otherwise if this is a keras issue/it would be beneficial. What is the reason I am not able to load my keras model from my Django app and how can I remedy the situation? -
How to desing a URL pattern for /check?id=984c3a7b-766b-450e?
I can't figure out how to design a regexp for /check?id=984c3a7b-766b-450e? url in django. I tried r'^check\?id=(?P<id>[0-9a-f-]+)/$' but it returns "Page Not Found". Works good with just (?P<id>[0-9a-f-]+) though. -
javascript leaflet click on button zoom to not working
I have a very basic django-leaflet app where I created a button and it is supposed to zoom to a certain area when clicked. I set it up and nothing occurs when I click on the button and there is nothing in the console this is my HTML document <html> {% load static %} {% load leaflet_tags %} {% load bootstrap3 %} <head> {% leaflet_js %} {% leaflet_css %} {% bootstrap_css %} <title>Our Home</title> <style type="text/css"> #gis {width: 100%;height:1000px;} </style> <link rel="stylesheet" type="text/css" href="{% static 'leaflet-search-master/src/leaflet-search.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'leafletgroupedlayercontrol/dist/leaflet.groupedlayercontrol.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'routing/dist/leaflet-routing-machine.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'leaflet-control-osm-geocoder-master/Control.OSMGeocoder.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'Leaflet.Control.Layers.Tree-master/L.Control.Layers.Tree.css' %}"> <script type="text/javascript" src="{% static 'jquery/jquery-3.3.1.slim.min.js' %}" > </script> <script type="text/javascript" src="{% static 'dist/leaflet.ajax.js' %}" > </script> <script type="text/javascript" src="{% static 'leaflet-search-master/src/leaflet-search.js' %}" > </script> <script type="text/javascript" src="{% static 'leafletgroupedlayercontrol/dist/leaflet.groupedlayercontrol.js' %}" > </script> <script type="text/javascript" src="{% static 'leaflet-control-osm-geocoder-master/Control.OSMGeocoder.js' %}" > </script> <script type="text/javascript" src="{% static 'Leaflet.Control.Layers.Tree-master/L.Control.Layers.Tree.js' %}" > </script> </head> <body> <h3> Maps Are FUN! </h3> <br> <div id="map2" class="col-md-4 well"> <p>GeoDjango is da bomb</p> <button id="Highlands" class="form-control btn-primary">Highlands</button> </div> <script src="static/js.js"></script> {% leaflet_map "gis" callback="window.our_layers" %} </body> </html> --as you can see I have the … -
Problem with uploading files in HDFS using Django
I build web application with Angular 6 frontend, Django 1.11 backend and Hadoop 3.1. It seems to me that the problem is associated with uploading large files. My method in Django looks line shown below. Everything seems to be working fine with small files in different formats. However very often when I try to upload larger files I get the error shown at the bottom. Does anyone have an idea what can be wrong and how can I fix it? def post(self, request): key = request.META.get('HTTP_AUTHORIZATION').split()[1] user_id = Token.objects.get(key=key).user_id user_name = User.objects.get(id=user_id).username upload_file(request.FILES['file'], user_name) return Response(status=status.HTTP_201_CREATED) def upload_file(file, user_name): response = requests.put(url + ':9870/webhdfs/v1/user/' + str(user_name) + '/' + str(file) + '?op=CREATE&user.name=myuser&createflag=&createparent=true&overwrite=false' , data=file, headers={'content-type':'application/octet-stream'}) return response ERROR: django_1 | Internal Server Error: /cloud/ django_1 | Traceback (most recent call last): django_1 | File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 600, in urlopen django_1 | chunked=chunked) django_1 | File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 354, in _make_request django_1 | conn.request(method, url, **httplib_request_kw) django_1 | File "/usr/local/lib/python3.6/http/client.py", line 1239, in request django_1 | self._send_request(method, url, body, headers, encode_chunked) django_1 | File "/usr/local/lib/python3.6/http/client.py", line 1285, in _send_request django_1 | self.endheaders(body, encode_chunked=encode_chunked) django_1 | File "/usr/local/lib/python3.6/http/client.py", line 1234, in endheaders django_1 | self._send_output(message_body, encode_chunked=encode_chunked) django_1 | File "/usr/local/lib/python3.6/http/client.py", line 1065, … -
Preloading Images With Django Template Langue
Is this code enough to preload images on my website? I use Django template langue for the loop, instead of javascript, like there. Is there any advantage of using javascript? Is my way as good as the javascript way? {% for marker in markers %} <img src="{{ marker.image }}" style="display: none"/> {% endfor %} -
Which is the best JavaScript framework for working with mainly rest API in terms of performance?
I want to build highly optimised product based website focusing with speed and performance mainly. After so many researches about which technology and framework I should opt, I reached at two options: 1) Develop Rest API's in Python (avoiding heavy calculations and iterations on python) and passing JsonResponse to Javascript frameworks like angular/react and make rest calculation etc at client level. 2) Use all in one Django to build, control and render template from this only. I have heard that Javascript frameworks take so much time on first load which increases page load time. Please suggest me best option, will be highly appreciable. -
django.core.exceptions.FieldError: Unknown field(s)
I am getting django.core.exceptions.FieldError: Unknown field(s) (authorized_users_read_or_write, authorized_users_to_write, authorized_users_to_read) specified for FileUpload while running makemigrations after changing the name of 3 fields in a model. I expected Django to pick up the name change and make a migration based on the changes. The model is: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User class FileUpload(models.Model): name = models.CharField(max_length=255, default='') file = models.FileField(upload_to='uploads/%Y/%m/%d/') upload_time = models.DateTimeField(auto_now_add=True, blank=True) owner = models.ForeignKey(User, on_delete=models.CASCADE, null=True, related_name='files_owned') description = models.TextField(null=True, blank=True) users_authorized_to_read = models.ManyToManyField(User, related_name='file_read_permissions', null=True, blank=True) users_authorized_to_write = models.ManyToManyField(User, related_name='file_write_permissions', null=True, blank=True) users_authorized_to_read_or_write = models.ManyToManyField(User, related_name='file_read_write_permissions', null=True, blank=True) def __str__(self): return self.name I changed the bottom 3 fields, and that's all I changed. Thank you -
Iterate over and validate large uploaded CSV file in Django
I'm using the Django module django-chunked-upload to receive potentially large CSV files. I can assume the CSVs are properly formatted, but I can't assume what the delimiter is. Upon completion of the upload, an UploadedFile object is returned. I need to validate that the correct columns are included in the uploaded CSV and that the data types in each column are correct. loading the file with csv.reader() doesn't work: reader = csv.reader(uploaded_file) next(reader) >>> _csv.Error: iterator should return strings, not bytes (did you open the file in text mode?) This might be because uploaded_file.content_type and uploaded_file.charset are both coming through as None. I've come up with a fairly inelegant solution to grab the header and iterate over the rows: i = 0 header = "" for line in uploaded_file: if i == 0: header = line.decode('utf-8') header_list = list(csv.reader(StringIO(header))) print(header_list[0]) #validate column names else: tiny_csv = StringIO(header + line.decode('utf-8')) reader = csv.DictReader(tiny_csv) print(next(reader)) #validate column types I also considered trying to load the path of the actual saved file: path = #figure out the path of the temp file f = open(path,"r") reader = csv.reader(f) But I wasn't able to get the temp file path from the UploadedFile object. Ideally … -
missing explicit frame definition for content or just static frames
I am converting HTML to pdf in Django app and using xhtml2pdf. Given is my HTML template. <!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"> <title>Certificate</title> <!-- Style sheets --> <link href="https://fonts.googleapis.com/css?family=Source+Sans+Pro:300,400,600" rel="stylesheet"> <link rel="stylesheet" type="text/css" href="/static/css/main.css"> </head> <body> <div class="container"> <img class="banner-top" src="/static/images/top.jpg"><br> <div class="inner-container"> <h2 style="letter-spacing:5;">WINNER'S</h2> <h1 style="letter-spacing:5;">CERTIFICATE</h1> <p class="client-name">Paul</p> <p>This is to acknowledge that you won the competition.</p> <h3> <img class="star" src="/static/images/star.jpg"> 4 TIME </h3> <p>Congratulations on winning Challenge.</p> <div class="row"> <div class="six columns"> <p class="date">2018-09-20</p> <p class="date-label">Date</p> </div> <div class="six columns"> </div> </div> </div> <img class="banner-bottom" src="/static/images/bottom.jpg"> </div> </body> </html> I am using pisa.CreatePDF to generate pdf and CSS is not loading properly. I tried default_css and git this error. Here is the snippet of my python code pisa.CreatePDF(io.BytesIO(html.encode('utf-8')), dest=result, link_callback=fetch_resources, default_css="/static/css/main.css") -
Dynamic HTML image loading using Javascript and Django templates
I am trying to load a specific image using javascript in a django template, but seem to be running into an issue based on the way django tags are formatted. I have a standard django static asset source in an img tag like below: {% load static %} <img src="{% static 'img/folder/logo1.svg' %}" id="orgLogo" alt="Logo" height="100px"/> I am displaying data from django lower on the page like so: <a id="orgName" class="side_nav_item">{{ thing.org_name }}</a> What I would like to do is have the img src change based on the value of thing.org inside the django tags. I originally thought jquery would be the best option, but it doesn't seem to play nice with django tags: $(document).on('load', '#orgName', function(){ $('img').attr('src','{% static 'img/folder/''+$('#orgLogo').val()+' %}'); }); I get error because of the single quotes required as part of the django syntax. I after I was able to get the basics of this javascript function to work, I was planning on using a javascript switch statement to test for specific values and assign an image (e.x. logo1.svg, logo2.svg, etc.) to each value (e.x. org1, org2, org2) thing.org can load (it's a pre-defined set of values that's not long and not likely to change). Any suggestions … -
How to get a slug in children - mptt django?
I try to create Dropdown Menu. Menu consists of categories which can be parent or children. When you aim on parent element dropdown works and you see all children element of this parent.For this I use mptt. My models.py: class Category(MPTTModel): name = models.CharField(max_length=50, unique=True) parent = TreeForeignKey('self', null=True, blank=True, related_name='children', on_delete=models.CASCADE, db_index=True) slug = models.SlugField() class MPTTMeta: order_insertion_by = ['name'] class Meta: unique_together = (('parent', 'slug',)) verbose_name_plural = 'categories' def get_slug_list(self): try: ancestors = self.get_ancestors(include_self=True) except: ancestors = [] else: ancestors = [ i.slug for i in ancestors] slugs = [] for i in range(len(ancestors)): slugs.append('/'.join(ancestors[:i+1])) return slugs def __str__(self): return self.name My query: category = Category.objects.all() My template: <ul class="header__nav"> {% recursetree category %} <li class="has-children"> {{ node.name }} {% if not node.is_leaf_node %} <ul class="sub-menu "> {{ children }} </ul> {% endif %} </li> {% endrecursetree %} </ul> It displays nice. But I can't get children as object and get slug of it or name of it because children : This variable holds the rendered HTML for the children of node. What should I do to get children as object? -
How to send an email containing HTML and CSS in Python Django?
I am sending an activation link to the user on their registered email for my blog. I am using the following lines of code for sending the email in my signup view:- current_site = get_current_site(request) subject = 'Activate Your Account' message = render_to_string('accounts/account_activation_email.html', { 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)).decode(), 'token': account_activation_token.make_token(user), }) message.content_subtype = "html" I have added html and css in my template account_activation_email.html as under:- {% autoescape off %} <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <meta http-equiv="Content-Type" content="text/html; charset=UTF-8" /> <title>Activate your SaralGyaan account</title> <style type="text/css" rel="stylesheet" media="all"> [styles go there not shown due to beverity] </style> </head> <body> <span class="preheader">Use this link to activate your SaralGyaan account. The link is only valid for 24 hours.</span> <table class="email-wrapper" width="100%" cellpadding="0" cellspacing="0"> <tr> <td align="center"> <table class="email-content" width="100%" cellpadding="0" cellspacing="0"> <tr> <td class="email-masthead"> <a href="https://saralgyaan.com" class="email-masthead_name"> SaralGyaan </a> </td> </tr> <!-- Email Body --> <tr> <td class="email-body" width="100%" cellpadding="0" cellspacing="0"> <table class="email-body_inner" align="center" width="570" cellpadding="0" cellspacing="0"> <!-- Body content --> <tr> <td class="content-cell"> <h1>Hi {{user.get_full_name}},</h1> <p>Thank you for registering your SaralGyaan's account. Please click the link below to activate your account. <strong>This link is only valid for the next 24 hours.</strong></p> <!-- Action --> <table … -
Django - Making an Ajax request
Im having a hard time figuring out how to integrate this ajax request into my view. I'm still learning how to integrate django with ajax requests. My first question would be: Does the ajax request need to have its own dedicated URL? In my case I am trying to call it on a button to preform a filter(Preforms a query dependent on what is selected in the template). I have implemented this using just django but it needs to make new request everytime the user preforms a filter which I know is not efficient. I wrote the most basic function using JQuery to make sure the communication is there. Whenever the user changed the option in the select box it would print the value to the console. As you will see below in the view, I would to call the ajax request inside this view function, if this is possible or the correct way of doing it. JQuery $("#temp").change( function() { $.ajax({ url : "http://127.0.0.1:8000/req/pending/", // the endpoint type : "GET", // http method data : { }, // data sent with the post request // handle a successful response success : function(json) { }, // handle a non-successful response … -
Python/Django - No module error in production
I'm new to Django, so this might be a simple mistake. I've created a project and added a few separate apps. Everything seems to be working locally, but as soon as I deploy it to Heroku, I get the following error: No module named 'myapp.api.urls' Project structure: website |____myapp | |_____api | | |_____urls.py | | |_____views.py | | | |_____homepage | | |_____urls.py | | |_____views.py | | | |_____mailing | | |_____urls.py | | |_____views.py | | | |_____settings.py | |_____urls.py | |_____wsgi.py | |_____manage.py |_____Procfile |_____requirements.txt |_____runtime.txt Procfile: web: gunicorn myapp.wsgi --log-file - settings.py (not entire file content): import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) ALLOWED_HOSTS = ['127.0.0.1', 'myapp.herokuapp.com'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'myapp.api', 'myapp.homepage', 'myapp.mailing', ] ROOT_URLCONF = 'myapp.urls' WSGI_APPLICATION = 'myapp.wsgi.application' API urlpatterns: urlpatterns = [ path('account/register/', ApiAccountRegisterView.as_view()), path('account/login/', ApiAccountLoginView.as_view()), ] MyApp urlpatterns: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('api/', include('myapp.api.urls')), path('', include('myapp.homepage.urls')) ] Any idea what I'm doing wrong? I've searched online but couldn't find anything to help me solve this issue. Any help would be appreciated! -
How to save python objects to sql database Django
I'm wondering if it is at all possible to save a python object to a database field using sql. I suppose it would be possible to create models that can save the individual attributes of that object, and I could write a method for reading from the database and creating the objects. I would prefer to not pursue that option because my object is very large and it would take a while to create all the fields for it. -
Postgresql cosine similarity search
I'm trying to implement a cosine similarity search on pre-made database table, having objects in this structure: from django.contrib.postgres.fields import ArrayField from django.db import models class Information(object): vectorized = ArrayField(models.FloatField(default=0.0)) original_data = models.TextField(blank=True) original_data_length = models.IntegerField(default=0) where the attribute vectorized will contain 512 dimensional vector that was created from the original_data. For example, user inputs something like "What is an Apple?": Input is converted to 512-dimensional vector A. A is iterated over all objects x on the database. On each iteration, normalized dot product (cosine similarity) is calculated between A and x.vectorized (see cosine similarity definition). x object with highest similarity (highest normalized inner product with A) is chosen, and x.original_data is printed out. I've implemented simple code for this purpose, it is inefficient since it is performed on the framework level rather than database level, and memory is allocated for all the objects in the database table: from core.models import Information from numpy import dot # dot product = inner product limited for real numbers from numpy.linalg import norm user_input = user_input # let this be 512 dimensional vector converted from user input most_similar = ("", 0) for item in Information.objects.all(): similarity = dot(item, user_input)/norm(item, user_input) if similarity > … -
module send.view has no attribute
Recently, I decided to start learning Python and just in a few days I was told our python developer is leaving. At the time of writing of this question, he already has left us. This has led me to a situation: I'm asked to add a feature to an existing program which is implemented using the Django/Python framework. I was hoping I would get a chance to learn Python first then would learn the framework but it is not possible at this time. This feature will allow the user to click on a button which it will show a small dialog/form to enter a value. A few challenges: I did write a code that I have added seems fine and it shows a message the email is sent but in reality, it doesn't send it! from django.shortcuts import render from django.core.mail import send_mail Create your views here. def index(request): send_mail('Request for a Clause', 'This is an automated email. Jeff, please submit the case for 1234567', 'akohan@mycompay.com', ['jjohnson@mycompany.com'], fail_silently=False) return render(request, 'send/index.html') In the project root, in the setting,py I have added SMTP configuration: EMAIL_HOST = 'mail.mycompany.com' EMIAL_PORT = 587 #EMAIL_HOST_USER = 'akohan@mycompany.com' ;no need it is on the white list … -
Django: how to save model instance after deleting a ForeignKey-related instance?
I am using Django 2.1.1. I have a model Analysis that, among other fields, contains a ForeignKey to a MyFile model (a model I wrote to handle files): from polymorphic.models import PolymorphicModel from django.db.models import Model, DateTimeField, FileField, SET_NULL from django.db.models.signals import pre_delete class MyFile(Model): file = FileField(upload_to='./', null=False, blank=False) description = CharField(max_length=255, null=True, blank=True) date_added = DateTimeField(auto_now_add=True) @receiver(pre_delete, sender=MyFile) def mymodel_delete(sender, instance, **kwargs): """ To delete the file connected to the `sender` class: receive the pre_delete signal and delete the file associated with the model instance. """ instance.file.delete(False) class Analysis(PolymorphicModel): # ... other fields ... file_results = ForeignKey(MyFile, on_delete=SET_NULL, related_name='file_results', null=True, blank=True) Analysis is a PolymorphicModel for reasons related to the bigger project. In Analysis.file_results I set on_delete=SET_NULL because I want to allow an Analysis instance to exist even without a file_result, which can be populated later. Let's suppose I have added a few files (the MyFile table has a few rows) and a few Analysis instances. Now, if I want to delete the file related to one of the instances of Analysis I do: a = Analysis.objects.get(pk=0) a.file_results.delete() a.save() but I get the following error: File "/Users/mtazzari/djangos/views.py" in update_job_refs 377. a.save() File "/Users/mtazzari/anaconda/envs/djangos/lib/python3.6/site-packages/polymorphic/models.py" in save 83. return super(PolymorphicModel, … -
Connecting domain name to django webserver
Currently, I have a Google Domain www.tanrunen.com. I would like to link it to my Django blog on 165.227.49.137. But I couldn't get it to work. I'm not using the One-Click install for the Django App on DigitalOcean as it doesn't support Python 3.6 & Django 2.11. Instead, I just selected a blank Ubuntu server and installed Python 3, Django 2, Supervisor, NGINX, Gunicorn manually. Right now the site is live on 165.227.49.137 but I'm struggling to link it to my domain name. Here are things I've done: I've added ns1.digitalocean.com, ns2.digitalocean.com, ns3.digitalocean.com to the nameservers on Google Domain. On DigitalOcean networking tab, I've added my domain name and direct it to my droplet IP address. In my NGINX configuration file, I've added my domain name to it. server_name 165.227.49.137 www.tanrunen.com; In my Django project directory, settings.py have my domain name in the list. ALLOWED_HOSTS = ['*','www.tanrunen.com','tanrunen.com'] I've waited for a full 12 hours after adding the nameservers on Google Domain. I understand that since I didn't use the One-Click install for Django, there may be additional steps needed to link my domain name to my site. If there is, do let me know more on how to do it. -
Django - using intermediate user group model
I need to use the intermediate model between user and group in another model like this: Class SomeModel(models.Model): usergroup = models.ForeignKey(UserGroupIntermediate, on_delete=models.DO_NOTHINH) That is possible? Thanks! -
How to prevent 504 timeout error in django app running in docker nginx server?
I have two containers for a Django app: One for the app itself, another for nginx server. Its workig fine, but there is a function that takes a little bit of time and I receive a 504 Gateway Timeout error before completes. The docker-compose.yml file contains the following services: services: dj: build: context: . dockerfile: prd/dj/Dockerfile volumes: - ./sharepoint:/sharepoint - static_files:/sharepoint/static/ - media_files:/sharepoint/media/ ports: - 8000:8000 command: gunicorn -w 4 sharepoint.wsgi --bind 0.0.0.0:8000 nx: build: context: . dockerfile: prd/nx/Dockerfile volumes: - static_files:/static_files - media_files:/media_files ports: - 8090:80 - 8091:443 The Dockerfile for nginx contains the following: FROM nginx:latest RUN rm /etc/nginx/conf.d/default.conf COPY ./prd/nx/nx.conf /etc/nginx/conf.d The nx.conf contains the following: server { listen 80; listen 443; server_name localhost; access_log /var/log/nginx/example.log; location /static/ { autoindex off; alias /static_files/; } location /media/ { autoindex off; alias /media_files/; } location / { proxy_pass http://dj:8000; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } I have found a solution for this in Nginx 504 Gateway Timeout Error for Django Set the timeout ngnix setings into the http{ ... } block in /etc/nginx/nginx.conf file: http { #All block content... #Now the timeout settings: proxy_connect_timeout 50000; proxy_read_timeout 50000; proxy_send_timeout 50000; } Restart nginx I have try that without … -
Can't set user session with Vue and Django
I have Vue app and Django rest framework separately. One on localhost:8080 (vue app) and the rest api is on localhost:8000. So, I created a APIView that is supposed to log user in when they made a post request: class LoginUserAPIView(APIView): permission_classes = () # login should be accessed by anyone, no restrictions. def post(self, request, format=None): username = request.data['username'] password = request.data['password'] user = authenticate(username=username, password=password) if user is not None: login(request, user) user = UserSerializer(user) return Response({'success': 'Logged in', 'user': user.data}) return Response({'wrong': 'username or password not correct, try again'}, status=status.HTTP_401_UNAUTHORIZED) And I was trying to get that user session from django with axios: login() { this.isLoading = true; return axios({ method: 'post', url: 'http://localhost:8000/api/login_user', data: { username: this.name, password: this.password }, headers: { 'Content-Type': 'application/json' } }) .then(response => { this.$store.commit('loginAuth', true); // setting isAuth to true in vuex store. this.$store.commit('setUser', response.data.user); // to access the user object since I don't use django templates this.$router.push({name: 'page'}); // redirect to random test page that requires authorization so I can see if everything went fine. }) .catch(err => { console.error(err); if (err.response.status == 401) { alert(err.response.data.wrong); this.isLoading = false; } }) but I was naive and I thought this … -
S3; static fies cannot be loaded suddenly both on local and production
My static files on S3 cannot be loaded suddenly. HTTP403: FORBIDDEN - The server understood the request, but is refusing to fulfill it. Actually it sometimes works so I am sure environment variables are set correctly, but almost doesn't work. Immediately after I deployed my Django project into elasticbeanstalk, static files cannot be loaded even on local. Is this related to it? What is the cause of this error? Here is my settings.py but I never changed. It did work completely but doesn't work suddenly. #AWS S3 configuration # --------------------------------------------------------------------------------- AWS_ACCESS_KEY_ID = os.environ.get('AWS_ACCESS_KEY_ID', '') AWS_SECRET_ACCESS_KEY = os.environ.get('AWS_SECRET_ACCESS_KEY', '') AWS_STORAGE_BUCKET_NAME = os.environ.get('AWS_STORAGE_BUCKET_NAME', '') AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' AWS_DEFAULT_ACL = None #STATIC FILES configuration # --------------------------------------------------------------------------------- # https://docs.djangoproject.com/en/2.0/howto/static-files/ STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_DIRS = ( os.path.join(APPS_DIR, 'static'), ) Anyone who could give me tips to find the cause and how to fix this? -
Firebase Integration with Django REST
I am building a mobile application on Flutter and have integrated a Firebase login to the application. I also have a Python Django REST API that is called within the app. I am hoping to integrate Firebase with the REST API so that the users in Firebase can become authenticated users of the API (and so I can create tokens and tokenize the API endpoint). Does anyone know of a method I can use for this? Novice programmer and new to Firebase so let me know if there is a better way to do this! Appreciate the help.