Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to serve response in django then down the server
I need a advice I want create a path in django for example /stop-server When somebody send a request to /stop-server server return a response and then become killed What's your proposal?......... -
Tests for Django Channels/WebSockets
what is the good & easy way to test consumers.py in Django Channels (websocket endpoints). I've seen https://channels.readthedocs.io/en/stable/topics/testing.html but to me that's kinda too complicated a bit and not sure if that's I want. For example I haven't find info about how to pass user to scope for proper consumer testing or how to make my custom middleware for authentication. Maybe there's someone "advanced" at django channels and you've tested consumers. If yes, please share the way you did it, because I really can't google how to test this stuff. I have already reached this stage: class TestConsumer(TestCase): async def test_consumer(self): communicator = WebsocketCommunicator(UserLocationConsumer.as_asgi(), path='/ws/user-track-location')) connected, subprotocol = await communicator.connect() self.assertTrue(connected, 'Could not connect') await communicator.send_json_to(content='test') result = await communicator.receive_json_from() print(result) await communicator.disconnect() That allows me to enter my consumer BUT inside consumer there is no scope, because no authorization where passed, so I can't fully cover my consumer's functionality with tests: ERROR: test_consumer (gps.tests.test_consumers.TestConsumer) self.user_id = self.scope['user'].id KeyError: 'user' -
Django .save() doesn't update on PUT request
I am trying to update a foreign-field with a PUT request on a resource. My serializer.data and the http response is correct after callig .is_valid, but the object doesn't get updated. View def put(self, request, user_pk): try: userById = getUserById(user_pk) except ChatUser.DoesNotExist: raise Http404 serializer = ChatUserInputSerializer(userById, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Serializer class IdentificationInputSerializer(serializers.ModelSerializer): class Meta: model = Identification fields = "__all__" read_only_fields = ["id"] class ChatUserInputSerializer(serializers.ModelSerializer): identification = IdentificationInputSerializer() class Meta: model = ChatUser fields = ["id", "userId", "identification"] read_only_fields = ["id", "userId"] def update(self, instance, validated_data): identification = validated_data.pop('identification') instance.identification.salutation = identification.get('salutation', instance.identification.salutation) instance.identification.firstname = identification.get('firstname', instance.identification.firstname) instance.identification.name = identification.get('name', instance.identification.name) instance.identification.street = identification.get('street', instance.identification.street) instance.identification.plz = identification.get('plz', instance.identification.plz) instance.identification.city = identification.get('city', instance.identification.city) instance.identification.country = identification.get('country', instance.identification.country) instance.save() return instance -
How to associate a URL with an IP address?
I developped multiple REST APIs in Django--each with a specific IP address--and I would like to point them to a single domain name. With A records I could associate IPs of the APIs with subdomains like s.example.com, c.example.com and so on, but how can I associate IPs with URLs ? is it possible ? The desired URL pattern would be something like this : https://example.com/s/api # IP 1 https://example.com/c/api # IP 2 https://example.com/t/api # IP 3 https://example.com/b/api # IP 4 https://example.com # IP 2 -
Way to fix "missing QuerySet" and "override QuerySet" with Django
I'm trying to code a blog with django but I want to add a placeholder to my form when creating or editing an article. So I had the forms.py because before that I wasn't using a form from this file because I only needed the models.py file. I fount a way to do what I wanted and so add my placeholder into my input from my forms. But one problem, when I updated my website and went to my pages to see the changed an error appeared. So I tried to fix the problem by looking on the web and I saw a lot of people having approximately the same problem but the answers were that I had to add a get_qeryset definition in my views in views.py for the specific forms. I didn't find what I have to set in the definition of the get_queryset and not very understood where I have to put these definitions. I would be very grateful if you can help me. Here's my code : My views in view.py : class BlogHome(ListView): model = BlogPost context_object_name = "posts" def get_queryset(self): queryset = super().get_queryset() if self.request.user.is_authenticated: return queryset else: return queryset.filter(published=True) @method_decorator(login_required, name='dispatch') class BlogPostCreate(CreateView): … -
Django installation failed
My pc recently started giving error in installing Django.... Look at the error message, what could be the cause please? I tried installing Django for my project, and it just throw an unexpected error message. I have the right Venv activation code so I expected it to work. -
Using django-bootstrap-modal-forms on success, redirect to the initial page
Using django-bootstrap-modal-forms, I would like to redirect to the initial page, say /d/SimulationScenario/123/, after a successful POST request of modal form. My guess is that this is done using success_url, but how can I pass an argument indicating the ID of the scenario, which is different each time, like here: class EventCreateView(BSModalCreateView): template_name = 'form_scenario_event_create.html' form_class = SimulationEventForm success_message = 'Success: Event was added to the scenario.' success_url = reverse_lazy('detail_scenario', kwargs={'scenario_ID':123}) -
Pythonanywhere: Error running WSGI application. ModuleNotFoundError: No module named 'dotenv'
My web blog on Pythonanywhere was deployed a long time ago, today I redid the design and hid my secrets with the help of Dotenev. After that, I pushed everything to github, then deployed it to Pythonanywhere. As a result, when I launch the site, I get this window: After reading the logs, I saw the source of the problem, but I can’t find a solution anywhere, and now I’m turning to your community. This is what it says in my logs: enter image description here I imported everything in the code correctly, activated it, and set the parameters in a new .env file. I wrote variables for the secrets, and so that they are read by the setting.py file. I read the logs, I saw this error, but I can't find a solution to it -
Django {% extends 'base.html' %} {% block content %} {% load static %} does not work, nothing works actually
I have a html template i want to code in django. For now i need to take the header and footer parts and make images, css and js into static files. I tried to do it but it does not quite work, can anyone help me with it? I would greatly appreciate if someone can fix my mistakes and send me the file {% extends 'base.html' %} {% block content %} {% load static %} none of them work -
How to create an SMPP server
I have built am sms platform in django that connects to providers via HTTP, but now i want my application to communicate in SMPP protocol. Please has anybody built such an application.? I have searched through the internet, I found this repo https://github.com/dtekluva/shorty_SMPP. But I cannot for the life of me, get it to run. I have also tried to reach out to the developer. -
Django doesn't recognize worker.js file which is created by react.js
I have an app where I create frontend with react.js and then send the template files into django app and then run only django app. I'm having trouble with django recognizing a file within in this "build" folder that comes from react. Here is my index.html file: <html lang="en"> <head> <meta charset="utf-8" /> <meta name="viewport" content="width=device-width, initial-scale=1" /> <meta name="theme-color" content="#000000" /> <meta name="description" content="Web site created using create-react-app"/> <link rel="apple-touch-icon" href="%PUBLIC_URL%/logo192.png" /> <link rel="manifest" crossorigin="use-credentials" href="./manifest.json" /> <script> if ('serviceWorker' in navigator) { window.addEventListener('load', function() { navigator.serviceWorker.register('./worker.js').then(function(registration) { console.log('Worker registration successful', registration.scope); }, function(err) { console.log('Worker registration failed', err); }).catch(function(err) { console.log(err); }); }); } else { console.log('Service Worker is not supported by browser.'); } </script> <title>SettledHead</title> </head> <body> <div id="root"></div> </body> </html> When I run react app directly, it works and this is the screenshot of the end-result: And this is the screenshot from the page which will create problem at django part (but works fine here): Then I run "npm run relocate" and send the build folder into django app. When I dont do anything about serviceworker, my app works well with this structure. But when I try to implement pwa - serviceworker into it, it doesnt … -
How to add django-editorjs-fields EditorJsTextField or EditorJsJSONField in html template
I am trying to add block style editor with django-editorjs-fields. It work django admin fine but not working with template. I properly configure urls.py for static files. Here is my code sample..... models.py class Post(models.Model): title = models.CharField(max_length=255, blank=False) slug = models.CharField(max_length=255, unique=True) image = models.ForeignKey(Media, on_delete=models.SET_NULL, blank=True, null=True) content = EditorJsTextField(blank=True, null=True) forms.py class PostForm(forms.ModelForm): class Meta: model = Post fields = '__all__' widgets = { 'content': EditorJsWidget(plugins=["@editorjs/image", "@editorjs/header"]) } views.py class PostFormView(FormView): form_class = PostForm template_name = 'add.html' success_url = '/' def form_valid(self, form): form.save() return super().form_valid(form) template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Title</title> </head> <body> <form action="" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Save</button> </form> </body> </html> Output: https://prnt.sc/ytMX_522Y4zF Not showing expected output. Show only normal textfield Expected output: https://prnt.sc/l0Uku9Xt-yNl -
django rest framework POST error. When I send a JSON/dictionary inside a Json it returns: "Not a valid string."
I'm trying to get this test API working, it is very simple and the model consist of only one class with 2 fields. My viewset inherits from ModelViewset and I added(to make it more explicit, and make some changes in the future) the list and create function. I could POST a few JSONs with succes, but when I try to post this one that has a 'nested json' it returns "Not a valid string." Here is the code and the JSON: views.py: class SessionViewset(viewsets.ModelViewSet): """" A simple viewset for listing or retrieving 'sessions' """ queryset = Session.objects.all() serializer_class = SessionSerializer def list(self, request): queryset = Session.objects.all() serializer = SessionSerializer(queryset, many=True) return Response(serializer.data) def create(self, request, *args, **kwargs): serializer = self.get_serializer(data=request.data) serializer.is_valid(raise_exception=True) self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) JSON: { "meta":"aca va la metadata", "reunion":{"juan":500, "pedro":300, "jose":1000} } and it returns: { "reunion": [ "Not a valid string." ] } screenshot: Do you know if there is any limitation that I'm not aware of, or how can I solve this issue? Thanks Tried to POST that JSON, into the API endpoint, with said error response -
Django - Form not populating in models but no error in console
I'm creating a Django application and am having a bit of difficulty with creating 'activities' via the frontend. (CRUD application) Previously, I had issues related to the ForeignKey for the host; which I was using the extended AllAuth models (named UserProfile) and the errors for this do appear to have resolved, however there is still something going wrong in the functionality. I'm currently struggling to get the submitted data to pass form the form through to the backend, but there are no errors in my console/terminal window when im running the application. views.py def create_activity(request): userprofile = get_userprofile(request) if request.method == "POST": form = ActivityForm(request.POST, instance=userprofile) if form.is_valid(): form.save() return redirect('activities') else: form = ActivityForm(instance=userprofile) context = { 'form': form, } return render(request, 'activities/new_listing.html', context) Along with my forms.py file from datetime import date from django import forms from .models import Activity from .widgets import DatePickerInput, TimePickerInput class ActivityForm(forms.ModelForm): class Meta: model = Activity fields = ('name', 'date', 'start_time', 'end_time', 'location', 'description') labels = { 'name': 'Activity Type', 'date': 'Date of Activity', 'start_time': 'Start Time', 'end_time': 'End Time', 'location': 'Location', 'description': 'Description', } widgets = { 'date' : DatePickerInput(), 'start_time' : TimePickerInput(), 'end_time' : TimePickerInput(), } -
Prefetching extra fields in a ManyToMany table
I am working with Django on a database that has additional fields on intermediate models. Since it's a big database, I try to optimize the way the data is loaded. But I have a problem with the extra fields of the association table. Let's take this example from Django's documentation : from django.db import models class Person(models.Model): name = models.CharField(max_length=128) def __str__(self): return self.name class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField(Person, through='Membership') def __str__(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) date_joined = models.DateField() invite_reason = models.CharField(max_length=64) What I would like to do is, from each entity of the Group class, retrieve all the entities of the Person class and retrieve all the fields invite_reason or date_joined. To retrieve the persons, it goes fast with the QuerySet.prefetch_related attribute that prevents the deluge of database queries that is caused by accessing related objects. groups = (Group.objects.prefetch_related('members') However, I did not find a solution to retrieve in a constant access time the extra fields invite_reason and date_joined. I tried prefetching membership_set or a related name in my variable groups but my code doesn't go faster. # NOT WORKING groups = (Group.objects.prefetch_related('members', 'membership_set') I also tried using … -
Apaceh2, DJango, WSGI errors "No such file or directory: mod_wsgi"
I'm trying to get my django app served on appache2, and ran into various errors. I've sort out most of them, but now getting the error below. I've found others with similar issues, but no solution was found. Please help. error.log [Fri Oct 28 16:42:15.537187 2022] [wsgi:warn] [pid 100608] (2)No such file or directory: mod_wsgi (pid=100608): Unable to stat Python home /home/ubuntu/django-app/env. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home/ubuntu/django-app/env' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home/ubuntu/django-app/env' sys.base_exec_prefix = '/home/ubuntu/django-app/env' sys.platlibdir = 'lib' sys.executable = '/usr/bin/python3' sys.prefix = '/home/ubuntu/django-app/env' sys.exec_prefix = '/home/ubuntu/django-app/env' sys.path = [ '/home/ubuntu/django-app/env/lib/python310.zip', '/home/ubuntu/django-app/env/lib/python3.10', '/home/ubuntu/django-app/env/lib/python3.10/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Current thread 0x00007fb6911f8780 (most recent call first): <no Python frame> ubuntu@ip-172-31-34-187:~$ apachectl -M Loaded Modules: core_module (static) so_module (static) watchdog_module (static) http_module (static) log_config_module (static) logio_module (static) version_module (static) unixd_module (static) access_compat_module (shared) alias_module (shared) auth_basic_module … -
Django App on Heroku using psycopg2 - unable to run locally - can't detect module
Been trying to implement a django app with postgresql database on heroku, with psycopg2 as the backend. (Based on the research I've done, psycopg3 looks like it's not really built for that purpose) My app works, without issue running inside heroku/heroku console, and connects to db fine. But running locally (python manage.py runserver), it just can't detect the psycopg2 module. I've reinstalled the module in and out of a venv. I've tried the binary install, used -pep517 method as well. I saw a thread here indicating newer python may not be compatible, but it didn't really provide any concrete proof as far as I could tell. Any advise in this regard, or perhaps a better backend adapter suggestion for Django + postgres? below are the relevant portions of settings.py in the django project directory: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': '*db info here' ...more db creds } } and the error: File "C:\*userdirectory*\djangenv\Lib\site-packages\django\db\backends\postgresql\base.py", line 24, in <module> import psycopg2 as Database File "C:\*userdirectory*\djangenv\Lib\site-packages\psycopg2\__init__.py", line 51, in <module> from psycopg2._psycopg import ( # noqa ImportError: DLL load failed while importing _psycopg: The specified module could not be found. -
Django run_validation removing MultiValueDict from QueryDict
I have a nested serializer field on a serializer which accepts Multipart/form-data (json + images). The run_validation happens to remove the nested serializer field data from the QueryDict. Here is the code: class CreateSerializer(ModelSerializer[Dress]): dress_sizes = SizeSerializer(many=True, required=False) def run_validation(self, data: Any = ...) -> Any | None: return super(CreateSerializer, self).run_validation(data) def validate(self, data): return super().validate(data) Here is the data that I get in the run_validation method: < QueryDict: { 'file_name': ['swimsuit.svg'], 'dress_sizes': [ [{ 'size': 'xs' }, { 'size': 's' }, { 'size': 'm' }, { 'size': 'l' }, { 'size': 'xl' }] ], 'image': [ < TemporaryUploadedFile: swim.svg(image / svg + xml) > ] } > After run_validation the validate gets following data: OrderedDict([('file_name', 'swimsuit.svg'), ('image', < TemporaryUploadedFile: swim.svg(image / svg + xml) > )]) Here the whole dress_sizes has disappeared. Which is needed to create the list of dress_sizes objects. I have reduced the code to make it readable. Maybe there are some mismatches in the spellings which is not the issue. Question is how to make the run_validation not remove the list of dress_sizes? Finally in the create method there is no data for the dress_sizes = []. Here is create: def create(self, validated_data: Dict[str, Any]) … -
I am a first time python/django user trying to test a nested serializer and getting 'TypeError: Direct assignment to the reverse side of a relatedset'
I am trying to write a test to show that I can serialize a customer and pass the subscriptions that the customer has subscribed for currently just one subscription but I do believe that what I have would work for multiple subscriptions. This is my first time doing anything in python and I do not know the inner workings and dont know what I messed up here Here is my test_serializer.py file class CustomerSerializerTestCase(unittest.TestCase): def setUp(self): self.subscription_attributes = { 'title': 'Tea Partay', 'price': 50.99, 'status': 'active', 'frequency': 'monthly' } self.customer_attributes = { 'first_name': 'Hai', 'last_name': 'Sall', 'email': 'sailt&peppa@saimall.com', 'address': 'this place Seattle, WA', 'subscriptions': 'self.subscription.id' } self.subscription = Subscription.objects.create(**self.subscription_attributes) self.serialzied_subscription = SubscriptionSerializer(instance=self.subscription) self.customer = Customer.objects.create(**self.customer_attributes) self.serialized_customer = CustomerSerializer(instance=self.customer) def test_customer_serializer_has_correct_keys(self): customer_att = { 'first_name': 'pachary', 'last_name': 'zrince', 'email': 'Ilovelittlekatanas@hotkatana.com', 'address': 'katana ln, maldorf, Waryland' } customer = Customer.objects.create(**customer_att) serialized_customer = CustomerSerializer(instance = customer) data = serialized_customer.data self.assertEqual(set(data.keys()), set(['first_name', 'last_name', 'email', 'address', 'subscriptions'])) def test_customer_field_contents(self): customer_data = self.serialized_customer.data self.assertEqual(customer_data['first_name'], self.customer_attributes['first_name']) self.assertEqual(customer_data['last_name'], self.customer_attributes['last_name']) self.assertEqual(customer_data['email'], self.customer_attributes['email']) self.assertEqual(customer_data['address'], self.customer_attributes['address']) self.assertEqual(customer_data['subscriptions'], self.subscription_attributes['title']) self.assertEqual(customer_data['subscriptions'], self.subscription_attributes['price']) self.assertEqual(customer_data['subscriptions'], self.subscription_attributes['status']) self.assertEqual(customer_data['subscriptions'], self.subscription_attributes['frequency']) Heres my models.py class Tea(models.Model):#has_many :subscriptions title = models.CharField(max_length = 100) description = models.CharField(max_length = 1000) temperature = models.IntegerField() brew_time = models.IntegerField() class Customer(models.Model):#has_many :subscriptions first_name = … -
Python manage.py runserver raise NotSupportedError( django.db.utils.NotSupportedError: PostgreSQL 11 or lateed (found 10.22)
I'm beginner in python and django, I'm working on a windows 10 - 32 bits computer. I don't understand where is the problem, what I changed but when I run manage.py, It get this : $ python manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\kgonc\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 932, in _bootstrap_inner self.run() File "C:\Users\kgonc\AppData\Local\Programs\Python\Python38-32\lib\threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "C:\Users\kgonc\Desktop\carzone-project\env\lib\site-packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\kgonc\Desktop\carzone-project\env\lib\site-packages\django\core\management\commands\runserver.py", line 137, in inner_run self.check_migrations() File "C:\Users\kgonc\Desktop\carzone-project\env\lib\site-packages\django\core\management\base.py", line 564, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "C:\Users\kgonc\Desktop\carzone-project\env\lib\site-packages\django\db\migrations\executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "C:\Users\kgonc\Desktop\carzone-project\env\lib\site-packages\django\db\migrations\loader.py", line 58, in __init__ self.build_graph() File "C:\Users\kgonc\Desktop\carzone-project\env\lib\site-packages\django\db\migrations\loader.py", line 235, in build_graph self.applied_migrations = recorder.applied_migrations() File "C:\Users\kgonc\Desktop\carzone-project\env\lib\site-packages\django\db\migrations\recorder.py", line 81, in applied_migrations if self.has_table(): File "C:\Users\kgonc\Desktop\carzone-project\env\lib\site-packages\django\db\migrations\recorder.py", line 57, in has_table with self.connection.cursor() as cursor: File "C:\Users\kgonc\Desktop\carzone-project\env\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\kgonc\Desktop\carzone-project\env\lib\site-packages\django\db\backends\base\base.py", line 323, in cursor return self._cursor() File "C:\Users\kgonc\Desktop\carzone-project\env\lib\site-packages\django\db\backends\base\base.py", line 299, in _cursor self.ensure_connection() File "C:\Users\kgonc\Desktop\carzone-project\env\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\kgonc\Desktop\carzone-project\env\lib\site-packages\django\db\backends\base\base.py", line 282, in ensure_connection self.connect() File "C:\Users\kgonc\Desktop\carzone-project\env\lib\site-packages\django\utils\asyncio.py", line 26, in inner return func(*args, **kwargs) File "C:\Users\kgonc\Desktop\carzone-project\env\lib\site-packages\django\db\backends\base\base.py", line 265, in connect self.init_connection_state() File "C:\Users\kgonc\Desktop\carzone-project\env\lib\site-packages\django\db\backends\postgresql\base.py", line 251, in init_connection_state super().init_connection_state() File … -
Why use Django REST Framework instead of returning normal HttpResponse in views?
I'm new to Python and I've seen a lot of tutorials which jump into the Django REST Framework when discussing how to create REST APIs without explaining why they need this library. I don't see the purpose of using the Django Rest Framework when I can just define API endpoints in views and return a simple HttpResponse to send data to a client. What does the Django Rest Framework accomplish that I can't do simply using HttpResponse? Why is it worth learning? I was going to use the library as it was included in the video, but it seemed more complex than I needed and I decided to try creating an API without Django REST Framework def getStats(request): print('--------STARTING Stats----------') # Take some GET variable version = request.GET.get('version') # Get some data with open('static/data.json') as f: data = json.load(f) # Filter the data if version is not None: data = list(filter(lambda x: x['version'] == version, data)) print("FILTERED DATA", len(data)) # Perform some operations on the data data = calculateStats(data) # Return an HTTP response return HttpResponse(json.dumps(data)) This code seemed to work as needed and I get the feeling that I could make this view more robust if needed based on … -
Dockerizing Django Project with Gunicorn and MSSQL - Login failed for user "myuser"
Can someone please tell me on how to dockerize django project using mssql and gunicorn? I am trying to do it for few days now but after every step I get some new error. Dockerfile: FROM registry.access.redhat.com/ubi8/python-38 USER root RUN yum update --assumeyes && \ yum install --assumeyes \ unixODBC-devel \ && yum clean all RUN curl https://packages.microsoft.com/config/rhel/8/prod.repo > /etc/yum.repos.d/mssql-release.repo RUN yum download -y msodbcsql17 RUN ACCEPT_EULA=y rpm -Uvh --nodeps msodbcsql17*rpm ENV PYTHONDONTWRITEBYTECODE=1 ENV PYTHONUNBUFFERED=1 EXPOSE 6001 WORKDIR /code ADD . /code COPY ./requirements.txt /code/requirements.txt RUN pip install -r requirements.txt COPY . /code/ docker-compose.yml version: "3.8" services: carcalapi: build: . command: gunicorn carcal.wsgi:application -b 0.0.0.0:6001 --workers=1 --timeout 1200 volumes: - .:/code ports: - "6001:6001" restart: unless-stopped env_file: .env networks: - npm-nw - carcal-network deploy: resources: limits: memory: 3000M reservations: memory: 20M networks: carcal-network: npm-nw: external: true Database Configuration: DATABASES = { 'default': { "ENGINE": "mssql", "NAME": env("DATABASE_NAME"), "USER": env("DBUSER"), "PASSWORD": env("PASSWORD"), "HOST": env("HOST"), "PORT": "", "OPTIONS": {"driver":"ODBC Driver 17 for SQL Server"}, } } I have tried many different things already to make it work, driver: SQL Server Native Client 11.0 tried it with giving a path to the driver '/opt/.....' (don't remember the exact path now). tried to add … -
Unable to authenticate Client in test
Python 3.10.7, Django 4.1.1, Django REST Framework 3.13.1 I am unable to get the django.test.Client login or force_login methods to work in a django.test.TestCase-derived test class. I'm referring to https://docs.djangoproject.com/en/4.1/topics/testing/tools/ My project seems to work when viewing it in a browser. Unauthenticated DRF views appear as expected, and if I log in through the admin site, protected views also appear as expected. A preliminary version of the front end that will consume this API is able to read data and display it with no problem. The local Django unit test environment uses a local SQLite3 install for data. All tests not requiring authentication are currently passing. This simplified test class reliably displays the problem: from django.contrib.auth.models import User from django.test import Client, TestCase from django.urls import reverse from eventsadmin.models import Address class AddressesViewTest(TestCase): username = "jrandomuser" password = "qwerty123" user = User.objects.filter(username=username).first() if user: print("User exists") else: user = User.objects.create(username=username) print("User created") user.set_password(password) user.save() client = Client() def setUp(self): if self.client.login(username=self.username, password=self.password): print("Login successful") else: print("Login failed") Address.objects.create(name="White House", address1="1600 Pennsylvania Ave", city="Washington", state="DC", postal_code="37188") def test_addresses(self): response = self.client.get(reverse("addresses-list")) self.assertContains(response, '"name":"White House"') First, I was surprised that I had to test for the existence of the User. Even though … -
How to use JavaScript in included components in Django?
In short, how to use JavaScript in the component that will be then included in the main page? A standard approach in Django templates is to create a base.html template and then extend it. That base template usually has blocks like content, extra_js, and extra_css. The extended template looks like {% extend 'base.html' %} {% block content %} <div> some content </div> {% endblock %} {% block extra_js %} # some js code here {% endblock %} I need to create a component that will be included on several pages and I need to use JavaScript inside that component. I know that it will be included only on pages that extend base.html, the page that includes it will look like {% extend 'base.html' %} {% block content %} <div> {% include 'component.html' %} </div> {% endblock %} {% block extra_js %} # some js code here {% endblock %} However, component.html knows nothing about extra_js block because it doesn't extend base.html, I cannot use that block in component.html, and if I just put some JavaScript code in it then after the template is rendered any JavaScript in component.html will end up being in the middle of the body of the … -
django-filer import file paths from mysql to postgresql
Recently I changed the database in my Django app from MySQL to PostgreSQL. I moved all text values and folders successfully from staging to the production environment but I am struggling with paths to media files that are stored on Azure Storage. I am using the same settings in my settings both in production and staging environments: DEFAULT_FILE_STORAGE = 'backend.custom_azure.AzureMediaStorage' MEDIA_LOCATION = "media" AZURE_ACCOUNT_NAME = config('AZURE_ACCOUNT_NAME') AZURE_CUSTOM_DOMAIN = f'{AZURE_ACCOUNT_NAME}.blob.core.windows.net' MEDIA_URL = f'https://{AZURE_CUSTOM_DOMAIN}/{MEDIA_LOCATION}/' The problem is that I connected all files on staging and when I am trying to manually export from mysql and import in postgresql filer_file and filer_image tables I am getting this error: Exception Type: Polymorphic Type Invalid at /homepage Exception Value: Content Type 37 Question Basically what I want is to copy folders and files that are on staging (paths stored in MySQL) and pasting/uploading/importing them on production (paths stored in PostgreSQL) so my question is how to resolve this issue. I don't want to connect each image once again in each model because there are hundreds of them already. Is there any way I can import them into PostgreSQL in a way that when I open the admin panel in the production environment it will show …