Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to return the values of functions called with yield in a ContextManager - Python
I am trying to organize my code by removing a lot of repetitive logic. I felt like this would be a great use case for a context manager. When making certain updates in the system, 4 things always happen - We lock the resource to prevent concurrent updates We wrap our logic in a database transaction We validate the data making sure the update is permissible After the function executes we add history rows to the database I want a wrapper to encapsulate this like below from contextlib import contextmanager @contextmanager def my_manager(resource_id): try: with lock(resource_id), transaction.atomic(): validate_data(resource_id) resources = yield create_history_objects(resources) except LockError: raise CustomError def update(resource_id): with my_manager(resource_id): _update(resource_id) def _update(resource_id): # do something return resource Everything works as expected except my ability to access resources in the contextmanager, which are None. The resources are returned from the function that's called during the yield statement. What is the proper way to access those resources through yield or maybe another utility? Thanks -
When using Generics types, how can I call an Attribute of an inherited class on the Base class instance with Python / Django?
Let's say I have a base Generic class called person to group all other persons that extend it: class Person(models.Model): name = models.CharField(...) And the class Worker, that extends the Person: class Worker(Person): card_id = models.CharField(...) When I access all Person objects I also see the Workers, but lets say that from there I want to do this: worker = Worker(name='Example', card_id='1234') person = Person.objects.all().first() Let's say that for some reason I want to use the Person class and call an Attribute o Worker: [in] person.card_id # Somehow expecting this result: [out] '1234 Is it possible, is it viable and how do I do it? -
How to write below sql query using Django queryset?
I have tried many solutions but could not find any luck, and also is django queryset faster than the raw sql join queries? Models - class S2BotCategoriesMappings(models.Model): id = models.IntegerField(primary_key=True) id_s2_bot = models.ForeignKey(S2Bot, models.DO_NOTHING, db_column='id_s2_bot', blank=True, null=True) id_s2_bot_categories = models.ForeignKey(S2BotCategories, models.DO_NOTHING, db_column='id_s2_bot_categories', blank=True, null=True) class Meta: managed = False db_table = 's2_bot_categories_mappings' class S2UserSubscription(models.Model): id = models.IntegerField(primary_key=True) id_s2_users = models.ForeignKey('S2Users', models.DO_NOTHING, db_column='id_s2_users', blank=True, null=True) id_s2_bot = models.ForeignKey(S2Bot, models.DO_NOTHING, db_column='id_s2_bot', blank=True, null=True) class Meta: managed = False db_table = 's2_user_subscription' query = """ SELECT s2_user_subscription.id_s2_users, s2_user_subscription.id_s2_bot, s2_bot_categories_mappings.id_s2_bot_categories FROM s2_user_subscription LEFT JOIN s2_bot_categories_mappings ON s2_user_subscription.id_s2_bot = s2_bot_categories_mappings.id_s2_bot; """ -
Dask task serialization in django
I am trying to set up prefect 2 with dask to run some tasks in django. One simple example with not much code runs fine but a larger example fails with: distributed.worker - ERROR - Could not deserialize task ****-****-****-**** Traceback (most recent call last): File "/usr/local/lib/python3.8/site-packages/distributed/worker.py", line 2185, in execute function, args, kwargs = await self._maybe_deserialize_task(ts) File "/usr/local/lib/python3.8/site-packages/distributed/worker.py", line 2158, in _maybe_deserialize_task function, args, kwargs = _deserialize(*ts.run_spec) File "/usr/local/lib/python3.8/site-packages/distributed/worker.py", line 2835, in _deserialize kwargs = pickle.loads(kwargs) File "/usr/local/lib/python3.8/site-packages/distributed/protocol/pickle.py", line 73, in loads return pickle.loads(x) File "/tmp/tmpb11md_6wprefect/my_project/models/__init__.py", line 2, in <module> from my_project.models.my_model import * File "/tmp/tmpb11md_6wprefect/my_project/models/api_key.py", line 14, in <module> class ApiKey(models.Model): File "/usr/local/lib/python3.8/site-packages/django/db/models/base.py", line 108, in __new__ app_config = apps.get_containing_app_config(module) File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 253, in get_containing_app_config self.check_apps_ready() File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 136, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. The problem here is that I use an init.py in a model directory instead of using multiple apps etc. To circumvent this error in other places I did set up the django environment at the beginning of each task, e.g.: import datetime import xyz import django os.environ.setdefault( "DJANGO_SETTINGS_MODULE", os.environ.get("DJANGO_SETTINGS_MODULE", "core.settings"), ) django.setup() # No we import the models from my_project.models import MyModel This worked fine … -
Ajax returning None in Django views [closed]
I have here a data from an input, and I want to send it using ajax to my django views. But it's returning None. in my html <input type="text" id="title" name="chart-title" /> <input onClick="send()" type="submit" /> in my script. this is the onclick function function send() { data = {}; data.title = $("#title").val(); console.log(data); //working I can see the data $.ajax({ url: '{% url "save" %}', method: "POST", data: { id: `{{ id }}`, csrfmiddlewaretoken: "{{ csrf_token }}", chart_data: JSON.stringify(data), }, }) .done(function (response) { console.log(response);//also this is workin fine }) .fail(function (error) { if (error) notify(error); }); } in my views.py def saveChart(request): if request.method == 'POST': title = request.POST.get('title') print(title) //it's returning None here return JsonResponse({"msg": "bar"}, status=200) -
How to combine two or more serializers which have custom fields but have same model in Django?
I am trying to create a Serializer Class which have two fields : name , subject but in a case I need to create two different serializers for each of the fields because the NameSerializer and SubjectSerializer will be used in many different places . So if I use them , I can just get detials just via the Serializer and not creating SerializerMethodField every time . For my NameSerializer and SubjectSerializer I am using SerializerMethod field , i am not directly accessing the fields . I am able to get data directly using a single serializer but I am unable to acceess the data when I am using both the serializer under one Combined Serializer. models.py class UserAccount(models.Model): name = models.CharField(max_length = 200) subject = models.CharField(max_length = 200 ) the views.py have serializers as well as the function views views.py from rest_framework import serializers from rest_framework.response import Response from rest_framework.decorators import api_view from .models import UserAccount class NameSerializer(serializers.ModelSerializer): the_name = serializers.SerializerMethodField("getName") class Meta : model = UserAccount def getName(self, object): return "__"+str(object.name)+"__" class SubjectSerializer(serializers.ModelSerializer): the_subject = serializers.SerializerMethodField("the_subject") class Meta : model = UserAccount def the_subject(self , object) : return "__"+str(object.subject)+"__" class FullSerializer(serializers.ModelSerializer): some_name = NameSerializer() some_subject = SubjectSerializer() class … -
Is there a way to hide url query params when using GET request?
I have a page on website with many filters/settings, all of them are stored in JSON object. And this page is displaying live data, so performance is important. Currently I'm sending POST request to fetch data, but I know it's not the best solution and breaking REST principles. So there is pros and cons for both solutions: GET Pros: Can use cache (good for performance, which is important) Good with REST Clear for user, he can see all of his settings directly in the url. Cons: With so much filters and settings final url can become very long, that's not what I want and I think that's a bad for users. POST Pros: Clean url, no distracting users I can just do queryset.filter(**request.data.items()), It's not really safe tho. Cons: Can't use caching So my question is, which way to choose, and if it is GET, can I hide query string somehow or hash it and decode on the backend? -
django.db.utils.OperationalError: no such column: *column_name*.id
Hi I have small app that scans RSS feed once a day. Data is then parsed to Pandas DF and then converted to SQL. This whole process works great when I go to my database I can see that data is inserted correctly. You can see it here here unfortunately, I cannot access that data. When I query queryset = Package.objects.all() I have this error django.db.utils.OperationalError: no such column: gathering_package.id models.py class Package(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False, unique=True) title = models.CharField(max_length=20) link = models.CharField(max_length=30) pubDate = models.CharField(max_length=30) description = models.CharField(max_length=200) author = models.CharField(max_length=30) class Meta: app_label = 'gathering' def __str__(self): return f'{self.title}' here are 3 functions that I use to get, parse and insert data to db def get_source(url: str) -> HttpResponse: try: session = HTMLSession() response = session.get(url) return response except requests.exceptions.RequestException as e: print(e) def get_feed(url: str) -> pd.DataFrame: response = get_source(url) df = pd.DataFrame(columns = ['title', 'link', 'description', 'author', 'pubDate']) tmp = [] with response as r: items = r.html.find("item", first=False) for item in items: title = re.split('added to PyPI', item.find('title', first=True).text)[0] link = item.find('guid', first=True).text pubDate = item.find('pubDate', first=True).text description = item.find('description', first=True).text or 'No description' try: author = item.find('author', first=True).text except AttributeError: author = … -
Django unittests + mock in signal testing : AssertionError: expected call not found (although actual and expected values match)
I am using Django 3.2 I am writing unittests to test some custom signals. Here is a (necessarily simplified) version of the code I am testing: /path/to/project/myapp/models.py from .signals import signal_comment from .constants import EVENT_COMMENT_DELETE class Commentable(models.Model): def delete_comment(actor, *args, **kwargs): # do some checking etc ... signal_comment.send(sender= self.__class__, instance=self, comment_instance=comment, event_type = EVENT_COMMENT_DELETE, actor=actor) class Meta: abstract = True class InterestingArtefact(Commentable): pass /path/to/project/myapp/signals.py from django.dispatch import Signal # ... signal_comment = Signal() /path/to/project/myapp/tests/models/test_comment_models.py from unittest.mock import MagicMock class CatchSignal: def __init__(self, signal): self.signal = signal self.handler = MagicMock() def __enter__(self): self.signal.connect(self.handler) return self def __exit__(self, exc_type, exc_value, tb): self.signal.disconnect(self.handler) class TestCommentModels(TestCase): # ... def test_delete_comment_signal_emits_correct_data(self): with CatchSignal(signal_comment) as catcher: the_signal = catcher.signal handler = catcher.handler # Create comment (not using InterestingArtefact.add_comment(), so signal not sent on creation) ct = ContentType.objects.get_for_model(self.artefact) oid = self.artefact.id comment = Comment.objects.create(content_type=ct, object_id=oid, body='Hello world!', actor=self.approved_user) # is_ok, comment = self.artefact.add_comment(self.approved_user, **self.cparms_plain_text) self.assertIsInstance(comment, Comment) self.artefact.delete_comment(self.approved_user, comment.id) handler.assert_called_once_with( signal = the_signal, sender = InterestingArtefact, instance = self.artefact, comment_instance = comment, event_type = EVENT_COMMENT_DELETE, actor = self.approved_user ) When I run the test for this particular test, it fails, and I get the rather cryptic/not helpful message on the console: in test_delete_comment_signal_emits_correct_data handler.assert_called_once_with( File "/usr/lib/python3.8/unittest/mock.py", line 925, … -
Is there any way to get the DNS address of an instance of an aws ubuntu server if I do not have the login to the aws account, but the SSH key for it
I got a task to deploy a static website on an AWS Ubuntu Server, I was given the username and the SSH key for it. Using PuTTy I got access to the server, setup django, postgres nginx and gunicorn. However now I need to check the progress and whichever tutorial I looked up, I found them checking their deployment progress with a dns address, but since I have connected to the server remotely, I do not have that. So please help me check my deployment status. I am attaching some screenshots of the PuTTy terminal below Image of the final Gunicorn command to finish the deployment -
Django gives errors to users who are not amazon ses approved during recording
I'm creating a website with Django and I make it, but I have a problem, I get an error when registering for email users here is a recording of the audio section of the plugin I'm using Amazon approved, the user works there, but it is giving me an error when registering users unapproved how can I solve this error, I shared a picture of. https://prnt.sc/GacRc7WudeDR -
Set graphene field when returning from query resolver
We are currently upgrading from an old version of graphene (0.99) to a new one (2.15). In the old version, we were able to set the value of a field in the query resolver. For example: class DogType(DjangoObjectType): selected = graphene.Boolean() class Meta: model = Dog class DogsQuery(graphene.ObjectType): dogs = graphene.List(DogType) resolve_dogs(self, info): top_dogs = Dogs.objects.all()[:10] return [DogType(d, selected=(i == 0)) for i, d in enumerate(top_dogs)] This resolver hands back a list of DogTypes, and the first dog in the list has "selected=True" while the others have "selected=False". It resolves successfully. In newer versions of graphene, this throws an error: "'DogType' object has no attribute 'pk'". I presume this is because newer versions of graphene don't want us to return Types. So I'm just wondering if it is possible to set the graphene field "selected" in the query resolver itself in newer versions of graphene? -
How to upload an image on server with react native?
I'm using react native on frontend and django in backend. I want to submit a form and that form contains images in it. Now the problem is. I'm unable to upload images with following code. currently following json is going in backend. { "details":{ "name":"My first ", "description":"this is Gina be cool", "display":"file:///data/user/0/com.merchant_app/cache/rn_image_picker_lib_temp_935cb7c5-72fd-4c7a-ab45-7b62906909f7.jpg", "background":"file:///data/user/0/com.merchant_app/cache/rn_image_picker_lib_temp_9449c3c0-32c6-4122-8a92-1a9b5afa352f.jpg" }, "hours":[ { "partition":"P1", "timings":[ { "day":"Monday", "full_day":false, "close_day":false, "start_time":"2022-09-16T01:00:00.149Z", "close_time":"2022-09-16T01:00:00.149Z" } ] } ] } backend response : {'display': ['The submitted data was not a file. Check the encoding type on the form.'], 'background': ['The submitted data was not a file. Check the encoding type on the form.']} my code . const {Name,bio,displayFilePath,backgroundFilePath} = this.props.route.params.stepOneData const background = backgroundFilePath const display = displayFilePath console.log("==> ",backgroundFilePath.assets[0].fileName) let data = { details = { name:Name, description:bio, display:display, background:background }, hours:[ { "partition":"P1", "timings":[ { "day":"Monday", "full_day":false, "close_day":false, "start_time":"2022-09-16T01:00:00.149Z", "close_time":"2022-09-16T01:00:00.149Z" } ] } ] } try { await addNewGroundAPI(formdata) alert("Post created") } catch (e) { console.log("Error", e) // alert("Error") } If you know to fix it. Please contribute in solving this thank You. -
Django+Postgres Broken transaction after checking for uniqueness
I created a simple project with one application and a model. https://github.com/SergeyMalash/test_unique It has two unique fields. Also in the settings I specified ATOMIC_REQUESTS When I make a POST request with an invalid IP address, an error occurs (screenshot) My assumptions: As far as I understand, during the check for uniqueness, a DataError exception occurs, since postgres can't compare inet field with an incorrect IP address This breaks all subsequent calls to the database. https://github.com/encode/django-rest-framework/blob/master/rest_framework/validators.py#L71 Am I right? How can this be fixed? I need to leave ATOMIC_REQUESTS enabled My issue is partially related to https://github.com/encode/django-rest-framework/issues/3381 But I didn't find a solution there. `https://pastebin.com/bDuQvje4` `https://pastebin.com/7VaWjMaZ` -
Django/Wagtail Rest Framework API Ordering/Pagination
I am using wagtail. I have serialized my API. I want to order them by -first_published_at, when someone hit my API url api/v2/pages they will see an ordered API without filtering it via URL. here is my api.py code: class ProdPagesAPIViewSet(BaseAPIViewSet): renderer_classes = [JSONRenderer] filter_backends = [FieldsFilter, ChildOfFilter, AncestorOfFilter, DescendantOfFilter, OrderingFilter, TranslationOfFilter, LocaleFilter, SearchFilter,] meta_fields = ["type","seo_title","search_description","first_published_at"] body_fields = ["id","type","seo_title","search_description","first_published_at","title"] listing_default_fields = ["type","seo_title","search_description","first_published_at","id","title","alternative_title","news_slug","blog_image","video_thumbnail","categories","blog_authors","excerpt","content","content2","tags",] nested_default_fields = [] ordered_queryset= [] name = "pages" model = AddStory api_router.register_endpoint("pages", ProdPagesAPIViewSet) I have tried ordered_queryset= [AddStory.objects.order_by('-first_published_at')] But it's not ordered by the newest published stories. How should I do the query? Here is my API response { "meta": { "total_count": 6 }, "items": [ { "id": 4, "meta": { "type": "blog.AddStory", "seo_title": "", "search_description": "", "first_published_at": "2022-08-30T11:05:11.341355Z" }, { "id": 6, "meta": { "type": "blog.AddStory", "seo_title": "", "search_description": "", "first_published_at": "2022-08-30T11:13:47.114889Z" }, { "id": 7, "meta": { "type": "blog.AddStory", "seo_title": "", "search_description": "", "first_published_at": "2022-08-31T11:13:47.114889Z" }, -
How to extend template from library
I have a Django app, where I have customized the admin base_site.html. I have installed a library (Django admin tools) which also extends the admin base_site.html Obviously, my custom base_site.html does not load anymore. I'd like to extend the base_site from django-admin-tools but I did not find how. I have read the Django docs (Template inheritence and extends) but could not find anything with more details. I have also seen the {% extend "project:path/file.html" %} notation but could not find documentation about how the part before the : works. I have tried : {% extend "admin_tools/base_site.html" %} {% extend "admin_tools/admin/base_site.html" %} {% extend "admin/admin_tools/base_site.html" %} {% extend "admin/admin_tools/menu/templates/admin/base_site.html" %} {% extend "admin_tools/menu/templates/admin/base_site.html" %} {% extend "admin_tools:menu/templates/admin/base_site.html" %} How can I extend this file ? And, if it exists, where can I find the documentation on how exactly extend works ? My template config looks like this : TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": [BASE_DIR / "templates"], "APP_DIRS": False, "OPTIONS": { "context_processors": [ "django.template.context_processors.debug", "django.template.context_processors.request", "django.contrib.auth.context_processors.auth", "django.contrib.messages.context_processors.messages", # Custom context processors "utils.context_processors.settings", "social_django.context_processors.backends", "social_django.context_processors.login_redirect", ], 'loaders': [ "admin_tools.template_loaders.Loader", "django.template.loaders.app_directories.Loader", # insert your TEMPLATE_LOADERS here ] }, }, ] -
Unique together with something related by a foreign key
class ExamSectionMixin(models.Model): exam_section = models.ForeignKey('fipi_exam_sections.ExamSection', blank=True, null=True, on_delete=models.CASCADE, ) class Meta: abstract = True class PriorityMixin(models.Model): priority = models.PositiveIntegerField(blank=False, default=0, null=False, db_index=True) class NameMixin(models.Model): name = models.CharField(max_length=255, null=False, default="") def __str__(self): return self.name class Meta: abstract = True class TaskDescription(NameMixin, PriorityMixin, ExamSectionMixin): class Meta: constraints = [ models.UniqueConstraint(fields=['exam_section__exam_part', 'name', ], name='exam_section-name'), models.UniqueConstraint(fields=['exam_section__exam_part', 'priority', ], name='exam_section-priority') ] This code blows up when migrating. That is makemigrations is done. But not migrate. fipi_task_descriptions.TaskDescription: (models.E012) 'constraints' refers to the nonexistent field 'exam_section__exam_part'. Could you tell me whether it is possible to organise unique together of exam_part and name and exam_part and priority respectively? -
Optional Parameter in URL for Taggit Django
I've been trying to use Tags in my project, using the django application django-taggit. I already put them in the models and it works fine so far. But now i want that people can search for the items in the url with the tags. For example /items/tag=blue. But i want this parameter in the URL to be optional. How can i do this? This is my URL: path('items/', views.ItemsView.as_view(), name='items') I just want a parameter in this url, that is optional so the user can, but doesn't have to search for them. -
How to get the remaining values from django array loop
I am learning some stuff in the Django template but I encountered some difficulty in adding my dynamic style. My goal here is to add a span and class in the first word but I don't know how to get the remaining words. Here's my code: <h4> {% for b in banner.title.split %} {% if forloop.counter == 1 %} <span class="main-color">{{ b }}</span> {% else %} {{ b }} {% comment %} HOW CAN I GET THE REMAINING HERE{% endcomment %} {% endif %} {% endfor %} </h4> {% comment %} Target output: <h4> <span class="main-color">OUR</span>WORKS </h4> {% endcomment %} -
ASGI Django Application Hosting in Windows Server 2012
Can I host ASGI Django App in Windows Server 2012 backed with Apache? I explored several blogs which mentions about "mod_wsgi" which confused me if it could handle ASGI application. Medium/Analytics-Vidya Prof. Dr. Christian Leubner settings.py INSTALLED_APPS = [ 'channels', 'rest_framework', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'broadcast', ] ASGI_APPLICATION = 'AppMain.asgi.application' CHANNEL_LAYERS = { "default": { "BACKEND": "channels_redis.core.RedisChannelLayer", "CONFIG": { "hosts": [("localhost", 6379)], # "hosts":[os.environ.get('REDIS_URL', 'redis://localhost:6379')] }, }, } asgi.py import os import django from django.core.asgi import get_asgi_application from channels.routing import ProtocolTypeRouter, URLRouter from channels.auth import AuthMiddlewareStack from django.urls import path from broadcast.consumers import AConsumer import broadcast.routing os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AppMain.settings') django.setup() # application = get_asgi_application() application = ProtocolTypeRouter({ 'http' : get_asgi_application(), 'websocket' : AuthMiddlewareStack( URLRouter( broadcast.routing.websocket_urlpatterns ) ) }) -
I can't get to one parameter(m2m) from my models Django
I created view where i add stops to route, its working fine, but stops are not appearing in order when i add them, and i have no idea why. Please tell me where i'm making a mistake Here's my code: Models: #not important class Port(models.Model): class Route(models.Model): name = models.CharField(max_length=128, default='') user = models.ForeignKey(User, on_delete=models.CASCADE) stop_list = models.ManyToManyField(Port, through='RoutePort') def __str__(self): return f'{self.name}' class RoutePort(models.Model): port = models.ForeignKey(Port, on_delete=models.CASCADE) route = models.ForeignKey(Route, on_delete=models.CASCADE) order = models.PositiveIntegerField() class Meta: ordering = ['order'] the order i intend them to appear is set by 'order' parameter from class routeport form: class AddRoutePort(forms.ModelForm): class Meta: model = RoutePort fields = ['port', 'order'] form is short and i dont know if i didnt forget something there View, get is working correctly, post works almost ok. New ports are correctly added to new route from list, but they appear in order of being added, not the one i wanted them to. class RouteCorrectView(View): def get(self, request, pk): route = Route.objects.get(pk=pk) form = AddRoutePort() return render(request, 'route_correct.html', {'route':route, 'form':form}) def post(self, request, pk): route = Route.objects.get(pk=pk) form = AddRoutePort(request.POST) if form.is_valid(): to_port = form.save(commit=False) to_port.route = route order = to_port.order ordering = RoutePort.objects.filter(order__gte=order, route=route) for port in … -
Select From Another DataBase in Django Rest framework
In Rest FrameWork Django I want use from another DataBase in my View Now I can use data of databse model of django created . I want select a database of another program and show in api Please Help Me Thanks -
Rendering Django View Data to HTML
I am creating a learning portal, in which students can learn on various books. Each book will have various chapters / topics. Each topic is having a unique slug, as reflected the below mentioned model, which we want to render / show on an HTML page, upon clicking on it. I want to show the contents of the topic on a separate HTML page, when somebody click on that particular topic. I have written the below mentioned code, however, failed to populate the data on the HTML. My Django model, view.py and url.py is as under. My Django model is as follows: class book_explination(models.Model): title = models.CharField (max_length = 255) slug = models.SlugField(max_length= 250, null = True, blank = True, unique= True) lesson_no = models.CharField (max_length = 255) book_text = models.TextField (blank=False, null=False) my view is as follows: def topic_detail(request, url): topic_detail = book_explination.objects.get(slug = url) return render(request, 'blog/topic_detail.html', {'topic_detail':topic_detail}) The HTML rendering page is as follows: {% block content %} <div class="container"> <p> {{lesson_no | safe}} </p> <p> {{book_text | safe}} </p> <p> {{book_text_explination | safe}} </p> </div> {% endblock %} <ul> {% for c in topic_detail %} <li>{{ c.lesson_no }}</li> <li>{{ c.lesson_no }}</li> <li>{{ c.lesson_no }}</li> {% endfor … -
How to connect to RDS from locally created django
I am trying to connect to Aurora on RDS from a local Django application. Docker is used as the execution environment. Publicly Accessible is allowed to connect to RDS from local. I have confirmed that I can connect from local with mysql command, but not from on django. Why can't I connect from Django? Commands tried: $ mysql -h xxxx.xxxx.ap-northeast-1.rds.amazonaws.com -u admin -p mysql> This command allows you to get inside mysql. The django database setup is as follows: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'xxxxxxxx', 'USER': 'admin', 'PASSWORD': 'xxxxxxx', 'HOST': 'xxxxx.xxxxxxx.ap-northeast-1.rds.amazonaws.com', 'PORT': '3306', } } Output error statement: django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'xxxxx.xxxxx.ap-northeast-1.rds.amazonaws.' (111)") -
Django test : Field 'id' expected a number but got datetime.datetime
It's my first time doing tests in a Django app, and I don't understand my error. When i run python manage.py test, I got this error : D:\Users\boucardale\Documents\code\djangotest>python manage.py test You are in dev mode Found 1 test(s). Creating test database for alias 'default'... Traceback (most recent call last): File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\db\models\fields\__init__.py", line 1988, in get_prep_value return int(value) TypeError: int() argument must be a string, a bytes-like object or a number, not 'datetime.datetime' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\core\management\__init__.py", line 446, in execute_from_command_line utility.execute() File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\core\management\__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\core\management\commands\test.py", line 24, in run_from_argv super().run_from_argv(argv) File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\core\management\base.py", line 414, in run_from_argv self.execute(*args, **cmd_options) File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\core\management\commands\test.py", line 68, in handle failures = test_runner.run_tests(test_labels) File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\test\runner.py", line 1000, in run_tests old_config = self.setup_databases( File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\test\runner.py", line 898, in setup_databases return _setup_databases( File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\test\utils.py", line 220, in setup_databases connection.creation.create_test_db( File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\db\backends\base\creation.py", line 79, in create_test_db call_command( File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\core\management\__init__.py", line 198, in call_command return command.execute(*args, **defaults) File "D:\Users\boucardale\Documents\code\djangotest\venv\lib\site-packages\django\core\management\base.py", line 460, in execute output = self.handle(*args, **options) …