Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django RelatedObjectDoesNotExist error related in foreign key
my model : class Problem(models.Model): ... prob_id = models.IntegerField(null=False, unique=True) #autofield?, (unique=True) ... def __str__(self): return str(self.prob_id) def prob_path(instance, filename): return 'upload/{0}/{1}'.format(instance.problem, filename) class Testcase(models.Model): problem = models.ForeignKey(Problem, on_delete=models.CASCADE) input_data = models.FileField(upload_to=prob_path) output_data = models.FileField(upload_to=prob_path) def __str__(self): return str(self.problem) views.py : def problem_write_foruser(request): if request.method == "GET": form = ProblemForm() form_t = TestcaseForm() if request.method == "POST": form = ProblemForm(request.POST) form_t = TestcaseForm(request.POST, request.FILES) if form.is_valid(): user = CustomUser.objects.get(username = request.user.get_username()) new_problem = Problem( ... prob_id = form.cleaned_data['prob_id'], ... ) new_problem.save() if form_t.is_valid(): form_t.problem = new_problem form_t.input_data = Testcase(input_data = request.FILES['input_data']) form_t.output_data = Testcase(output_data = request.FILES['output_data']) form_t.save() return redirect('koj:problemset') context = {'form':form, 'form_t':form_t} return render(request, 'koj/problem_write_foruser.html',context) forms.py class ProblemForm(forms.ModelForm): ... prob_id = forms.IntegerField() ... class Meta: model = Problem fields = ['prob_id', 'title', 'body', 'input', 'output', 'time_limit', 'memory_limit'] class TestcaseForm(forms.ModelForm): input_data = forms.FileField() output_data = forms.FileField() class Meta: model = Testcase fields = ['input_data', 'output_data'] when i submit this form in website, RelatedObjectDoesNotExist error is occured i think 'form_t.problem = new_problem' in views.py and relation of Problem model and Testcase model Testcase has no problem. Request Method: POST Request URL: http://127.0.0.1:8000/problem_write_foruser/ Django Version: 3.0.8 Exception Type: RelatedObjectDoesNotExist Exception Value: Testcase has no problem. Exception Location: /home/dsyun/grad/venvs/mysite/lib/python3.6/site- packages/django/db/models/fields/related_descriptors.py in get, line … -
How to upload Multiple images using Django Rest Framework using foreign key?
i can not upload multiple image using Django rest framework.i have Searched this and i Found that using ForeignKey we can upload multiple images.for that We have to make two models.But i dont know how to use Foreign key for multiple image upload.i have tried many Code but did not Worked.can any one help me with this Issue? i have following code, In My models.py class UserModel(models.Model): username= models.CharField(max_length=255) user_images= models.ImageField(upload_to='images/') In My Forms.py from django import forms from user_register.models import UserModel #user_register is my app name class UserForm(forms.ModelForm): class Meta: model = UserModel fields = "__all__" My serializers.py is from user_register.models import UserModel #user_register is my app name from rest_framework import serializers class userSerializer(serializers.ModelSerializer): class Meta: model = UserModel fields = "__all__" And This is My views.py @api_view(['POST','GET']) def userfunction(request): if request.method=='POST': form = UserForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponse('Data Inserted') else: return HttpResponse('form is invalid') i Want my all images to be saved in 'images' folder.Can any one help me with this Issue? i would appreciate if anyone can help me. -
Creating React-Django project
I have confusion on creating react django project.I found two type of approaches of creating react-django project. First creating django project and the integrate react on it.(using npm run build) Creating react project and django project seprately Which approach is best?and which to use when? -
I am unable to install Django in my machine, It is showing error and I don't know what exactly I am doing wrong
Hello I tried installing Django in my laptop, but due to some reason it is not installing properly. i don't know what to do please help me. I have Python 3.8.5 installed in my computer, and I am using Windows 10 operating system. I tried installing django using pip install django It is giving me this error C:\Users\DELL>pip install django Collecting django Downloading Django-3.1.1-py3-none-any.whl (7.8 MB) |▌ | 143 kB 8.0 kB/s eta 0:16:01ERROR: Exception: Traceback (most recent call last): File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pip\_vendor\urllib3\response.py", line 437, in _error_catcher yield File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pip\_vendor\urllib3\response.py", line 519, in read data = self._fp.read(amt) if not fp_closed else b"" File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pip\_vendor\cachecontrol\filewrapper.py", line 62, in read data = self.__fp.read(amt) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\http\client.py", line 458, in read n = self.readinto(b) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\http\client.py", line 502, in readinto n = self.fp.readinto(b) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\socket.py", line 669, in readinto return self._sock.recv_into(b) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\ssl.py", line 1241, in recv_into return self.read(nbytes, buffer) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\ssl.py", line 1099, in read return self._sslobj.read(len, buffer) socket.timeout: The read operation timed out During handling of the above exception, another exception occurred: Traceback (most recent call last): File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pip\_internal\cli\base_command.py", line 228, in _main status = self.run(options, args) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pip\_internal\cli\req_command.py", line 182, in wrapper return func(self, options, args) File "c:\users\dell\appdata\local\programs\python\python38-32\lib\site-packages\pip\_internal\commands\install.py", line 323, in run … -
KeyError at /api/stores/product/create/ 'product_variation' in Postman while testing Django rest framework api
Hey guys i am getting this KeyError at /api/stores/product/create/ 'product_variation' in Postman while testing Django rest framework api. What has gone wrong with my code? Please do help. serializer class ProductCreateSerializer(serializers.ModelSerializer): images = serializers.ListField(child=serializers.ImageField()) #limit the number of images to 5 product_variation = ProductVariationSerializer(many=True, required=False) def create(self, validated_data): image = self.context['request'].FILES.get('image') images = self.context['request'].FILES.getlist('images') images_data = validated_data.pop('images') variations_data = validated_data.pop('product_variation') product = Product.objects.create(user= self.context['request'].user, **validated_data) for image in images_data: ProductImage.objects.create(product=product, **image) for variation in variations_data: ProductVariation.objects.create(product=product, **variation) return product views class ProductCreateAPI(generics.CreateAPIView): serializer_class = ProductCreateSerializer permission_classes = [IsAuthenticated] authentication_classes = (TokenAuthentication,) def create(self, request, *args, **kwargs): serializer = ProductCreateSerializer(data=request.data, context={'request':request,}) if serializer.is_valid(): serializer.save() return Response({'response':'Product listed successfully.'}, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) This is how I give in postman, the product_variation as key and [{ "size-colour": "1", "size_name": "small", "colour_name": "Green", "price": "100", }, { "size-colour": "2", "size_name": "medium", "colour_name": "Blue", "price": "100", }] and this as the value, but still it shows the error. What can be the reason? Thanks -
How to launch this command mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql on Xampp Ubuntu
Hello i'm writing a website in django but I've this error: *Database returned an invalid datetime value. Are time zone definitions for your database installed?* People say that to solve this, i want to run this code: mysql_tzinfo_to_sql /usr/share/zoneinfo | mysql -u root -p mysql The problem is that, I can't run this command because I'm using MySql from Xampp. How can I launch this command using Xampp's MySql? -
How do I create a custom view that doesn't depend on a model in the Django admin site?
Is it possible to have the Django admin site have a link to a custom view that isn't actually a model alongside the models? That custom view will have an add functionality that adds to every model in my existing database. -
Python Django: Filled in form field always throws error "This field is required" on POST
I have a form where I just included one textbox and a submit button. Everytime when I fill in the textbox and try to submit the form validation fails and the error message "This field is required" gets thrown. add_stock.html {% extends 'base.html' %} {% block content %} <h1>Add Stock</h1> <form action="{% url 'add_stock' %}" method="POST" enctype="multipart/form-data"> {% csrf_token %} <input class="form-control" type="text" id="ticker"> <button type="submit" class="btn btn-primary">Add</button> </form> {{ form.errors }} {% endblock %} views.py def add_stock(request): if request.method == 'POST': form = StockForm(request.POST or None) if form.is_valid(): form.save() messages.success(request, ('Stock has been added')) return redirect('overview') return render(request, 'add_stock.html', {'form':form}) return render(request, 'add_stock.html', {}) models.py from django.db import models class Stock(models.Model): ticker = models.CharField(max_length=10) #trade_date = models.DateField(blank=True, default='') #quantity = models.IntegerField(blank=True, default='') #unit_price = models.DecimalField(max_digits=8, decimal_places=2, blank=True, default='') #brokerage = models.DecimalField(max_digits=3, decimal_places=2, blank=True, default='') def __str__(self): return self.ticker forms.py from django import forms from .models import Stock class StockForm(forms.ModelForm): class Meta: model = Stock fields = ["ticker"] #fields = ["ticker", "trade_date", "quantity", "unit_price", "brokerage"] Error message -
How to fetch Google Meet participants using Google Api - Python
Hey we are creating Google Meet links using Calendar Api. No we have requirement to fetch participants in a meeting. We are able to see the participants from Gsuite Audit Report. We tried using Admin SDK Reports API. But we have getting Access denied googleapiclient.errors.HttpError: <HttpError 401 when requesting https://www.googleapis.com/admin/reports/v1/activity/users/all/applications/meet?alt=json&maxResults=10 returned "Access denied. You are not authorized to read activity records."> SCOPES = ['https://www.googleapis.com/auth/admin.reports.audit.readonly'] def main(): creds = ServiceAccountCredentials.from_json_keyfile_name('srv.json', scopes=SCOPES) service = build('admin', 'reports_v1', credentials=creds) results = service.activities().list(userKey='all', applicationName='meet', maxResults=10).execute() print(results) We are using python (Django) -
How to implement upvotes and downvotes in Django models?
I am trying to develop a reusable votes Django application that can fit any model and allow me to avoid code duplication. Its purpose should be to just upvote and downvote objects. For example, I could develop a project where there are Question and Answer models, both of which have their respective score field (upvotes - downvotes). The code in models.py could look something like this: class Question(models.Model): score = models.IntegerField(default=0) def upvote(self): self.score += 1 def downvote(self): self.score -= 1 class Answer(models.Model): score = models.IntegerField(default=0) def upvote(self): self.score += 1 def downvote(self): self.score -= 1 It is clear that this code would work but is not well designed since the two models are practically a copy of one another. To solve this, I was thinking about creating a votes app with perhaps a Vote model in it that would fit both the Question and Answer models described above. I tried to create a single Vote model in votes/models.py, but I ended up needing two models anyway: a QuestionVote and an AnswerVote model. Besides, I could not really integrate this code with the Question and Answer models at all. Here is the general idea for the QuestionVote model I came … -
Django rest framework one to one relation model
I would like to add phone number as one to one relation to django User table. is there I can get phone number field too at the registration. -
Admin filters for django admin
Django admin provides very basic view for applying filters on List pages but we have several uses cases where we want multi select, multi search, range filtering. These cases include applying filtering on related fields and reverse related fields as well We explored several packages https://github.com/modlinltd/django-advanced-filters https://github.com/silentsokolov/django-admin-rangefilter https://github.com/lukasvinclav/django-admin-numeric-filter but none seems to fit our use cases well without fiddling with base model admin. Are there alternatives to these ? If creating own custom filters how are you handling such uses cases ? - any ideas / tips / suggestion to start with ? I did get some idea for search here - https://medium.com/@hakibenita/how-to-add-a-text-filter-to-django-admin-5d1db93772d8 for multiple options to search, planning to use comma separated values and then split that in backend confused on how to implement for multi select choices -
Pyinstaller Django Channels issue
I'm trying to pack a django app into an .exe, after a multiple tries (hooks etc...) Everything works fine, except django-channels. When I run mysite.exe runserver, the app starts but the routing are not found and channels are not working. Here is my .spec -- mode: python ; coding: utf-8 -- block_cipher = None a = Analysis(['mysite\manage.py'], pathex=['C:\Users\SFadili\Documents\_Never Backup\Django\help2'], binaries=[], datas=[ ('mysite/templates', 'templates'), ('mysite/static', 'static'), ('C:\Users\SFadili\Documents\_Never Backup\Django\help2\my_env_0\Lib\site-packages\plotly\', 'plotly'), ('C:\Users\SFadili\Documents\_Never Backup\Django\help2\my_env_0\Lib\site-packages\daphne\', 'daphne'), ('C:\Users\SFadili\Documents\_Never Backup\Django\help2\my_env_0\Lib\site-packages\daphne-2.5.0.dist-info\', 'daphne-2.5.0.dist-info'), ('C:\Users\SFadili\Documents\_Never Backup\Django\help2\my_env_0\Lib\site-packages\raven\', 'raven'), ('C:\Users\SFadili\Documents\_Never Backup\Django\help2\my_env_0\Lib\site-packages\raven-6.10.0.dist-info\', 'raven-6.10.0.dist-info'), ], hiddenimports=[ 'mysite.routing', 'mysite.urls', 'myapp.apps', 'myapp.urls', 'myapp.routing', 'myapp.consumers', 'channels.apps', 'channels_redis', ], hookspath=[], runtime_hooks=[], excludes=[], win_no_prefer_redirects=False, win_private_assemblies=False, cipher=block_cipher, noarchive=False) pyz = PYZ(a.pure, a.zipped_data, cipher=block_cipher) exe = EXE(pyz, a.scripts, a.binaries, a.zipfiles, a.datas, [], name='mysite', debug=False, bootloader_ignore_signals=False, strip=False, upx=True, upx_exclude=[], runtime_tmpdir=None, console=True ) coll = COLLECT(exe, a.binaries, a.zipfiles, a.datas, strip=False, upx=True, upx_exclude=[], name='manage') FYI : I had an issue with daphne saying that another application is using the server, I solved it by modifiying the pyi_rth_twisted.py file into : from twisted.internet import asyncioreactor This creates module: sys.modules['twisted.internet.reactor'] asyncioreactor.install() when I run the server , I got thit : System check identified no issues (0 silenced). September 14, 2020 - 10:13:24 Django version 2.2.16, using settings 'mysite.settings' Starting development server at http://127.0.0.1:8000/ Quit the … -
Django - nearby user without geodjango?
I'm looking for any suggestions and alternative to Geodjango. My goal is to propose to user to find the nearest users and display a distance between them. I got a classical model for localisation. class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) latitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') longitude = models.DecimalField(max_digits=9, decimal_places=6, blank=True, default='0') ... -
Django Quill text-editor
I have a problem when trying to add a value to QuillField field. I have a model field like this : ... from django_quill.fields import QuillField ... ... quill_field = QuillField(blank=True, null=True) #QuillField ... And the idea is to add a value on object creation inside the create function : ... if form.is_valid(): obj_ = form.save(commit=False) ... obj_.terms_of_use_text = get_default_terms() #Here obj_.save() ... ... With get_default_terms() function which basically just pulls all the text from txt file: def get_default_terms(): cpath = Path.cwd() document = open((Path(cpath, 'properties/defaultTerms.txt'))).read() text_json = { "delta": "{\"ops\":[{\"insert\":\"%s} \\n\"}]}", "html": "<p></p>" } return json.dumps(text_json['delta'] % document) get_default_terms() function returns simple text in a normal format : "TERMS AND CONDITIONS\nAll of the membership rules contained herein apply equally to members, temporary members and guests alike.\nOverview\nAll reference to the [Property Address] or [Property/Company Name] refers to [Property/Company Name], its staff, employees, sub contractors, agents and representatives. Facilities refer to any of the rooms to be reserved within. Including but not limited to: the gymnasium, showers, saunas, changing rooms and fitness studios where applicable.\n... The problem appears when I try to save the text inside the QuillField, I get django_quill.quill.QuillParseError: Failed to parse value error. Any idea why I can't … -
Django bulk_update not working on default attributes
I want to change the default value of an attribute from a model in Django. So I want to update the existing values in the database. Strange enough, a bulk update doesn't change those values. My model: class UserSettings(models.Model): offline_notification_filter = models.BooleanField(default=False) My test class TestSetOfflineNotificationMigration(APITestCase): def test_set_offline_notification_filter_to_false(self): user_settings_1 = UserSettingsFactory(offline_notification_filter=True) user_settings_2 = UserSettingsFactory(offline_notification_filter=False) user_settings_3 = UserSettingsFactory(offline_notification_filter=True) user_settings_4 = UserSettingsFactory() all_user_settings = UserSettings.objects.all() for user_setting in all_user_settings: user_setting.offline_notification_filter = False UserSettings.objects.bulk_update( all_user_settings, ["offline_notification_filter"] ) self.assertEqual(user_settings_1.offline_notification_filter, False) This test is failing because the the offlince_notification_filter is not updating. Anyone knows why not? -
In Django, how to keep many-to-many relations in sync?
What's the best way, in Django, to set and keep up-to-date a many-to-many field that is (for a lack of a better term) a composite of many-to-many fields from other models? To give a concrete example, I have a Model representing a Resume. class Resume(models.Model): owner = models.OneToOneField( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="resume", ) description = models.TextField(default="Resume description") skills = models.ManyToManyField(Skill, related_name="resume") The Resume object is referenced by another model called WorkExperience: class WorkExperience(models.Model): ... skills = models.ManyToManyField(Skill, related_name="work") owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=False, default=1, related_name="work_experience", ) resume = models.ForeignKey( Resume, on_delete=models.CASCADE, null=False, default=1, related_name="work_experience", ) Notice that there's a fair amount of redundancy here, with both Resume and WorkExperience pointing to the same owner etc. That said, both of these Models (Resume & WorkExperience) have a field called Skills. That reference another Model called Skills. What I'd like is to have the Resume skills to point to the same skills as the ones in WorkExperience. Any suggestions on how to do this? I also have a Model called EducationExperience which also references Skills and has a foreign key relation to Resume. Is there any way to keep the skills in Resume be in sync with both the skills in WorkExperience … -
Pytest Django: access database but not in a transaction
According to the documentation of pytest.mark.django_db https://pytest-django.readthedocs.io/en/latest/helpers.html#pytest-mark-django-db-request-database-access, using pytest.mark.django_db Each test will run in its own transaction This makes it tricky to test certain behaviours with multiple sessions [say, with others started in other threads]. Specifically, if production code uses autocommit, which is the default, changes due to database statements become visible to other sessions immediately. However, in the test, changes in the main session won't be visible to others since the first is wrapped in a transaction. However, if I don't use pytest.mark.django_db, then running the test I get the error: RuntimeError: Database access not allowed Is it possible to have database access, but not in a transaction? -
"detail": "Authentication credentials were not provided." test.py
I am writing a test in test.py like this class TodoListCreateAPIViewTestCase(APITestCase): url = reverse("todolist:add") def setUp(self): self.username = "john" self.email = "john@snow.com" self.password = "you_know_nothing" self.user = User.objects.create_user(self.username, self.email, self.password) self.token = Token.objects.create(user=self.user) self.api_authentication() def api_authentication(self): self.client.login(username=self.username, email=self.email , password=self.password) self.client.credentials(HTTP_AUTHORIZATION='Token ' + self.token.key) def test_create_todo(self): self.client.force_login(user=self.user) response = self.client.post(self.url, {"list_name" : "Clean the room!"} format='json', HTTP_AUTHORIZATION='jwt {}'.format(self.token)) self.assertEqual(201, response.status_code) and this always gives 401 in return. how I can authenticate properly user here. any kind of help would be highly appreciated . -
Django - public profile with slug - how to use two user models?
I've created a public profile with slug -> .../slug of user/ My issue is how I can know if current_user (user of the slug of the page has an active story): {% if current_user.story.is_active %}new_story_available{% else %}no{% endif %} That does not work because current_user is related to userprofile models. Does anyone has an idea? user.views.py @login_required(login_url='/cooker/login') def userpublicpostview(request, slug): user = get_object_or_404(User.objects.select_related('userprofile'), username=slug) ... storys = Story.objects.filter(user_id=user.id) return render(request, 'user_public_profile.html', { 'current_user': user, ... 'user_storys': storys, }) user/models.py class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) ... is_online = models.BooleanField(default=False) slug = models.SlugField(editable=False) class Story(models.Model): user = models.ForeignKey(User, blank=True, null=True, on_delete=models.CASCADE,related_name='user_storys') title = models.CharField(max_length=200, unique=False) image = models.ImageField(upload_to='story/') created_on = models.DateTimeField(auto_now_add=True) @property def is_active(self): now = timezone.now() if (self.created_on + timedelta(days=1)) > now: return True return False -
Display an inherited Field in Django ModelAdmin
I have models.py file as follows. from django.db import models class UpdateCreateModelMixin: created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Question(UpdateCreateModelMixin, models.Model): name = models.CharField(max_length=100) code = ... ... (Some more field) How do I display the updated, created fields in the Django model Admin, my admin.py file is from django.contrib import admin from .models import Question class QuestionAdmin(admin.ModelAdmin): list_display = ('name', 'created', 'updated') list_filter = ('created') admin.site.register(Question, QuestionAdmin) For the above admin.py file I am getting this error. <class 'assignments.admin.QuestionAdmin'>: (admin.E116) The value of 'list_filter[0]' refers to 'created', which does not refer to a Field. So, how do I add an inherited fields in the django model Admin and why is the above failing? -
how to put tags in articles in python django in website
my client want me to build an article post website in which the user come and login and write the articles.in article he must put tags and with those tags the other users can search. the problem is i do not know how to put tags in views. and also in html .enter image description here and my views file is: enter image description here can any body please help me with sample coding -
How can i make a post request to a rest api endpoint and the request to save my form in a view file in django?
So i am trying to send a JSON file to a rest API endpoint and i am trying to use the requests library and it doesn't work. Also in the function i have a return render to another page, because when i save a form i want also to send a request to the rest api to send an email and they only send emails via the endpoint. from django.shortcuts import render from django.views.generic import View from Upload_Page import models from django.core.files.storage import FileSystemStorage from Upload_Page.forms import Upload_Document from django.shortcuts import redirect #from django.core.mail import send_mail from Upload_Page.mail import mail_class import requests import json def upload_doc(request): if request.method == 'POST': form = Upload_Document(request.POST, request.FILES) if form.is_valid(): form.save() mail=mail_class() jsonmail=mail.createSimpleMail() requests.post("http://mail.internal.de1.bosch-iot-cloud.com:80/email",data=json.dumps(jsonmail)) #send_mail('Title','Body','DigitalLibrary.BoschECC@bosch.com',['fixed-term.Razvan.Sabou@ro.bosch.com'],fail_silently=False) return render(request,'Upload_Page/upload_successful.html') else: form = Upload_Document(auto_id=True,label_suffix='') return render(request, 'Upload_Page/upload_page.html', {'form':form}) So this is the code, and i do not know why it doesn't send the post request, i checked the terminal to see what requests are made and the request from the requests it doesn't appear. I've searched but i am new in django and Rest API and i didn't find the answer for my problem, if you need any more information i can provide it to you. So … -
Feeding json data from Django into jquery function
I am implementing some jquery code for filtering, which initially takes data from a json file: function getProducts() { $.get("products.json", (products) => { ...; }) However, instead of fetching a json file, I'd like to use a json-like array and use that instead of the json file. This data would come from the Django backend, which would pass the data onto the html template. Something like this: var products = {{jsonData}} which would then be this: var products = [ { "id": 1, "category": "shirts", "name": "Fantasy T-shirt", "rating": 4, }, { "id": 2, "category": "hoodies", "name": "Wolf Hoodie", "rating": 5, }, ] How could I modify the jquery code to accept that? Thanks! -
My site is not available after installing Let's Encrypt certification
I am a beginner in web development. I built a site with Django, saw that my site was not fully secure, found out the following tutorial and installed certbot on my server. https://www.digitalocean.com/community/tutorials/how-to-secure-nginx-with-let-s-encrypt-on-ubuntu-18-04 I followed all the guideline in that tutorial and it worked fine with no error, but after that, my site is completely inaccessible on any devices(it's not a problem of cache I think). I used lightsail AWS, ubuntu 18.04 and nginx, and my server block content is: server { server_name 1.23.456.7 mysite.com www.mysite.com; location = /favicon.ico {access_log off; log_not_found off; } location /static { alias /home/ubuntu/projects/mysite/static; } location / { include proxy_params; proxy_pass http://unix:/tmp/gunicorn.sock; } listen 443 ssl; # managed by Certbot ssl_certificate /etc/letsencrypt/live/mysite.com/fullchain.pem; # managed by Certbot ssl_certificate_key /etc/letsencrypt/live/mysite.com/privkey.pem; # managed by Certb$ include /etc/letsencrypt/options-ssl-nginx.conf; # managed by Certbot ssl_dhparam /etc/letsencrypt/ssl-dhparams.pem; # managed by Certbot } server { if ($host = www.mysite.com) { return 301 https://$host$request_uri; } # managed by Certbot if ($host = mysite.com) { return 301 https://$host$request_uri; } # managed by Certbot listen 80; server_name 1.23.456.7 mysite.com www.mysite.com; return 404; # managed by Certbot } I have absolutely no idea on how to solve the problem. Please help me.