Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I make a calculation appear from models in my HTML template?
hello I am trying to do a multiplication in Django from models multiplying the quantity by the unit_price and reflecting the result in total_price) but I see that it is not reflected in my HTML template (I have some inputs and in the input where I want to reflect the result of the multiplication, it does not appear), does anyone know what is missing for me? [![Here neither the input of total_price appears][1]][1] I should also mention that it is a form and a formset to which I want to apply that models.py class Parte(models.Model): codigo=models.IntegerField() quantity=models.IntegerField() unit_price=models.IntegerField() total_price=models.IntegerField() tax_free=models.BooleanField() descripcion=models.CharField(max_length=255,blank=True, null=True) descuento=models.IntegerField() total=models.IntegerField() @property def total_prices(self): return self.quantity*self.unit_price def __str__(self): return f'{self.codigo}: {self.descripcion} {self.quantity} {self.unit_price} {self.total_prices} {self.tax_free}{self.descuento}{self.total}' presupuestos-forms.html <table class="table table-bordered table-nowrap align-middle"> <thead class="table-info"> <tr> <th scope="col">Código</th> <th scope="col">Descripción</th> <th scope="col">Cantidad</th> <th scope="col">Precio Unitario</th> <th scope="col">Precio Total</th> <th scope="col">Libre de Impuestos</th> <th scope="col">Agrega Fila</th> </tr> </thead> <tbody> <tr> <td> {{presupuestosparteform.codigo}} </td> <td> {{presupuestosparteform.descripcion}} </td> <td> {{presupuestosparteform.quantity}} </td> <td> {{presupuestosparteform.unit_price}} </td> <td> {{presupuestosparteform.total_prices}} </td> <td> <div> {{presupuestosparteform.tax_free}} </div> </td> <td> <input type="button" class="btn btn-block btn-default" id="add_more" value="+" /> </td> </tr> {{ formset.management_form }} {% for form in formset %} <tr id="formset" class="form-row"> <td> {% render_field form.codigo class="form-control" %} </td> … -
Ajax call to update sort criteria of product list in a Django template
I'm trying to make an Ajax call to update the sort criteria of a product list that is being displayed on the store page, depending on the drop-down option. The store page template extends from the main template. However, the sort isn't working. I took the liberty of removing all views that are not relevant to the question, except the store page view which is receiving the ajax call. I am wondering if there is a conflict issue since the store page is also receiving the cart total from the front end via the CartData function. Any insight would be helpful. main.html <!DOCTYPE html> {% load static %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width,initial-scale=1,maximum-scale=1,minimum-scale=1"/> <title>MyShop</title> {# Bootstrap stylesheet#} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css"> {# Custom CSS#} <link rel="stylesheet" href="{% static 'css/ecomsite.css' %}"> {# Google Fonts import#} <link rel="preconnect" href="https://fonts.googleapis.com"> <link rel="preconnect" href="https://fonts.gstatic.com" crossorigin> <link href="https://fonts.googleapis.com/css2?family=Roboto:wght@300&display=swap" rel="stylesheet"> <script type="text/javascript"> var user = '{{request.user}}' /* getToken function creates a CSRF token so that the cart.js script can communicate with the updateItem view */ function getToken(name) { var cookieValue = null; if (document.cookie && document.cookie !== '') { var cookies = document.cookie.split(';'); for (var i = 0; … -
How to perform multiple saving in django?
Am about to perform 3 saves in django, am worried about race condition and also confused to know if its the correct way to do it ! Here is my code: process.user = user process.save() user.is_updated = True user.save() actions = Actions(owner=user, action="Personal") actions.save() Am doing all this in a view function, is this a right way to do it ? Or should i use @transaction.atomic or please suggest which is a good method ? -
Django ImageField not uploading on form submit but not generating any errors
I have a simple app that uses an ImageField to upload & store a photo. I'm running the app local. The form displays as expected, and allows me to browse and select a jpg file. It then shows the selected filename next to the "Choose File" button as expected. When I submit the form, it saves the model fields 'name' and updates 'keywords' but it does not save the file or add the filename to the db. No errors are generated. Browsing the db, I see the newly added record, but the 'photo' column is empty. Any help appreciated. settings.py: MEDIA_ROOT = '/Users/charlesmays/dev/ents/ents/enrich/' models.py: class Enrichment(models.Model): name = models.CharField( max_length=255, unique=True) keywords = models.ManyToManyField(KeyWord, blank=True) photo = models.ImageField(upload_to='enrichments/', null=True, blank=True) views.py: def EnrichmentUploadView(request): if request.method == 'POST': form = CreateEnrichmentForm(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('index')) else: return render(request, 'createEnrichment.html', {'form':form}) else: form = CreateEnrichmentForm() return render(request, 'createEnrichment.html', {'form':form}) forms.py: class CreateEnrichmentForm(forms.ModelForm): class Meta: model = Enrichment fields = ('name', 'photo', 'keywords') enctype="multipart/form-data" -
django queryset with __date returns Nones
I have a django queryset where I want to group by created_at date value (created_at is a datetime field). (Activity.objects .values('created_at__date') .annotate(count=Count('id')) .values('created_at__date', 'count') ) I am following the accepted answer here which makes sense. However, the query returns None for all created_at__date values. When I change it to created_at it shows the actual value. The generated SQL query: SELECT django_datetime_cast_date("activity"."created_at", 'UTC', 'UTC'), COUNT("activity"."id") AS "count" FROM "activity" GROUP BY django_datetime_cast_date("activity"."created_at", 'UTC', 'UTC') -
How to setup User and (maybe) UserCreationForm model in Django?
Need help or resources for Django models. Hello, I am trying to modify/extend the django.contrib.auth.models.User class so it could register a few more fields, apart from username and password. For now I have implemented the User class only as a foreign key in another Task class. from django.db import models from django.contrib.auth.models import User # Create your models here. class Task(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True, blank=True) # cascade deletes all tasks/items when user is deleted title = models.CharField(max_length=200) description = models.TextField(null=True, blank=True) complete = models.BooleanField(default=False) created = models.DateTimeField(auto_now_add=True) def __str__(self) : return self.title class Meta: ordering = ['complete'] What I tried: I've tried making it a One-to-One relation with a Employee class, but things got a little messy, as I was required to first register the user, and then later add attributes to the Employee as well as selecting the (already created) User as a primary key. That was not practical I suppose. So my question is: What is the best way to add attributes like Email, ID number, First name, Last name, etc in the User class and how to implement/render the appropriate form in the views.py? Here is my views file: from django.contrib.auth.mixins import LoginRequiredMixin # settings.py … -
Import packages from outside django project
Context: The package being considered is an application that was developed by another team and I want to use the functionality exposed as part of an API call in my django project. Directory layout: <repo> ├── org_wide_django_code │ ├── my_django_project │ │ ├── my_django_project │ │ ├── manage.py │ │ ├── requirements.txt │ │ └── my_application ├── frontend │ └── application ├── other_team_work │ ├── README.md │ ├── __init__.py │ ├── implemented_logic What is the best way for me to use other_team_work in my django project my_django_project? Prior reading: Manipulating PYTHONPATH or sys.path is an option Setting up a .whl or .egg to install other_team_work (also need to add a setup.py there) -
click table row redirect to website showing django db entry
I have a django project (form) with a database to save customer data. In URL_1 of my projects the most important db entries are shown as a table. Each row contains one customer and the columns list the relevant information. It delivers a brief overview of a database entry per row. The other URL_2 contains a search bar with a POST request. You can enter the ID of your database entry and you will see the full information for a customer on the whole page. Now I want to CLICK on the table in URL_1 and would like to land in URL_2, but already "pre-entered" the id of the customer to the search bar, so the information is shown. Now the code. This generates my "overview" table in URL_1: {% for snippet in snippets %} <tr data-href="form2"> <td id="rowid">{{snippet.id}}</td> <td>{{snippet.Titel_Person}} {{snippet.Vorname}} {{snippet.Nachname}}</td> <td>{{snippet.Kennzeichen}}</td> <td>{{snippet.Titel_Anwalt}} {{snippet.Anwalt_vorname}} {{snippet.Anwalt_nachname}}</td> <td>{{snippet.Anwalt_Straße}} {{snippet.Anwalt_ort}}</td> <td>{{snippet.Fahrzeug}}</td> <td>{{snippet.Geschlecht}}</td> <td>{{snippet.Tattag}}</td> </tr> {% endfor %} With this command I call the database entries to view in the URL_2: <form action = "{% url 'ga_form' %}" method = "POST" autocomplete="off"> {% csrf_token %} <input type="search" name="id_row" placeholder="Gutachten suchen" required> <button type="submit" name="id_row_btn" >Suchen</button> </form> which call this view method: def ga_form(request): … -
First django rest api call returns request.user as AnonymousUser but further calls return proper user
right now I have an api view that requires knowing which user is currently logged in. When I try to call it with a logged in user; however, it returns anonymous user. The odd thing is that if I call the api view again, it returns the proper user. I am using django rest framework and JSON Web Tokens with simplejwt. Right now the call in ReactJS looks like this: const fetchAuthorData = () => { axiosInstance.get('authors/') .then((res) => { setAuthor(res.data) }).catch((err) => { fetchAuthorData() }) fetchAuthorThreads() fetchAuthorArticles() } However, I know recursively calling this over and over is very dangerous, because even though I redirect if the user is actually not logged in before this recursive api call, if somehow that fails my server will be overloaded with api calls. Does anyone know how I could make it so that my api actually properly identifies on the first call whether the user is logged in? Here is the faulty view: @api_view(['GET']) def author(request): print(request.user) if request.user.is_authenticated: author = request.user serializer = AuthorAccessSerializer(author, many=False) return Response(serializer.data) else: return HttpResponse(status=400) In this, request.user is an anonymous user even though I am logged in Here is a similar part of another view … -
How to integrate a validator between python class and restful api?
I'm supposed to have a validator between my calculator and a rest-api that uses set calculator. My calculator is a python class as follows: class Calculator: reduced_tax = 7 standard_tax = 19 @staticmethod def calculate_reduced_tax(price): price_float = float(price) calculated_tax = price_float + ((price_float/100) * Calculator.reduced_tax) return calculated_tax @staticmethod def calculate_standard_tax(price): price_float = float(price) calculated_tax = price_float + ((price_float/100) * Calculator.standard_tax) return calculated_tax My (hopefully) restful api looks like this: from django.http import HttpResponse from calculator.calculator import Calculator from calculator.validator import validate_number import json def get_standard_tax(request, price): if request.method == 'GET': try: validated_input = validate_number(price) calculated_tax = Calculator.calculate_standard_tax(validated_input) response = json.dumps([{'price': price, 'with_standard_tax': calculated_tax}]) except: response = json.dumps({'Error': 'Could not calculate standard tax'}) return HttpResponse(response, content_type='text/json') def get_reduced_tax(request, price): if request.method == 'GET': try: validated_input = validate_number(price) calculated_tax = Calculator.calculate_reduced_tax(validated_input) response = json.dumps([{'price': price, 'with_reduced_tax': calculated_tax}]) except: response = json.dumps({'Error': 'Could not calculate standard tax'}) return HttpResponse(response, content_type='text/json') I tried to implement a validator as follows trying to throw a ValidationError from the django framework since my project overall uses Django: from django.core.exceptions import ValidationError from django.utils.translation import gettext_lazy as _ def validate_number(value): if not float(value): print('a validation error should be thrown') raise ValidationError( _('%(value)s is not an number'), params={'value': value} … -
Dynamic modal content - youtube?
I have a daft question. I have a load of data coming in from a Django view - it has a column which includes a YouTube URL. At the moment, I loop through the skills & create a modal for each. Then when you click on the item, it opens the corresponding modal. However, when you have 100 items, this is a bit of a silly approach Does anyone know a better way to do it? I still want the videos embedded in a modal - but the video should be dynamically set, based on the chosen item. Thank you!! {% for skill in skill_list %} <div class="modal fade" id="{{ skill.skill_id }}" tabindex="-1" role="dialog" aria-hidden="true"> <div class="modal-dialog modal-semi-full modal-dialog-centered"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title">{{ skill.skill_name }}</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <iframe width="100%" height="100%" src="https://www.youtube.com/embed/{{skill.syllabus}}" title="YouTube video player" frameborder="0" allow="accelerometer; autoplay; clipboard-write; encrypted-media; gyroscope; picture-in-picture" allowfullscreen></iframe> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> </div> </div> </div> </div> -
Django-q multiple clusters and tasks routing
Is it possible to have two clusters and route tasks between them? I suppose I can run two clusters using different settings files, but how to route tasks in that case? -
AttributeError: 'NoneType' object has no attribute 'lower'; password validation
When registering a User, the desired user password is checked against a list of disallowed passwords. Yet when the password is passed to a validator method, the following error is raised: AttributeError: 'NoneType' object has no attribute 'lower' Why is the validate() method being invoked as is if password is None when in fact it is truthy? from django.contrib.auth.models import User from django.contrib.auth.password_validation import ( validate_password, CommonPasswordValidator, NumericPasswordValidator ) from rest_framework import serializers class LoginSerializer(UsernameSerializer): password = serializers.RegexField( r"[0-9A-Za-z]+", min_length=5, max_length=8 ) def validate(self, data): username = data['username'] password = data['password'] try: validate_password(password, password_validators=[ CommonPasswordValidator, NumericPasswordValidator ]) except serializers.ValidationError: if username == password: pass raise serializers.ValidationError("Invalid password") else: return data class Meta: fields = ['username', 'password'] model = User -> for validator in password_validators: (Pdb) n > \auth\password_validation.py(46)validate_password() -> try: (Pdb) n > \auth\password_validation.py(47)validate_password() -> validator.validate(password, user) (Pdb) password 'Bingo' (Pdb) user (Pdb) password 'Bingo' (Pdb) s --Call-- > \auth\password_validation.py(180)validate() -> def validate(self, password, user=None): (Pdb) password (Pdb) n > \django\contrib\auth\password_validation.py(181)validate() -> if password.lower().strip() in self.passwords: (Pdb) n AttributeError: 'NoneType' object has no attribute 'lower' -
PyTube files are in root directory not in Downloads path from user
I'm coding an video converter and everything works as expected on my localhost but now on the server my converted video gets saved in the root dir from my server and not in the Downloads path from the user. This is my code: if format == "3": messages.info(request, 'The MP3 was downloaded successfully!') yt = YouTube(link) downloads = str(os.path.join(Path.home(), "Downloads")) audio_file = yt.streams.filter(only_audio=True).first().download(downloads) base, ext = os.path.splitext(audio_file) new_file = base + uuid + '.mp3' os.rename(audio_file, new_file) elif format == "4": messages.info(request, 'The MP4 was downloaded successfully!') yt = YouTube(link) downloads = str(os.path.join(Path.home(), "Downloads")) ys = yt.streams.filter(file_extension='mp4').first().download(downloads) username = request.user.username context = {'format': format, 'username': username} return render(request, 'home/videoconverter.html', context) the parameter next to .download is the path, as I already said on my localhost everything worked. So I need a way to save files in the users download dir with server. -
Reverse not working with kwargs while working in another function - why?
def test_no_errors_direct_flights_rendered_in_template(self): request = HttpRequest() response = render(request,'app1/flight-search-result.html', { 'direct_flights': [ { ---- not relevant }) self.assertContains(response, 'Direct connection') self.assertNotContains(response, 'No options for your search') self.assertNotContains(response, 'One change') # this assertContains will ensure that the searched word is not in the form - we don't pass # the form to the render function above self.assertContains(response, 'Venice Airport Marco Polo') self.assertContains(response, 'Dubai International Airport') # you can add more once you change the template url = reverse('app1:flight-search-detail-passenger-form', kwargs={'to_first': "VCEDXB2201040"}) ---- works! self.assertContains(response, '<a href="{}">'.format(url)) def test_no_errors_indirect_flights_rendered_in_template(self): request = HttpRequest() response = render(request, 'app1/flight-search-detail-passenger-form.html', { 'indirect_flights': [ { ----- not relevant { } ] } ] }) self.assertContains(response, 'One change') self.assertNotContains(response, 'No options for your search') self.assertNotContains(response, 'Direct flight') # you can add more once you change the template kwargs = {'to_first': "VCEDXB2201040"} _url = reverse('app1:flight-search-detail-passenger-form', kwargs=kwargs)------- doesn't work! self.assertContains(response, '<a href="{}">'.format(_url)) A very weird problem, but the first reverse works perfectly well while the second one throws the following error: django.urls.exceptions.NoReverseMatch: Reverse for 'flight-search-detail-passenger-form' with arguments '('',)' not found. 2 pattern(s) tried: ['flights/detail/passenger/to=(?P<to_first>[ A-Z0-9]{13})&(?P<to_second>[A-Z0-9]{13})$', 'flights/detail/passenger/to=(?P<to_first>[A-Z0-9]{13})$'] Has someone encountered it before? How can I solve it? -
How to deploy django(back) and react(front) servers on nginx on ubuntu?
I have to to deploy web-server(django and react) on nginx server. I already have working projects, they weigh about a 2 gigabyte, there are a lot of libraries. Do I need to save them? I can't imagine how to do it in most simple way. There are information doing it using docker. Is it a common way to do it? Can you explain me how exactly a true way to do this deploying, please. -
How to send stream data using just python?
I am currently learning NodeJS and I learned a really neat way of sending big files, using streams, I already have a bit of an experience with Django but how can I do the following in Django (or python) const http = require('http') const fs = require('fs') const server = http.createServer((req, res)=>{ const fileContent = fs.createReadStream('./content/bigFile.txt', 'utf8') fileContent.on('open', ()=>{ fileContent.pipe(res) }) fileContent.on('error',(err)=>res.end(err) ) }) server.listen(5000) -
Limit amount of foreign keys in clean method Django
I'm not trying to limit amount of foreign keys on Forms or views, I'm trying to make it through the clean method on the models.py. I tried to find something about it but the thing is that when you save a model with a foreign key, the clean method don't get the new related object becouse, first, it saves the model args and then the foreign keys, so when you try to add somethings like this: class RelatedModel(models.Model): fields... def clean(self) -> None: from django.core.exceptions import ValidationError limit = 5 if self.related_name: if self.related_name.count() > limit: raise ValidationError(f"The limit of related objects is { limit }") return super().clean() class Model(models.Model): related_model = models.ForeignKey(RelatedModel, related_name="related_name") The count() is not the real one, becouse you just get an instance of the model with the previous related_models, but not with the new ones, so the you can't limit the amount like that. ¿Is there any way to achieve this? -
django: when to derive directly from View class in CBVs
I am using django 3.2. I am building a commenting system that allows users to post comments (without using a form). It is not clear from the documentation whether I should do this: class AddComment(MyMixin, View): post(request, *args, **kwargs): pass OR class AddComment(MyMixin, CreateView): post(request, *args, **kwargs): # No form .. so just deal with passed in args pass Which is the canonical way to do this? (citations please) -
From python to django [closed]
What are the Python topics that one should focus on to master and understand django? am done with the basics of python but just wanna know before moving to django. -
Queryset with collated/merged values
Let's say I have the following two models: class Parent(models.Model): name = models.CharField(max_length=48) class Child(models.Model): name = models.CharField(max_length=48) movement = models.ForeignKey(Parent, related_name='children') And I have the following DRF generics.ListAPIView where I want to be able to search/filter on Child objects but actually return the related Parent objects: class ParentSearchByChildNameView(generics.ListAPIView): """ Return a list of parents who have a child with the given name """ serializer_class = ParentSerializer def get_queryset(self): child_name = self.request.query_params.get('name') queryset = Child.objects.all() if child_name is not None: queryset = queryset.filter(name__contains=child_name) matched_parents = Parent.objects.filter(children__in=queryset).distinct() return matched_parents Now, this works well for me. If a Parent object has 3 Child objects which all match the given "name" query_param, then I only get one Parent object back, which is what I want: { "next": null, "previous": null, "results": [ { "url": "URL to parent", "name": "Parent #1", } ] } However, what I also want is to indicate the matched Child object IDs within the result. If I may illustrate in JSON what I want: { "next": null, "previous": null, "results": [ { "url": "URL to parent", "name": "Parent #1", "matched_child": [1, 3, 7] } ] } Is this something I can do with built-in tools, without expensively and repeatedly … -
Customizing UserChangeForm in django
I want to delete 'groups' field from build-in UserChangeForm and add own "Role' field. How to handle that? I created my class which inherits from UserChangeForm and went to somehow delete but no change. class CustomUserChangeForm(UserChangeForm): def __init__(self, *args, **kwargs): super(CustomUserChangeForm, self).__init__(*args, **kwargs) self.exclude = ('groups',) -
Why does my column appear below my row rather than to the right?
I have a webpage at the moment with 3 cards on it which I am going to use as contact cards. To the right of that in a seperate column I want to have some text but for some reason, the text always appears directly below the cards as below. My desired outcome is to have the test text appear to the right of the cards. The html is currently formatted like this: {% extends 'base.html' %} {% block content %} <br> <div class="container"> <div class = "row-sm-1"> <div class ="col-sm-1"> <!-- Card 1 --> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Person</h5> <p class="card-text">Description</p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item">Email: </li> <li class="list-group-item">Phone: </li> </ul> </div> <br><br> <!-- Card 2 --> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Person</h5> <p class="card-text">Description</p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item">Email: </li> <li class="list-group-item">Phone: </li> </ul> </div> <br><br> <!-- Card 3 --> <div class="card" style="width: 18rem;"> <div class="card-body"> <h5 class="card-title">Person</h5> <p class="card-text">Description</p> </div> <ul class="list-group list-group-flush"> <li class="list-group-item">Email: </li> <li class="list-group-item">Phone: </li> </ul> </div> <br><br> </div> <!-- Second Column --> <div class = "col-sm-2"> <h1>Test</h1> </div> </div> </div> <br><br><br> {% endblock %} Where base.html contains just basic tags like head, body, etc. This … -
Django ORM complex order_by (with CASE and WHEN by related model), DISTINCT lefting duplicates
What am i trying to do - is to create ajax datatable with serverside processing, where in first column will be keyword_name (main model), and in all others - positions ranks (related model), with ability to sort data by any column, apply search and filters. The table looks like: | Keyword_name | Position created 01.01.21, Google search engine, New-York Region | Position created 03.01.21, Yahoo Search engine, New-York Region | blablabla, all types of positions by dates,engines,regions | | |--------------|------------------------------------------------------------|---------------------------------------------------------|------------------------------------------------------------|---| | keyword 1 | rank:1 | Rank:3 | etc | | | keyword 2 | rank:5 | Rank:1 | etc | | | etc.. | | | | | My models are: class Keyword(): """Main model""" project = models.ForeignKey(Project, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) name = models.CharField(max_length=1000) <-----> created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) class Position(): """Model for keep keywords positions""" keyword = models.ForeignKey(Keyword, on_delete=models.CASCADE) engine = models.ForeignKey(SearchEngine, on_delete=models.CASCADE) region = models.ForeignKey(Region, on_delete=models.CASCADE) rank = models.IntegerField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now_add=True) So, i dont have problem with filtering positions (getting data with simple Keyword.objects.filter("position__created_at__date_gte" = 01.01.21, "position__created_at__date_lte" = 01.02.21 etc), but the problem is when i`m trying to sort data by columns - i want to click to column … -
Connecting Django to AWS MySQL Database
I am having an issue allowing my Django project connect to my AWS MySQL RDS instance. I keep getting the error: RuntimeWarning: Got an error checking a consistent migration history performed for database connection 'default': (2005, "Unknown MySQL server host 'cropdrone.cp1xd7eoed6m.us-east-2.rds.amazonaws.com' (11001)") So then nothing happens. I deleted all my security groups and opened all IPv4 and v6 ports to the database. I tried doing an EC2 method but that was all local. The goal is for me to make a website that uses this database then can pull images and GPS coordinates a partner of mine uploads to the database. Here is my settings.py image displaying the database connection I have set up. Here is another question I have been asking myself and would like to know from anyone willing to help. Should I scratch the MySQL option and do PostgreSQL? I see many many many tutorials showing how to connect Django to it and I'm so at a loss I'm willing to change databases. I don't have data stored in my instance yet so it won't be much of a change anyway.