Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I want to run a python script of machine learning algorithm using django.
The idea is to make a somewhat replica of Weka, only it won't be a desktop application but it will be a web application. Question.1: Is it even possible? Question.2: How do i run a python code and display results using Django? -
Python manage.py startapp does not work
When I run the python manage.py startapp "app name" command in my Django project directory nothing happens... Every other manage.py command works without problem. What could be the problem? Thanks a lot!! Andrew -
PIp exception error while insalling django
I am installing django in ubuntu using the command pip install django==1.11.2 but i am getting the following error Collecting django==1.11.2 Exception: Traceback (most recent call last): File "/usr/share/python-wheels/urllib3-1.13.1-py2.py3-none-any.whl/urllib3/connectionpool.py", line 555, in urlopen self._prepare_proxy(conn) File "/usr/share/python-wheels/urllib3-1.13.1-py2.py3-none-any.whl/urllib3/connectionpool.py", line 753, in _prepare_proxy conn.connect() File "/usr/share/python-wheels/urllib3-1.13.1-py2.py3-none-any.whl/urllib3/connection.py", line 230, in connect self._tunnel() File "/usr/lib/python3.5/http/client.py", line 832, in _tunnel message.strip())) OSError: Tunnel connection failed: 407 Proxy Authentication Required During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/lib/python3/dist-packages/pip/basecommand.py", line 209, in main status = self.run(options, args) File "/usr/lib/python3/dist-packages/pip/commands/install.py", line 328, in run wb.build(autobuilding=True) File "/usr/lib/python3/dist-packages/pip/wheel.py", line 748, in build self.requirement_set.prepare_files(self.finder) File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 360, in prepare_files ignore_dependencies=self.ignore_dependencies)) File "/usr/lib/python3/dist-packages/pip/req/req_set.py", line 512, in _prepare_file finder, self.upgrade, require_hashes) File "/usr/lib/python3/dist-packages/pip/req/req_install.py", line 273, in populate_link self.link = finder.find_requirement(self, upgrade) File "/usr/lib/python3/dist-packages/pip/index.py", line 442, in find_requirement all_candidates = self.find_all_candidates(req.name) File "/usr/lib/python3/dist-packages/pip/index.py", line 400, in find_all_candidates for page in self._get_pages(url_locations, project_name): File "/usr/lib/python3/dist-packages/pip/index.py", line 545, in _get_pages page = self._get_page(location) File "/usr/lib/python3/dist-packages/pip/index.py", line 648, in _get_page return HTMLPage.get_page(link, session=self.session) File "/usr/lib/python3/dist-packages/pip/index.py", line 757, in get_page "Cache-Control": "max-age=600", File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 480, in get return self.request('GET', url, **kwargs) File "/usr/lib/python3/dist-packages/pip/download.py", line 378, in request return super(PipSession, self).request(method, url, *args, **kwargs) File "/usr/share/python-wheels/requests-2.9.1-py2.py3-none-any.whl/requests/sessions.py", line 468, in … -
Error while running collectstatic while deploying Django to Heroku
I have a django rest framework api that I am trying to deploy to heroku. I run the git push heroku master command and everything works fine up until the collectstatic method is ran. remote: -----> $ python manage.py collectstatic --noinput remote: Traceback (most recent call last): remote: File "manage.py", line 22, in <module> remote: execute_from_command_line(sys.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line remote: utility.execute() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/__init__.py", line 355, in execute remote: self.fetch_command(subcommand).run_from_argv(self.argv) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 283, in run_from_argv remote: self.execute(*args, **cmd_options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/management/base.py", line 330, in execute remote: output = self.handle(*args, **options) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 199, in handle remote: collected = self.collect() remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/management/commands/collectstatic.py", line 115, in collect remote: for path, storage in finder.list(self.ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/finders.py", line 112, in list remote: for path in utils.get_files(storage, ignore_patterns): remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/contrib/staticfiles/utils.py", line 28, in get_files remote: directories, files = storage.listdir(location) remote: File "/app/.heroku/python/lib/python3.6/site-packages/django/core/files/storage.py", line 397, in listdir remote: for entry in os.listdir(path): remote: FileNotFoundError: [Errno 2] No such file or directory: '/tmp/build_f0e1fb0957c8f67cf4c508df62f6ca99/assets' remote: remote: ! Error while running '$ python manage.py collectstatic --noinput'. remote: See traceback above for details. remote: remote: You may need to update application code to resolve this error. remote: Or, you … -
Django - Deleting all the related ForeignKeys to a model
I have a model called Team, with a ForeignKey relationship to Agent (my user model). When an Agent who is a team_leader deactivates the team, all the Agents with team_member set to the current team will have their team_member attribute removed and set to NULL/empty. I read this and this, I know I'm either supposed to do something with ._meta.get_fields() or with the Collector class. I'm experimenting with the get_fields() but haven't managed to get it working. models.py class Agent(AbstractUser): team_member = models.ForeignKey('AgentTeam', on_delete=models.CASCADE, null=True, blank=True, related_name='team_member') team_leader = models.OneToOneField('AgentTeam', on_delete=models.CASCADE, null=True, blank=True, related_name='team_leader') class AgentTeam(models.Model): team_is_active = models.BooleanField(default=False) views.py def deactivate_team(request): request.user.AgentTeam.team_is_active = False # request.user in this case is the team_leader # I need to set all the Agent's with team_member set to the request.user's team to NULL. I have experimented with the code below and gotten only errors, mostly related to ReverseToOne like ''ReverseManyToOneDescriptor' object is not iterable' agents = [ f for f in AgentTeam._meta.get_fields() if (f.one_to_many) and f.auto_created and not f.concrete ] for agent in agents: objects = getattr(AgentTeam, agent.name).all() for object in objects: object.team_member = None Please provide some comments and pointers on my views code and any errors I made. Thank you. -
Check if user has a permission with specific codename in django
I am trying to check if a user has a permission, which I have defined in the class Meta of the model, with a specific codename. At the moment I have: if request.user.has_perm('app_label.code_name'): do something What I am trying to avoid is using the app_label, however using has_perm('code_name') does not seem to work. -
Bad Request 400 on Django Heroku deployment
I'm facing a Bad Request (400) error on my Django deployment on Heroku. The logs show a SuspiciousOperation error, and specifically the platform nags about that: Su spiciousOperation: Attempted access to '/jquery/dist/jquery.min.js' denied. Traceback (most recent call last): ValueError: the joined path is located outside of the base path component I've set my ALLOWED_HOSTS to [.mydomain.com] although the error still persists. Any ideas? -
Django ModelAdmin: How to access data from inline fields?
models.py: class SomeClass(models.Model): name = models.CharField(max_length = 140) total = models.FloatField(default=0) items = models.ManyToManyField(Item, through="ItemDetail") def __str__(self): return self.name class Item(models.Model): name = models.CharField(max_length = 140) amount = models.FloatField(default=0) def __str__(self): return self.name class ItemDetail(models.Model): item = models.ForeignKey('Item') someclass = models.ForeignKey('SomeClass') quantity = models.FloatField() admin.py: class SomeInlineAdmin(admin.TabularInline): model = SomeClass.items.through extra = 1 class SomeClassAdmin(admin.ModelAdmin): fields = ('name','total',) readonly_fields = ('total',) inlines = (SomeInlineAdmin,) list_display = ['name','total',] So, basically when I am adding a new SomeClass through django admin, I would like to add a name, choose some items, mention their quantities and save. now, there's a total field in SomeClass. I would like it to be auto calculated and saved upon saving the model. I want the total to be like the following: total = summation of (item.amount)*(respective quantity mentioned in ItemDetail) I did some digging around save_model method. Couldn't help myself. So, how do i achieve this? I am still very new to Django. Thanks in advance for your help. -
Serializer in Django Rest is not returning a relation object
I have 4 models, one of them is a relation between the other three. The same for the serializers. But when I retrieve the data from the API I'm not receiving all the data, I'm only receiving the fields 'day', 'order' and 'time', not 'teacher', 'subject' and 'in_class' fields declared on ScheduleClassTeacherSubjectSerializer Models: class User(models.Model): name = models.CharField(max_length=20, unique=True, blank=False, null=False) class Subject(models.Model): name = models.CharField(max_length=20, unique=True, blank=False, null=False) class Class(models.Model): name = models.CharField(max_length=20, unique=True, blank=False, null=False) class ClassTeacherSubject(models.Model): teacher = models.ForeignKey(User, related_name='classes_subjects', on_delete=models.CASCADE, null=False, blank=False, ) subject = models.ForeignKey(Subject, related_name='classes_teachers', on_delete=models.CASCADE, null=False, blank=False, ) teaches_in = models.ForeignKey(Class, related_name='teachers_subjects', on_delete=models.CASCADE, null=False, blank=False, ) class Schedule(models.Model): MONDAY = 'MONDAY' TUESDAY = 'TUESDAY' WEDNESDAY = 'WEDNESDAY' THURSDAY = 'THURSDAY' FRIDAY = 'FRIDAY' DAY_CHOICES = ( (MONDAY, 'Monday'), (TUESDAY, 'Tuesday'), (WEDNESDAY, 'Wednesday'), (THURSDAY, 'Thursday'), (FRIDAY, 'Friday'), ) ORDER = ( (1, 1), (2, 2), (3, 3), (4, 4), (5, 5), (6, 6), (7, 7), (8, 8), (9, 9), (10, 10), ) day = models.CharField(max_length=10, choices=DAY_CHOICES, null=False, blank=False ) order = models.IntegerField(choices=ORDER, null=False, blank=False) time = models.TimeField(null=True, blank=True, ) class_teacher_subject = models.ForeignKey(ClassTeacherSubject, on_delete=models.CASCADE, null=False, blank=False, ) class Meta: unique_together = ('day', 'order', 'class_teacher_subject') Serializers: class TeacherSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', … -
How to catch sqlite database locked errors
I have code right now in a Django framework that needs to access a data stored in an Sqlite file and return it as JSON (GeoJSON specifically). This works, but I have a specific case where the database can be accessed in a locked state. I know why the problem is happening, but I'd like to know how to detect when it is happening, and return an appropriate response. My naive guess was to try to catch an Sqlite OperationalError, but this is non-effectual. The problem code: class GetVectorLayer(APIView): def post(self, request): ... ... import sqlite3 try: cache.write_layers(VectorLayer.objects.filter(pk=layer.pk), Formats.GeoJSON, file_path, epsg, bbox) except sqlite3.OperationalError as e: return Response("Cache Locked", status=status.HTTP_423_LOCKED) import json When this executes I get the same error as before I added the try: ERROR 1: sqlite3_step() failed: database is locked (5) The error happens in lower level code that is accessing the DB. That code throws whatever error that is printing to my console, but it doesn't seem to be actually raising an exception fortunately. The error happens when the cache is still being populated from an external source while someone tries to access data from it. I don't know how to properly check for this state … -
django how to change __str__ label by user status?
I want to change select option's label by user status. my model is class BookCategory(model): label_1 = char label_2 = char def __unicode__(self): #something here? class Book(model): name = char categoey = models.Foreignkey(BookCategory) BookCategory is used in createview for new book, and the page has modelform, textinput for book.name and choices for book.catgory. My goal is if user type==1: =>display category's label_1 if user type==2: =>display category's label_2 I know "__unicode__" can display instance's value, but I want to know change its field by user's status. Anyone knows the solution? -
Validate a django form with multiple fields
I have a django form with multiple fields and I need to validate the form..reading this tutorial https://developer.mozilla.org/en-US/docs/Learn/Server-side/Django/Forms it works with one field but not work in my case. My forms.py: class mopa(forms.Form): idcarrellosorgente = forms.IntegerField(label="Identificativo Carrello Sorgente *", required=True, max_value=9999999999, min_value=0000000000 ) causale = forms.CharField(label="Causale Pagamento *", required=True) imp_unitario = forms.DecimalField(label="Importo Unitario Bene (es. 20.00) *", required=True) quantita_item = forms.IntegerField(label="Quantita' Bene Acquistato (intero) *", required=True) my views.py: def paga(request): # If this is a POST request then process the Form data if request.method == 'POST': # Create a form instance and populate it with data from the request (binding): form = mopa(request.POST) print('form: ', form.data) #return a dictionary # Check if the form is valid: if form.is_valid(): # process the data in form.cleaned_data as required idcarr = form.cleaned_data['idcarrellosorgente'] caus = form.cleaned_data['causale'] imp_u = form.cleaned_data['imp_unitario'] qta = form.cleaned_data['quantita_item'] dictmopa={} dictmopa['id_carr']=idcarr dictmopa['ente']=cod_ente dictmopa.save() # redirect to a new URL: return HttpResponseRedirect(reverse('viewsdati/') ) # If this is a GET (or any other method) create the default form. else: form = mopa() return render(request, 'paga.html', {'form': form}) and my template: <div class> <form action="" method="post"> {% csrf_token %} <table> {{ form }} </table> <input type="submit" value="Submit" /> </form> </div> So, how can I … -
Add and remove rows from a formset within a form
I have a Django formset within a form that is build using django-crispy-forms and bootstrap 4.0.0-alpha.6. It looks like so: {% block content %} <div> <h1 class="text-center">Create New Activity</h1> <div class="row"> <div class="col"></div> <div class="col-md-8 col-lg-8"> <form role="form" method="post"> {% csrf_token %} {{ form|crispy }} {{ activitykeycharacteristics_formset|crispy }} <hr> <button class="primaryAction btn btn-primary pull-right ml-1" type="submit">{% trans "Submit" %}</button> <a class="btn btn-secondary pull-right" href="{{ request.META.HTTP_REFERER }}" role="button">{% trans "Cancel" %}</a> </form> </div> <div class="col"></div> </div> </div> {% endblock content %} What I have been trying to do is include add and delete buttons so that I can add or delete forms from the formset. At the moment it renders with one form in the formset and so only an add button should be seen, but once there is more than one a delete button should also be seen. I'm pretty sure the best way to do this is to use jQuery to add and remove the forms but I haven't been able to get this to work properly. I thought that I had the add button working using Dave's answer in this SO question. But I couldn't get it to correctly update the indices of the inputs. I couldn't get … -
Django round to 2 decimal places if there are decimals else round to no decimal places
please can you point me in the right direction. Given the number 1.555, I want the result 1.56 Given 1.500, I want 1.5 Given 1,000 I want 1 Are there any existing filters that can do this? I know that I can write my own, I'll do that if there isn't a built solution already. -
Update three-level nested django model using serializer
I am trying to update one of my models (which is a nested model - three level actually as you can see below) and I am getting the following error: AssertionError: The .update() method does not support writable nestedfields by default. Write an explicit .update() method for serializer SystemSettingsSerializer, or set read_only=True on nested serializer fields. All day I have been reading about nested models and nested serializers, trying to add update and create methods setting fields as read_only=True but no matter what I did, it just didn't work :( :( These are my models: class SystemSettings(models.Model): # ... some fields class Components(models.Model): settings = models.ForeignKey(SystemSettings, related_name="Components") class SysComponent(models.Model): class Meta: abstarct = True index = models.PositiveIntegerField(primery_key=True) is_active = models.BooleanField(default=False) component = NotImplemented class Foo(SysComponent): component = models.ForeignKey(Components, related_name="Foo") class Bar(SysComponent): component = models.ForeignKey(Components, related_name="Bar") task_id = models.PositiveIntegerField(default=0) and serializers: class SystemSettingsSerializer(ModelSerializer): Components = ComponentsSerializer(many=True) class Meta: model = SystemSettings fields = [# some fields, Components] class ComponentsSerializer(ModelSerializer): Foo = FooSerializer(many=True) Bar = BarSerializer(many=True) class Meta: model = Components fields = ['Foo', 'Bar'] class FooSerializer(ModelSerializer): class Meta: model = Foo class BarSerializer(ModelSerializer): class Meta: model = Bar My logic is the following: I am fetching the SystemSettings via GET and … -
Wagtail document links downloading instead of displaying as a page
It seems that the default configuration for Wagtail CMS is to have links to documents trigger an automatic download of the document instead of displaying the document in the browser. Is there a simple way to change this configuration? -
Optimizing a Django `.exists()` query
I have a .exists() query in an app I am writing. I want to optimize it. The current ORM expression yields SQL that looks like this: SELECT DISTINCT (1) AS "a", "the_model"."id", ... snip every single column on the_model FROM "the_model" WHERE ( ...snip criteria... LIMIT 1 The explain plan looks like this: Limit (cost=176.60..176.63 rows=1 width=223) -> Unique (cost=176.60..177.40 rows=29 width=223) -> Sort (cost=176.60..176.67 rows=29 width=223) Sort Key: id, ...SNIP... -> Index Scan using ...SNIP... on ...SNIP... (cost=0.43..175.89 rows=29 width=223) Index Cond: (user_id = 6) Filter: ...SNIP... If I manually modify the above SQL and remove the individual table columns so it looks like this: SELECT DISTINCT (1) AS "a", FROM "the_model" WHERE ( ...snip criteria... LIMIT 1 the explain plan shows a couple fewer steps, which is great. Limit (cost=0.43..175.89 rows=1 width=4) -> Unique (cost=0.43..175.89 rows=1 width=4) -> Index Scan using ...SNIP... on ...SNIP... (cost=0.43..175.89 rows=29 width=4) Index Cond: (user_id = 6) Filter: ...SNIP... I can go further by removing the DISTINCT keyword from the query, thus yielding an even shallower execution plan, although the cost saving here is minor: Limit (cost=0.43..6.48 rows=1 width=4) -> Index Scan using ..SNIP... on ..SNIP... (cost=0.43..175.89 rows=29 width=4) Index Cond: (user_id = … -
How to store datetime and input timezone offset in Django
I have a Django model with a timestamp field and need to store the timestamp including the timezone offset. The model data is stored in a PostgreSQL database and the offset is lost when retrieving it from the database (because PostgreSQL stores all timestamps in UTC). To achieve this I have added a field to the model that stores the offset (in minutes) and a property that combines the timestamp and offset when reading / extracts the offset from the timestamp when writing: from django.db import models class FooModel(models.Model): client_timestamp = models.DateTimeField() client_utc_offset = models.IntegerField(default=0) @property def client_timestamp_with_offset(self): return timezone.localtime(self.client_timestamp, timezone.get_fixed_timezone(self.client_utc_offset)) @client_timestamp_with_offset.setter def client_timestamp_with_offset(self, value): self.client_timestamp = value self.client_utc_offset = value.tzinfo.utcoffset(value).total_seconds() // 60 This works, but is not ideal. For instance, it's not possible to use this property when creating an instance directly i.e.: FooModel.objects.create(client_timestamp_with_offset=...) doesnt work. It's also not possible to use this property in forms/Django's admin. So I'm looking for a better solution. I've been looking into custom fields/descriptors, but I'm not sure how to use those tools to do it properly. -
JSONField serializes as json for POST, but string for GET
There is likely a very simple problem with my code, but I've been slamming my head against this problem for a couple days and can't make any headway. Important Packages: Django==1.11.3 django-cors-headers==2.1.0 djangorestframework==3.7.0 drf-nested-routers==0.90.0 psycopg2==2.7.3 pycparser==2.18 Here is what is happening: I create a model via an AJAX call My server correctly serializes the brainstorm_data field as a json object. Now I navigate my user to the next page and fetch the current model For some reason, brainstorm_data is now be returned as a string. Anytime I call a GET request on this resource I always get a string representation of the JSON object. Here is the code associated: models.py from django.contrib.postgres.fields import JSONField class Adventure(TimeStampedModel, models.Model): name = models.CharField(max_length=200) user = models.ForeignKey(User) world = models.ForeignKey(World) theme = models.ForeignKey(Theme, default=1) brainstorm_data = JSONField() image_src = models.CharField(max_length=400, null=True, blank=True) sentence_summary = models.TextField(null=True, blank=True) paragraph_summary = models.TextField(null=True, blank=True) page_summary = models.TextField(null=True, blank=True) outline_complete = models.BooleanField(default=False) brainstorm_complete = models.BooleanField(default=False) private = models.BooleanField(default=False) def __str__(self): return self.name views.py class MyAdventuresViewSet(viewsets.ModelViewSet): queryset = Adventure.objects.all() serializer_class = AdventureSerializer permission_classes = (permissions.IsAuthenticated,) def get_queryset(self): return Adventure.objects.filter(user=self.request.user) def create(self, request, *args, **kwargs): user = self.request.user world = World.objects.filter(user=user).first() if not world: world = World.objects.create(name='My World', user=user, description="This is … -
In Django, how do I save a file that has been uploaded in memory as an email attachment?
I am building an email gateway for our clients and need to be able to attach the files they upload to the email. I am using EmailMultiAlternatives to send the email and a FileField for the upload. The problem happens when I try to connect the two. I have the following logic in my view. if request.method == 'POST': form = MyForm(request.POST, request.FILES) if form.is_valid(): ... email = EmailMultiAlternatives(...) email.attach(request.FILES['image']) else: form = MyForm() This results in "No exception message supplied" and the following values in debug: content: None filename: <InMemoryUploadedFile: ImageFile.png (image/png)> mimetype: None So it looks like for some reason, there is no file content. Not sure what's going on here. Examples in the docs save the file to a model, but there is no model to save the file to here. Ideally, I would just like to pass the file content directly to the attach method and send it on. Any ideas on how to make this work? -
values show up correctly in view, but not template
I have the following view, which shows up correctly in the print report details: def profile(request): owner = User.objects.get (formattedusername='request.user.formattedusername') reportdetail = QVReportAccess.objects.filter(ntname = owner.formattedusername).values('report_name') print(reportdetail) args = {'user':owner, 'applicationaccess':reportdetail} return render(request, 'accounts/profile.html', args) However, it's not getting passed to my template correctly. I'm new to Django so I'm going to assume there is something wrong the part of my template passing the report name. <h2>Current Access Application List</h2> <ul> {{reportdetail.report_name}} <li>Application Name: {% for app in reportdetail %} <input type="checkbox" name="report_name" value="{{ app.report_name }}" /> {{ reportdetail.report_name }}<br /> {% endfor %} </li> </ul> -
Django delete records missing after syncing
I have a Django table that syncs data with a external API. When data is added / updated there is no problem with the sync but how can I detect data has been deleted and remove it from the Django table. For the record during each sync I am dealing with a lot of data. -
Unable to display user input in django
I am new to Django and trying to display user input text. I tried multiple things but nothing has worked so far. Advice/help needed! Here are my files: models.py from django.db import models class Post(models.Model): message = models.TextField(max_length=4000) def __unicode__(self): return self.title views.py from .models import Post from django.core.exceptions import * def index(request): return render('index.html') def result(request): p = request.POST['message'] return render_to_response('result.html', {'message': p}, context_instance=RequestContext(request)) index.html <!DOCTYPE html> <head> <title>Index page</title> </head> <body> <div id="header">Welcome to index page</div> <div id="content"> <p>Enter your name</p> <form action="/polls/results.html/" method="post" accept-charset="utf-8">{% csrf_token %} <input type="text" name="message"> <input type="submit" value="Send!"> </form> </div> </body> results.html <!DOCTYPE html> <head> <title>Result page</title> </head> <body> <div id="header">Here is the result</div> <div id="content"> <p>Your name is: {{ message }}</p> </div> </body> url.py from django.conf.urls import include, url from django.conf.urls.static import static from . import views app_name = 'polls' urlpatterns = [ url(r'^$', views.result, name='results'), ] -
How to setup a remote database only server for my django application
I am planning to separate my SQL database from my Django application server by implementing a remote database server. I also want to create a backup server of the primary database server. I would like to sync my backup database with the primary database when some data is changed in the primary database. So here are my questions. How can I connect my remote database server to my Django application server and also how can I sync my primary and backup database servers.? I'm thinking if there is any way to interconnect Django application server, database server, backup database server via private IP's and block any requests to the database servers via Public IP to avoid potential threats. I tried to connect my remote database by changing database HOST to my private IP and PORT to '3306' in my Django settings file and I'm stuck with django.db.utils.OperationalError: Can't connect to MySQL server I am using amazon-ec2 ubuntu 16.04 for all my servers -
Django, using the same view depending on if its a GET or an AJAX POST method
So I am using the same view in Django to do two things, depending on if the request is a GET or a POST method. The GET method is simply to render the page when the user requests it, and the POST is when I use ajax to send information from the frontend, to the view so that i can process it and save it in the database. Here is the Javascript/Ajax: var url = window.location.pathname; $.ajax({ url: url, data: { 'vals': vals }, dataType: 'json', success: function (data) { //On sunccess } }); The window.location.pathname contains the review_id in it and looks like: /reviews/*ID*/add_questions/ This is my Django View: def add_questions(request, review_id = None): #print('yes') if request.method == 'GET': try: review = ReviewBlock.objects.get(pk = review_id) args = {'review': review} return render(request, 'add_questions.html', args) except ObjectDoesNotExist: return HttpResponseNotFound('<h1>Page not found</h1>') elif request.method == 'POST': print(review_id) As you can see, I have a print statement to see if the ajax call is working, however, it never prints it in the console.