Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to send data from React to Django API
I'm trying to add some data to an database with django. As frontend I use React. Thus, fetch request is as follows: const data = { name: formData.name, email: formData.email, title: formData.title, message: formData.message }; fetch("/some/some_view/", { method: 'POST', headers: { 'Accept': 'application/json, text/plain, */*', "Content-Type": "application/json" }, body: JSON.stringify(data), }) .then((response) => response.json()) .then((data) => { debugger; console.log('Success:', data); }) .catch((error) => { debugger; console.error('Error:', error); }); And in Django I have view as follows: @csrf_exempt def some_view(request): if request.method == 'GET': return HttpResponse('Unauthorized', status=400) if request.method == 'POST': #TODO: Add security item = json.loads(request.POST.get('body'), object_hook=json_util.object_hook) pdb.set_trace() return HttpJsonOk() In request.POST I get the data that I want to send as follows: <QueryDict: {u'{"name":"dsdsd","email":"dsdsd@dsds.com","title":"dsds jflj ","message":"dlkj lksj kmsdkk fljs m"}': [u'']}> But I expect it to be in request.POST.get('body'), but there I do not get anything. Any idea? -
Updating Vue files of an old system(3 years old) resulting in unexpected results
So I am facing this weird error. 3 years ago we had a vue/django based project built which at the time was working perfectly. However, now if I even update the html part of a vue file, the page isn't loading. The header and fotters are loading, but not the body. I wonder what the problem is. I also use webpack/babel in this project, and it is compiling successfully. I wonder what's going wrong. -
django.shortcuts reverse() call at class var result as error URLconf 'xxx.urls' does does not appear to have any patterns in it
1.evn python3.5 django2.2 2.problem call django.shortcut: reverse() at initializing class variable, compilation is fully ok. Got runtime error: The included URLconf 'xxx.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused by a circular import. Moreover this error message is quite mis-leading, and I spend many time to check the urls which are actually fully correct. 3.Code example from django.views import View from django.shortcuts import render, reverse, redirect class LoginView(View): main_page = reverse('main') => cause runtime error def get(...): def post(...): urlpatterns = [ path(r'login/', authviews.LoginView.as_view(), name='login'), path(r'main/', authviews.MainView.as_view(), name='main'), ... 4.Runtime Error Message File ".../auth/view/views.py", line 10, in <module> class LoginView(View): File ".../auth/view/views.py", line 13, in LoginView main_page = reverse('main') File ".../.local/lib/python3.5/site-packages/django/urls/base.py", line 90, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File ".../.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 600, in _reverse_with_prefix self._populate() File ".../.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 438, in _populate for url_pattern in reversed(self.url_patterns): File ".../.local/lib/python3.5/site-packages/django/utils/functional.py", line 80, in __get__ res = instance.__dict__[self.name] = self.func(instance) File ".../.local/lib/python3.5/site-packages/django/urls/resolvers.py", line 580, in url_patterns raise ImproperlyConfigured(msg.format(name=self.urlconf_name)) django.core.exceptions.ImproperlyConfigured: The included URLconf 'xxx.urls' does not appear to have any patterns in it. If you see valid patterns in the file then the issue is probably caused … -
How to do a reverse look up of m2m field within django template
Hello i've been trying to do a reverse m2m query and count but have failed to do so. The methods suggested by other posts dont seem to work , here is my code currently. This is the relevant bit in my HTML: <table id='myTable' class="display ui celled table" style="width:100%"> <thead> <tr> <th>ID</th> <th>Company</th> <th>Company Address</th> <th>Telephone</th> <th>Total Projects</th> </tr> </thead> {% for customer in customers %} <tr> <td>{{ customer.customer_id }}</td> <td><a href="{% url 'customer-profile' customer.customer_id %}" class='btn w3-teal'>{{ customer.customer_name }}</a></td> <td>{{ customer.address }}</td> <td>{{ customer.telephone_number}}</td> {% for project in customer.salesProject_set.all %} <td>{{project.count}}</td> {%endfor%} </tr> {% endfor %} </table> </div> This is my view: class CustomerView(ListView): model = CustomerInformation template_name = 'rnd/customers_all.html' context_object_name = 'customers' def get_context_data(self, **kwargs): context = super(CustomerView, self).get_context_data(**kwargs) context['customers'] = CustomerInformation.objects.all() return context This is my models: class SalesProject(models.Model): customer_information = models.ManyToManyField('CustomerInformation') class CustomerInformation(models.Model): customer_id = models.AutoField(primary_key=True) customer_name = models.CharField(max_length=100, default='Lee Ji Eun') telephone_number = models.CharField(max_length=100) I intend to access the m2m field within the template in order to display the relevant count of the number of projects associated with that company but the results displays nothing without throwing any error. Any help would be greatly appreciated! -
How to trigger a function when customer accepts call Twilio Javascript Client?
I have integrated Twilio in my django application to make phone calls to customers and it is working fine but now the problem is I want to check when customer accepts the call and then I want to trigger a function which will start calculating call time. I'm unable to find any function that will be fired when support agent make call to customer and he accepts the phone call. browser-calls.js // Store some selectors for elements var hangUpButton = $('.hangup-button'); var callCustomerButtons = $('.call-customer-button'); var callTime = $('#call-time'); var interval; /* Get a Twilio Client token with an AJAX request */ $(document).ready(function() { $.get('/support/token', { forPage: window.location.pathname }, function(data) { // Set up the Twilio Client Device with the token Twilio.Device.setup(data.token); }); }); /* Report any errors to the call status display */ Twilio.Device.error(function(error) { updateCallStatus('ERROR: ' + error.message); }); /* Callback for when Twilio Client initiates a new connection */ Twilio.Device.connect(function(connection) { // Enable the hang up button and disable the call buttons hangUpButton.prop('disabled', false); callCustomerButtons.prop('disabled', true); callSupportButton.prop('disabled', true); answerButton.prop('disabled', true); // If phoneNumber is part of the connection, this is a call from a // support agent to a customer's phone if ('phoneNumber' in connection.message) { updateCallStatus('In … -
How to reload a perticular area in html once the form updated
I have a form I need to update the profle picture using Ajax.... Once it get uploaded the area needs to be change without refreshing the page Here is my html <div class="row"> <div class="col-md-12"> <form data-action="{% url 'user-profileupdate' %}" id="profile-file-upload" method="post" enctype="multipart/form-data"> <div class="text-center"> <div class="avatar-upload"> <div class="avatar-edit"> <input name="input_file" type="file" id="profile-pic-upload" /> <label for="profile-pic-upload"></label> </div> <div class="avatar-preview"> {% if user_profile.avatar %} <div id="imagePreview" style="background-image: url('{{user_profile.profile_pic}}');"></div> {% else %} <div id="imagePreview" style="background-image: url('{% static 'assets/img/user-64x.png' %}');"></div> {% endif %} </div> </div> </div> </form> </div> </div> Here is the javascript part $("#profile-pic-upload").change(function () { var data = new FormData(); var file = this.files[0]; data.append("file", file); $.ajax({ type: 'POST', data: data, contentType: false, processData: false, url: $("#profile-file-upload").data('action'), cache: false, success: function (data, status) { if (data['status'] == true) { toastr.success(data.msg); $('#profile-pic-upload').val(''); } else { toastr.error(data.msg); } } }); }); Currently a toster is updating in the successfunction I need to update the image via ajax success -
How to use filtering data while using distinct method in django?
I hope my title is enough to understand what i mean is, please help me on this problem guys.. when I tried this id_list = grade.objects.filter(Teacher=m.id).values_list('Students_Enrollment_Records_id',flat=True).distinct() I use distinct() to eliminates duplicate rows of Students Enrollment Record from the query results but I wonder why the result is like this what should i do to show the Students name not that QuerySet in my html? this is my current views.py id_list = grade.objects.filter(Teacher=m.id).values_list('Students_Enrollment_Records_id',flat=True).distinct() print(id_list) grades = grade.objects.filter(Students_Enrollment_Records_id__in=id_list) print(grades) this is my models.py class grade(models.Model): Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Average = models.FloatField(null=True, blank=True) -
unable to start up django app with runsslserver
I am completely new to Django/python so excuse any wrong vocabulary. I have a Django based application that has been running perfectly on the HTTP protocol in an Ubuntu server. (Django is used both as App server and webserver here) I was asked to migrate the application from HTTP to the HTTPS protocol. I have performed the below steps in the server. Installed the following packages: django-extensions, django-secure, and django-sslserver Added 'sslserver' in setting.py under INSTALLED_APPS Placed certificate and key in /etc/ssl/certs/ and /etc/ssl/private respectively Start-up application with the command: python3 manage.py runsslserver --certificate /etc/ssl/certs/my.cer --key /etc/ssl/private/my.key 172.31.83.127:8081 --configuration=uat I have updated the CLB as below: - CLB Listener CLB Health Check Now, when I run the command in the server I am getting below errors: - File "/usr/lib/python3.5/wsgiref/handlers.py", line 138, in run self.finish_response() File "/usr/lib/python3.5/wsgiref/handlers.py", line 180, in finish_response self.write(data) File "/usr/lib/python3.5/wsgiref/handlers.py", line 279, in write self._write(data) File "/usr/lib/python3.5/wsgiref/handlers.py", line 453, in _write result = self.stdout.write(data) File "/usr/lib/python3.5/socket.py", line 593, in write return self._sock.send(b) File "/usr/lib/python3.5/ssl.py", line 861, in send return self._sslobj.write(data) File "/usr/lib/python3.5/ssl.py", line 586, in write return self._sslobj.write(data) ssl.SSLEOFError: EOF occurred in violation of protocol (_ssl.c:1848) [13/Jan/2020 17:54:54] "GET / HTTP/1.1" 500 59 Exception happened during processing … -
How to display an instances of ontology in django
I have an ontology with that some data. I want to display the data in a form using django, but I have no clue on how to do this. Example: I have two instances of a class (Student) in the ontology as follows: Student1 and Student2. Each instance of the Student class has other attributes, such as gpa, graduation year, etc. Now, I want to pull the information from the ontology and display it in multiple form view where I can edit and then save the information back to the ontology. The multiple formview would look something like this: Form 1 Name: Student1 GPA: 3.5 Graduation Year: 2022 Form 2 Name: Student2 GPA: 2.5 Graduation Year: 2023 **Cancel or Update** -
Getting invalid credentials even the credentials are registered in database in django login form?
I am having a registration,login and dashboard the registration form is successfully registering and the users are storing in the custom user model now after registering the page will go to login now button if user clicks it will redirect to login page in login page I am having a username and password field and it should authenticate with the registered users and if the credentials are valid the dashboard page should come but here the problem after registration when I go to login page and try to login with the credentials which are registered I am getting message as invalid credentials. My views.py from django.shortcuts import render, redirect from django.contrib import messages, auth from django.contrib.auth.models import User from contacts.models import Contact from django.shortcuts import render,HttpResponseRedirect from django.contrib import messages,auth from account.forms import UserForm from account.forms import UserRequirementForm from django.contrib.auth import authenticate, login def register(request): return render(request, 'account/register.html',); def user_register(request): if request.method == 'POST': # if there is a post request in the form user_form = UserForm(data=request.POST) #first of all it is a user_form will be posted details present in the user_form user_requirement_form = UserRequirementForm(data=request.POST)# after posting the details of the user_form post the details if user_form.is_valid() and user_requirement_form.is_valid(): # … -
Django Sessions not saved after deploy on vps
this problem makes me crazy for crazy 2 days of debugging and the problem is solving so easily and boom; after deploy my django app on my vps i got a bad error sessions not saved for react client -
Django service worker not able to cache page : Uncaught (in promise) TypeError: Request failed
I am trying to implement django-progressive-web-app into my project and I am having some issues with being able to cache the page. In chrome I am getting the following error Uncaught (in promise) TypeError: Request failed here is the corresponding code serviceworker.js var staticCacheName = 'djangopwa-v1'; self.addEventListener('install', function(event) { event.waitUntil( caches.open(staticCacheName).then(function(cache) { return cache.addAll([ '/base_layout' ]); }) ); }); self.addEventListener('fetch', function(event) { var requestUrl = new URL(event.request.url); if (requestUrl.origin === location.origin) { if ((requestUrl.pathname === '/')) { event.respondWith(caches.match('/base_layout')); return; } } event.respondWith( caches.match(event.request).then(function(response) { return response || fetch(event.request); }) ); }); views.py ... def base_layout(request): return render(request, 'main/home.html') ... urls.py urlpatterns = [ ... #pwa path('', include('pwa.urls')), ] I followed this tutorial: https://medium.com/beginners-guide-to-mobile-web-development/convert-django-website-to-a-progressive-web-app-3536bc4f2862 Any help would be very much appreciated!!! -
Django test database is using local db.sqlite3, not running in memory
When I run Django tests that inserts data into the database, it will insert to my local db.sqlite3 and preserve it when the tests finishes. I don't want this to happen, and it shouldn't be according to the docs: Regardless of whether the tests pass or fail, the test databases are destroyed when all the tests have been executed. My unit test: from unittest import TestCase from web.constants import USER_TYPE_CONTRACTOR from web.models import User class LoginTestCase(TestCase): def setUp(self): self.demo_user_1_username = 'c2' User.objects.create(username=self.demo_user_1_username, password='c12345678') def test_user_defaults_to_contractor(self): demo_user_1 = User.objects.get(username=self.demo_user_1_username) self.assertEqual(demo_user_1.user_type, USER_TYPE_CONTRACTOR) def doCleanups(self): """Delete demo data from database""" # I needed to do this as workaround # demo_user_1 = User.objects.get(username=self.demo_user_1_username) # demo_user_1.delete() The user c2 is now in the db.sqlite3, so when I run the test again, it fails as username c2 already exists. I've tried to do this in settings.py: DATABASES = { 'default': dj_database_url.config(conn_max_age=600) } DATABASES['default']['TEST'] = { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'test_db.sqlite3'), } But test_db.sqlite3 is not created. How can I use an in-memory sqlite3 db so it doesn't affect my local db when testing? -
LookupError: No installed app with label 'admin'
I am working on a HR app using the small-small-hr set up in django. Getting this look up error when i run python manage.py runserver or makemigrations. Below is my code for apps.py and settings.py. What could be going wrong here? apps.py: **from django.apps import AppConfig class SmallSmallHrConfig(AppConfig): """ Apps config class """ name = 'small_small_hr' app_label = 'small_small_hr' def ready(self): # pylint: disable=unused-import import small_small_hr.signals # noqa # set up app settings from django.conf import settings import small_small_hr.settings as defaults for name in dir(defaults): if name.isupper() and not hasattr(settings, name): setattr(settings, name, getattr(defaults, name))** settings.py: **INSTALLED_APPS = [ 'small_small_hr.apps.SmallSmallHrConfig', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites.models.Site'** ] -
How to use the distinct() in Django
when i tried this id_list = grade.objects.filter(Teacher=m.id).values_list('Students_Enrollment_Records_id',flat=True).distinct() I use distinct() to eliminates duplicate rows of Students Enrollment Record from the query results but I wonder why the result is like this what should i do to show the Students name not that QuerySet in my html? this is my current views.py id_list = grade.objects.filter(Teacher=m.id).values_list('Students_Enrollment_Records_id',flat=True).distinct() print(id_list) grades = grade.objects.filter(Students_Enrollment_Records_id__in=id_list) print(grades) this is my models.py class grade(models.Model): Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Average = models.FloatField(null=True, blank=True) -
Jenkins: run test coverage on pipeline job
I made new job using pipeline, and I wanted add function that examine test coverage. So I download plugins like codertuna and violations and tried to add it to pipline job, but it seems like I can use those when I make job using freestyle template. I wonder if I can add test coverage function to pipeline job. -
Ajax - Django: Using Array Of IDs To Filter Model
I have a template with cards that each contain order information and have a checkbox that will allow me to select multiple and then with a button mark them all as paid without having to do it individually. I created an empty array and then push the ID's of the orders that are checked to it on the button click. Then send this array via ajax to filter my model and update the status of the orders whos ID are in the array. However, when I get the array from the request it only reads in the first item. Javascript: var idArray = []; $('input[name="selector"]:checked').each(function(){ idArray.push($(this).attr("id")); }) $.ajax({ url:'/test/ajax', data:{ 'idArray':idArray, }, dataType:'json', success: function(serialized){ parsed = JSON.parse(serialized) console.log(parsed) } }) Django: def ajax_test(request): # get array of order ids # problem - it only returns the first item in the array id = request.GET.get('idArray[]') #return records matching order ids # order = Order.objects.filter(Q(order_id__in = [id])) #mark each record paid serialized = serializers.serialize("json", order) return JsonResponse(serialized, safe = False) -
getting an error while register and login the users in the custom user model in django?
I want the registration for my application with some fields with associations My models.py is: from django.db import models from django.contrib.auth.models import User from datetime import datetime class room(models.Model): id = models.IntegerField(primary_key=True) image = models.ImageField(upload_to='images') content = models.CharField(max_length=50,default='0000000') created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) def __str__(self): return self.content # This is the model for goals class goal(models.Model): id=models.IntegerField(primary_key=True) goal = models.CharField(max_length=50,default='0000000') created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) def __str__(self): return self.goal # This is the model for designs class design(models.Model): id=models.IntegerField(primary_key=True) image = models.ImageField(upload_to='images') content = models.CharField(max_length=50,default='0000000') created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) def __str__(self): return self.content # This is the model for furniture class furniture(models.Model): id=models.IntegerField(primary_key=True) phrase=models.CharField(max_length=60,default='111111') created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) def __str__(self): return self.phrase # This is the user_requirement model where all the details selected by the user will be stored in this model class User_Requirement(models.Model): user=models.OneToOneField(User,on_delete=models.CASCADE) room = models.ForeignKey(room,on_delete=models.CASCADE) goal = models.ManyToManyField(goal) design = models.ManyToManyField(design) furniture = models.ForeignKey(furniture,on_delete=models.CASCADE) created_at = models.DateTimeField(default=datetime.now) updated_at = models.DateTimeField(default=datetime.now) My forms.py is: class UserForm(forms.ModelForm): class Meta: model = User fields = ('user','username','email','password') def clean_email(self): # Get the email email = self.cleaned_data.get('email') # Check to see if any users already exist with this email as a username. try: match = User.objects.get(email=email) … -
Django deployment - 404 Not Found when trying to load file even though it is there
I am trying to deploy a django app and I cannot figure out what I'm doing wrong. One application that I wrote and works quite well when run locally, gives me 404 when I run it on an EC2 instance. Here are the details of the app: #myapp/settings.py ASGI_APPLICATION = 'results.routing.application' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') USER_DATA = os.path.join(MEDIA_ROOT, 'user-data') User uploads are then saved by the following model: #uploads/models.py def user_directory_path(instance, filename): return '{0}/{1}/{2}'.format('user-data', instance.user.username, filename) class jsonModel(models.Model): json= models.FileField(upload_to=user_directory_path, null=True, blank=False) In the static/js/script.js file I have the following line: // static/js/script.js file_name = "/media/user-data/" + username + "/" + "server_side_calculated.json" loadJSON(file_name) The loadJSON function simply reads and plots the data using d3. When I run the server, however, I get the following (uvicorn output): WARNING: Not Found: /media/user-data/user2/server_side_calculated.json But the file is there. So the problem perhaps is on my configuration but I do not know where. In the application url.py I make sure to include + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Normally I'd suspect that I've screwed up somewhere by defining USER_DATA, but the file uvicorn tells me it cannot find, is in fact there. Just to note, the website … -
How to filter the data at the same time distinct()? using Django
this is my data in admin site looks like I use distinct() to eliminates duplicate rows of Students Enrollment Record from the query results but I wonder why the result is like this even though my html code is {% for n in total %} <tr> <td>{{n.Teacher}}</td> <td>{{n.Subjects}}</td> <td>{{total.Students_Enrollment_Records.Students_Enrollment_Records.Student_Users}}</td> <td>{{total}}</td> </tr> {% endfor %} I have this distinct() code in my views.py mystudent = grade.objects.filter(Teacher = m.id).values_list('Students_Enrollment_Records', flat=False).distinct() and this is my model.py class grade(models.Model): Teacher = models.ForeignKey(EmployeeUser, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Grading_Categories = models.ForeignKey(gradingCategories, related_name='+', on_delete=models.CASCADE, null=True, blank=True) Subjects = models.ForeignKey(Subject, related_name='+', on_delete=models.CASCADE, null=True) Students_Enrollment_Records = models.ForeignKey(StudentsEnrolledSubject, related_name='+', on_delete=models.CASCADE, null=True) Average = models.FloatField(null=True, blank=True) can you guys please explain why the result is like this? this is my current complete query id_list = grade.objects.filter(Teacher = m.id).values_list('Students_Enrollment_Records__id', flat=True).distinct() grades = grade.objects.filter(Students_Enrollment_Records_id__in=id_list) print(grades) rating = grade.objects.values('Grading_Categories').annotate(Average=Avg('Average')) print(id_list) this is the current result -
Join two models and concatenate in Django?
I have two models, mpa and Cid - (only displaying relevant data) class Mpa(models.Model): mpa_number = models.CharField(max_length=16) legacy_mpa = models.CharField(max_length=100, null=True, blank=True) rbc_transit_number = models.CharField(max_length=100, null=True, blank=True) class Cid(models.Model): mpa = models.ForeignKey(Mpa,on_delete=models.CASCADE) anchor_cid = models.CharField(max_length=100, null=False, blank=False) campaign_name = models.CharField(max_length=100, null=False) google_cid = models.CharField(max_length=100, null=True, blank=True) I have joined two tables on foreign key, using select_related: result = Cid.objects.all().select_related('mpa') Anchor_cid has one to many relation with mpa_number. I wanted to display all anchor_cid, that corresponds to an mpa_number, in one row (there is a table in template). For concatenating anchor_cid, I have used Concat like this - query_set = test_tables.values('mpa_id').annotate(name = Concat('anchor_cid')) Since .values() returns a dictionary and .all() returns a model instance. I can't figure out a way of joining them together and displaying them in template. I have tried searching for a solution but couldn't find this scenario. Maybe I'm trying to do this in wrong way and somebody can point me in right direction.. (using Django 2.1.5) -
Different python version on production - django
I create a VM instance on Google Cloud Platform and chose ubuntu 18.04LTS as the image for production and as we all know default version of python on version is 2.7. However I created a virtualenv with python3 but that's 3.6.9. While I made my whole project on Manjaro with python version 3.8.1. I followed this tutorial to set everything but as I put my external IP on browser. It keeps loading and gives me Gateway Timeout. Is it because the python version is different because everything else looks fine? -
Angular unable to store jwt token on IOS devices
I am using the following: Angular 7.2.15 django 2.1.7 djangorestframework 3.9.1 djangorestframework-jwt 1.11.0 I am storing a JWT token in localstorage and this works on computers and android phones (at least the ones i tested) but when i try to log in on an iPhone or iPad, it accepts the credentials and shows my landing page for a split second then throws a 401 unauthorized error and logs be back out (i have it set up to log out on 401 errors). I did some debugging using the webtools with safari and it looks like my token is not getting stored and that would explain why i get the 401. My login script is pretty simple login(username, password) { return this.http.post<any>(`${this.apiUrl}/api-token-auth/`, { username, password }) .pipe(map(user => { // store user details and jwt token in local storage to keep user logged in between page refreshes localStorage.setItem('currentUser', JSON.stringify(user)); this._currentUserSubject.next(user); return user; })); } Any thoughts on how i can get this token to store on an iPhone/iPad? Thanks in advance, jAC -
How can I manipulate strings to be stored in fields in Django Crate View?
For example, if filename is passed as below filename = django_inflearn2 \ wm \ views.py I want to modify it like this. django_inflearn2 / wm / views.py The problem is how to get the entered information as a variable. if you know how to fix thanks for let me know code: class MyShortCutCreateView_textarea_summer_note(LoginRequiredMixin,CreateView): model = MyShortCut form_class = MyShortCutForm_summer_note def form_valid(self, form): ty = Type.objects.get(type_name="summer_note") ms = form.save(commit=False) ms.author = self.request.user # file_name = file_name_before.replace("\\","/") # ms.filename = return super().form_valid(form) -
Django - m2m_changed signal not saving changes to related model
I have created a function to run on a m2m_changed signal. After carrying out various actions, I need to update a field on BMGUser objects. Essentially: I subscribe a BMGUser to an AWS Simple Notification Service topic and store the arn in the BMGUser object. The issue: when I update the resorts field on a BMGUser object directly, the code works. When I update the bmg_users field from a Resort object, the function is triggered and runs, but the changes to the user objects in the function do not persist. Code: class Resort(models.Model): """ Resort model """ class BMGUser(models.Model): """ Extend the User model to include a few more fields """ resorts = models.ManyToManyField(Resort, related_name='bmg_users') sub_arn = models.CharField("AWS SNS Subscription arns", max_length=1000, blank=True, null=True) @receiver(m2m_changed, sender=BMGUser.resorts.through) def subscribe_sns_topic(instance: Union[BMGUser, Resort], action: str, reverse: bool, pk_set: Set[int], **kwargs) -> None: """ Subscribe or unsubscribe the user to the relevant resort SNS topic, if resort added to their obj :param instance: BMGUser or Resort object being updated :param action: type of update on relation :param reverse: False if BMGUser is being modified directly; True if Resort object is being modified :param pk_set: set of primary keys being added or removed to the …