Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to implement SQLAlchemy Postgres async driver in a Django project?
I have come across really weird behavior implementing SQLAlchemy in my Django project using the asynchronous Postgres driver. When I create a SQLAlchemy Session using a sessionmaker and then execute a simple SELECT statement within a session context manager, it generates the correct result the first time, but the proceeding attempts result in a RuntimeError exception stating "Task ... attached to a different loop". I looked up the error and it usually indicates that the session is persisted across multiple Django requests; however, in my code, I don't see how that is possible since I am creating the database session within the request using the sessionmaker and using the session context manager to close it. It gets weirder when reloading the page for a 3rd time using the session context manager approach because the RuntimeError changes to an InterfaceError stating "cannot perform operation: another operation is in progress". But when not using the context manager approach and creating the session manually and immediately after using it closing the session it only produces the RuntimeError exception even after the 2nd attempt. And it continues to get weird, when I do the second approach and do not await the session close, then … -
Gunicorn error: unrecognized arguments wsgi:application
I was trying to run Django in Nginx with the centos7 platform and also I am a newbie to it. After some time, I configured Django in Nginx with the help of the gunicorn service, But suddenly gunicorn service stopped with an unrecognized argument error (WSGI). enter image description here and my gunicorn service file: [Unit] Description=gunicorn daemon After=network.target [Service] User=user Group=nginx WorkingDirectory=/home/websitehg/websites/qatarfactory/qf_project ExecStart=/home/websitehg/websites/qatarfactory/qf_env/bin/gunicorn --workers 3 --reload true --bind unix:/home/websitehg/websites/qatarfactory/qf_project/qf_project.sock qf_project.wsgi:app [Install] WantedBy=multi-user.target I don't know what's wrong with it -
Error while install mysqlclient in Ubuntu 20.04 (WSL)
I'm using Ubuntu 20.04 in WSL, using conda virtual environment with python 3.8. I need to create a django project using MySql but I have a problem installing mysqlclient. Specifically, when I run: pip install mysqlclient I get the following error: WARNING: Retrying (Retry(total=4, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8c1955ea90>: Failed to establish a new connection: [Errno -2] Name or service not known')': /simple/mysqlclient/ WARNING: Retrying (Retry(total=3, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8c19559670>: Failed to establish a new connection: [Errno -2] Name or service not known')': /simple/mysqlclient/ WARNING: Retrying (Retry(total=2, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8c195597c0>: Failed to establish a new connection: [Errno -2] Name or service not known')': /simple/mysqlclient/ WARNING: Retrying (Retry(total=1, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8c19559fa0>: Failed to establish a new connection: [Errno -2] Name or service not known')': /simple/mysqlclient/ WARNING: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<pip._vendor.urllib3.connection.HTTPSConnection object at 0x7f8c19559d90>: Failed to establish a new connection: [Errno -2] Name or service not known')': /simple/mysqlclient/ ERROR: Could not find a version that satisfies the requirement mysqlclient==2.0.3 (from versions: none) … -
Migrate with database postgres fails
I aim to use postgres as default database for my django models. I am using docker-compose for the postgres and it seems to be up and running. version: '3.2' services: postgres: image: postgres:13.4 environment: POSTGRES_DB: backend_db POSTGRES_USER: postgres POSTGRES_PASSWORD: postgres volumes: - database-data:/var/lib/postgresql/data/ ports: - 5432:5432 networks: - postgres volumes: database-data: driver: local networks: postgres: driver: bridge However, when I am doing python3 manage.py migrate --database postgres I am getting the following: Operations to perform: Apply all migrations: admin, auth, authentication, authtoken, contenttypes, sessions, token_blacklist, vpp_optimization Running migrations: No migrations to apply. The problem is evident also when I am doing python3 manage.py runserver, where I am getting: Performing system checks... System check identified no issues (0 silenced). You have 31 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, authentication, authtoken, contenttypes, sessions, token_blacklist, vpp_optimization. Run 'python manage.py migrate' to apply them. April 11, 2022 - 05:32:10 Django version 3.1.7, using settings 'core.settings' Starting development server at http://127.0.0.1:8000/ Quit the server with CONTROL-C. It appears like the command python3 manage.py migrate --database postgres was not executed. Here is the settings.py part of the databases: DATABASES = { 'default': get_config( 'DATABASE_URL', 'sqlite:///' … -
How to pass response from one function to another function using ajax in django HTML?
I am trying to pass flight data which is in dictionary form and this is generated when user searches for flight and selects offer. What I want is the flight data should be passed in the url but user should not be able to read or modify it. Currently, I have passed flight data with {% for flight in response %} href="{% url 'get_detail' flight %}" {% endfor %} but it shows flight information in URL like 127.0.0.1/get_detail/{flightinfohere} . Is there any idea so that I can save this flight data for another function without passing in URL or I can hide this data or encode it? Any help would be appreciated. I tried to use AJAX, but I don't know how to pass the flight data in ajax as it is response of another views.py function. -
Reload django server on demand
I am running django development server using python manage.py runserver --noreload. In my development environment I am installing modules using pip(pip install modulename) with python code. Once installed, is it possible to reload the server even if --noreload paramater still on? -
Python - Django - cryptocurrency exchange | subscribe to wallet address and inform of deposits
I am developing a cryptocurrency exchange platform with Django. I have two critical questions: In the case of cryptocurrency deposits, Is it correct that I create a separate wallet address for every user, watch the address for every change in balance on the blockchain, and add it to my own database as a deposit? How can I watch all the wallets and be informed of every balance change? Is there a good third party that provides WebSocket service for bitcoin? -
Django Ckeditor image not showing after 1 hour in production with amazon s3 bucket
Django ckeditor image shows perfectly on local machine but not display in production with s3 bucket after 1 hour. Make s3 bucket public. But didn't solve yet. Settings are DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' AWS_ACCESS_KEY_ID = env('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = env('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = env('AWS_STORAGE_BUCKET_NAME') AWS_S3_REGION_NAME = env('AWS_S3_REGION_NAME') AWS_QUERYSTRING_AUTH = False AWS_QUERYSTRING_EXPIRE = int(env('AWS_QUERYSTRING_EXPIRE')) # for 10 years in seconds AWS_DEFAULT_ACL = 'public-read' after disappering the image when I hit the url it shows the error This XML file does not appear to have any style information associated with it. The document tree is shown below. <Error> <Code>AccessDenied</Code> <Message>Request has expired</Message> <Expires>2022-04-11T04:17:03Z</Expires> <ServerTime>2022-04-11T04:33:34Z</ServerTime> <RequestId>65579SD4M8QA0RCB</RequestId> <HostId>o4HzVND3mA0yt6oULNSXeceP1ALOTHPfToDD/I0XH+W/t9zuYRQAfdG29o+QZt8wsNaidDlnaCY=</HostId> </Error> and on cosole it shows the error also GET https://cntestbucket.s3.amazonaws.com/pranta/2022/04/11/1_zcvrri69ovmke7xgulw8ow.png?AWSAccessKeyId=AKIAYR5JG2JQDGCDJ77A&Signature=UjF9Fnr28v%2FjX3sEmbGGV8%2FsK10%3D&Expires=1649650623 403 (Forbidden) -
How to display reverse relation data in Django with unique title?
I have 2 models and I want to display the data on my template, but currently, it's reflected with my other app. I have created the dynamic title and it's working fine on live but it's conflicting with other apps. Could you please help me here? I want to display the data on ListingTech models, and a ListingTech models have multiple data of Listing so it should be displayed under the ListingTech model slug. A ListingTech model has multiple Listing so the title and description should be displayed of ListingTech. It is working fine with the current code of the views.py file but it's giving an error whenever I try to access other app URL (Error is coming: The view company.views.company_list didn't return an HttpResponse object. It returned None instead.) Please solve this issue, your help will be appreciated. Here is my models.py file... class ListingTech(models.Model): city = models.ForeignKey(City, default=None, related_name="ListTechCity", on_delete=models.CASCADE, help_text=f"Value: Select City") name = models.CharField(max_length=60, default=None, help_text=f'Type: String, Values: Enter Company Name') slug= models.SlugField(max_length=60, unique=True, help_text=f'Type: String, Values: Enter Slug') title = models.CharField(max_length=100, null=True, blank=True, verbose_name="Meta Title", help_text=f"Values: Enter ListingTech Title.") description = models.TextField(max_length=200, verbose_name="Meta Description", null=True, blank=True, help_text=f'Values: Enter ListingTech Meta Description.') listing_img = models.ImageField(upload_to="listing-image", default=None, … -
Heroku Django get error 500 when Debug = False
None of the answers from the similar questions helped me. Hello guys i will dump a bunch of the log items from "heroku logs" because i dont have enough knowladge to filter it I tried my best in finding for myself the response but i didnt get it 2022-04-11T01:38:21.468915+00:00 app[api]: Release v23 created by user kaynanrodrigues.nt@gmail.com 2022-04-11T01:38:21.894310+00:00 heroku[web.1]: Restarting 2022-04-11T01:38:22.078216+00:00 heroku[web.1]: State changed from up to starting 2022-04-11T01:38:23.440307+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2022-04-11T01:38:23.902672+00:00 heroku[web.1]: Process exited with status 0 2022-04-11T01:38:33.564199+00:00 heroku[web.1]: State changed from starting to up 2022-04-11T01:39:19.769086+00:00 heroku[router]: at=info method=GET path="/" host=quiet-ravine-74023.herokuapp.com request_id=2a1e2ccb-5923-4a73-9b51-4f172c653ccf fwd="177.124.150.24" dyno=web.1 connect=0ms service=428ms status=500 bytes=451 protocol=https 2022-04-11T01:39:19.770060+00:00 app[web.1]: 10.1.55.102 - - [10/Apr/2022:22:39:19 -0300] "GET / HTTP/1.1" 500 145 "-" "Mozilla/5.0 (Linux; Android 6.0; Nexus 5 Build/MRA58N) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/100.0.4896.75 Mobile Safari/537.36" 2022-04-11T02:13:35.839258+00:00 heroku[web.1]: Idling 2022-04-11T02:13:35.841484+00:00 heroku[web.1]: State changed from up to down 2022-04-11T02:13:36.656264+00:00 heroku[web.1]: Stopping all processes with SIGTERM 2022-04-11T02:13:37.856205+00:00 heroku[web.1]: Process exited with status 0 2022-04-11T02:29:07.000000+00:00 app[api]: Build started by user kaynanrodrigues.nt@gmail.com 2022-04-11T02:29:47.486991+00:00 app[api]: Deploy 436002d8 by user kaynanrodrigues.nt@gmail.com 2022-04-11T02:29:47.486991+00:00 app[api]: Running release v24 commands by user kaynanrodrigues.nt@gmail.com 2022-04-11T02:29:48.066613+00:00 app[api]: Starting process with command `/bin/sh -c 'if curl $HEROKU_RELEASE_LOG_STREAM --silent --connect-timeout 10 --retry 3 --retry-delay 1 >/tmp/log-stream; then 2022-04-11T02:29:48.066613+00:00 app[api]: … -
Get the encrypted value in django-fernet-fields
I use the django-fernet-fields library: class RoutePoint(models.Model): username = models.CharField(max_length=30) password = EncryptedCharField(max_length=30, null=True) When I access an encrypted field, the value of the field is automatically decrypted. p = RoutePoint.objects.all()[0] print(p.password) > mypass Is there any way I can get the encrypted value that is actually stored in the database? -
Reverse for 'user_page' with keyword arguments '{'pk': ''}' not found. I beleive my decorators are causing the issue
So my login view takes the user to the home.view but first checks user is logged in and then checks if the user is an admin or not through the decorator 'admin_only'. My user will prove to be false for this scenario (which is expected). The user is then redirected to the user_page view to which first goes through the decorator allowed_users (which will be true) and then the user_page view. My aim is to pass the primary key at login_user view to user_page view but the middle men decorators I believe are causing me problems. views.py @unauthenticated_user def login_user (request): user = None if request.method == 'POST': temp_username = request.POST.get('username') temp_password = request.POST.get('password') user = authenticate(request, username=temp_username, password=temp_password) if user is not None: login(request, user) context = {'user':user} print ('Primary key in login view = ', user.id) return redirect('home', context) else: messages.info(request, "Username or Password is incorrect!") context = {'user':user } return render(request, 'login.html', context) @login_required(login_url='login') @admin_only def home(request, pk): user = User.objects.get(id=pk) context = {'user':user} return render(request,'home.html',context) @login_required(login_url='login') @allowed_users(allowed_roles=['customer']) def user_page(request,pk): user = User.objects.get(id=pk) context = {'user':user} return render(request, 'user.html', context) urls.py #url.py path('user/<int:pk>/', views.user_page, name='user_page') path('', views.home, name='home'), decorators.py def allowed_users(allowed_roles=[]): def decorator(allow_users_view_function): def wrapper_function(request, *args, **kwargs): … -
How to store a Keras .h5 file in a Django database?
I have several Keras .h5 files that I want to store using a Django model. In the Django docs there is no model field designed for .h5 files. Is there and way I can convert it to a json and store it as that or is there another go to way for doing this? -
Qual os conhecimentos indispensáveis para um back-end pleno em python?
Qual os conhecimento indispensável para um back-end python pleno, e qual o legal saber? -
Can't create links to any Django admin templates beside index.html?
I'm trying to create a link to Django's admin/auth/user/add/ to let users create an account to login with. This is when I ran into the problem that even though setting href="{% url 'admin:index' %}" works for linking to the admin's index.html, replacing index with any other template's name doesn't work. So, I have no way of adding new accounts. -
ValueError: Field 'id' expected a number but got '<built-in function id>'; POST request redirect
When a User successfully makes a POST request to edit their own question, they are redirected to a detail page for the same question. When a subsequent GET request is sent to the PostedQuestionPage view after editing a question, the following ValueError is raised when trying retrieve an instance with get_object_or_404(): ValueError: Field 'id' expected a number but got '<built-in function id>' Why is PostedQuestionPage being passed '<built-in function id>' and not a value that is suppose to represent a question instance id? > c:\..\posts\views.py(137)get() -> question = get_object_or_404(Question, id=question_id) (Pdb) ll 134 def get(self, request, question_id): 135 import pdb; pdb.set_trace() 136 context = self.get_context_data() 137 -> question = get_object_or_404(Question, id=question_id) 138 context['question'] = question 139 return self.render_to_response(context) (Pdb) question_id '<built-in function id>' (Pdb) n ValueError: Field 'id' expected a number but got '<built-in function id>'. > c:\..\posts\views.py(137)get() -> question = get_object_or_404(Question, id=question_id) (Pdb) n --Return-- > c:\..\posts\views.py(137)get()->None -> question = get_object_or_404(Question, id=question_id) class TestPostEditQuestionPage(TestCase): '''Verify that a message is displayed to the user in the event that some aspect of the previous posted question was edited.''' @classmethod def setUpTestData(cls): cls.user = get_user_model().objects.create_user( username="OneAndOnly", password="passcoderule" ) profile = Profile.objects.create(user=cls.user) tag = Tag.objects.create(name="TagZ") question = Question.objects.create( title="This is Question Infinity", body="The … -
Django form not showing up in template
My problem is not showing up form in the Django template. I'm using python 3.7.6 Django 3.2 Here is my code .................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................................... forms.py from django import forms from tasks.models import Task, TaskType class TaskForm(forms.ModelForm): name = forms.CharField(max_length=100, required=True, widget=forms.TextInput(attrs={'class': 'form-control'})) input_image = forms.ImageField(widget=forms.FileInput( attrs={'class': 'form-control-file'})) task_type = forms.ModelChoiceField(queryset=TaskType.objects.name.all(), widget=forms.Select( attrs={'class': 'form-control'})) class Meta: model = Task fields = ['name', 'input_image', 'task_type'] view.py from django.shortcuts import render, redirect from tasks.forms import TaskForm def create_task(request): if request.method == 'POST' and 'submit-task' in request.POST: task_form = TaskForm(request.POST, request.FILES, instance=request.user) if task_form.is_valid(): task_form.save() return redirect(to='dashboard') return render(request, 'users/dashboard.html', {'task_form': task_form}) dashboard.html <form method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="modal fade" id="myModal"> <div class="modal-dialog modal-fullscreen-lg-down"> <div class="modal-content"> <!-- Modal Header --> <div class="modal-header"> <h4 class="modal-title">Upload your image</h4> <button type="button" class="btn-close" data-dismiss="modal" ></button> </div> <!-- Modal body --> <div class="modal-body"> <div class="form-group"> <label class="">Task name</label> {{task_form.name}} <div class="input-group"> <select class="custom-select" id="inputGroupSelect04"> <option selected>Choose your model</option> {{task_form.task_type}} </select> <span class="input-group-btn"> <span class="btn btn-outline-dark btn-file"> Browse… {{task_form.image_input}} </span> </span> <input type="text" class="form-control" readonly /> </div> <img id="img-upload" /> </div> </div> <!-- Modal footer --> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal" > Close </button> <button type="button" class="btn btn-primary" name="submit-task"> Save changes </button> </div> </div> </div> </div> </form> So, … -
Failed to load resource: net::ERR_INCOMPLETE_CHUNKED_ENCODING in Django deployed to Heroku
How to fix this error? I have set a server-sent event that sends data only if there is new data in the database to the frontend. but every minute it keeps on sending data even though there is no new data in the database. This problem is not present during development, but when deployed to Heroku this error shows. views.py def event_stream(): initial_data = "" while True: deposit_records = Deposit.objects.filter().values('date').order_by( '-id').annotate(bottles=Sum('number_of_bottles'), credits=Sum('credits_earned'), not_bottle=Sum('not_bottle')) bottle = Deposit.objects.aggregate(Sum('number_of_bottles'))[ 'number_of_bottles__sum'] # deposit_records = Deposit.objects.order_by( # "-id").values("number_of_bottles", "credits_earned", "date") data = json.dumps(list(deposit_records) + list(str(bottle)), cls=DjangoJSONEncoder) # print(data) if not initial_data == data: yield "\ndata: {}\n\n".format(data) initial_data = data time.sleep(1) def stream(request): response = StreamingHttpResponse(event_stream()) response['Content-Type'] = 'text/event-stream' return response JS var eventSource = new EventSource("{% url 'stream' %}") eventSource.onopen = function(){ console.log('yay its open'); } eventSource.onmessage = function(e){ if(!e){ eventSource.end() } else{ console.log(e) var final_data = JSON.parse(e.data) } eventSource.onerror = function(e) { console.log(`error ${e}`); } -
InvalidArgument when calling the PutObject operation: None
i try to use boto3 and django-storages for media storage when i try to upload image its throws me an error like this: ClientError at /admin/myschool/secondary/add/ An error occurred (InvalidArgument) when calling the PutObject operation: None even in my admin panel. i'm a begineer i don't know how this work this is my first time using AWS after i switch from cloudinary to aws S3. i have setup everything as you can see here in my settings.py file: AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY '' AWS_STORAGE_BUCKET_NAME '' AWS_S3_FILE_OVERWRITE = 'False' AWS_DEFAULT_ACL = 'None' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' this is my Cross-origin resource sharing (CORS): [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "GET", "HEAD" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [], "MaxAgeSeconds": 3000 } ] Access control list (ACL): Grantee Objects Bucket ACL Bucket owner (your AWS account) Canonical ID: '' List Write Read Write Edit Object Ownership ACLs disabled (recommended) is anybody who can help me please ? -
Django Can't CSS / customize image
I want to center an image and it doesn't work. I cant customize the image at all with my CSS files. home.html {% load static %} <link rel="stylesheet" href="{% static 'stylehome.css' %}"> <div class="testimage"> <img src="{% static 'images/bottrade.jpg'%}" alt="erar"> </div> stylehome.css .testimage { display: block; margin-left: auto; margin-right: auto; width: 50%; } -
Hello, I am completely lost with this error: ModuleNotFoundError: No module named 'django.contrib.authpolls'
I know that this is not really how stackoverflow is supposed to be used and I apologize if I wasted your time with this question. But I keep getting this error when I try to run my django applications on pythonanywhere and I do not have any idea why. I do not recall using such thing as django.contrib.authpolls or at least I cannot find it anywhere in my settings.py or any other file. I found, that a missing comma in the INSTALLED APPS in the settings.py file could be the source of this issue, but i checked it and thats not my case. So please could you guys help me out. Thank you so much in advance. Traceback (most recent call last): File "/home/jaca2288/django_projects/mysite/manage.py", line 22, in <module> main() File "/home/jaca2288/django_projects/mysite/manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/jaca2288/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/jaca2288/.local/lib/python3.9/site-packages/django/core/management/__init__.py", line 395, in execute django.setup() File "/home/jaca2288/.local/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/home/jaca2288/.local/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/home/jaca2288/.local/lib/python3.9/site-packages/django/apps/config.py", line 212, in create mod = import_module(mod_path) File "/usr/local/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File … -
Django + mod_wsgi + apache2 : Module not found
im trying to host my django webapp on a VPS where I have root access. I followed the official django mod_wsgi apache tutorial and its almost working.. but my virtual env don't work because wsgi can't find django module. I've done a lot a research on this topic but my soul is slowly dying right now. help. I don't understand why it don't work, I've tested my venv at /home/env by doing an import django and it works... Here is my apache virtualHost conf file : ServerAdmin admin@elytrasfr.localhost ServerName 127.0.1.1 ServerAlias localhost DocumentRoot /var/www/elytras ErrorLog /var/www/elytras/error.log CustomLog /var/www/elytras/access.log combined Alias /static /var/www/elytras/static <Directory /var/www/elytras/ecommerce> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /var/www/elytras/ecommerce/wsgi.py process-group=elytras WSGIDaemonProcess elytras python-home=/home/env python-path=/var/www/elytras WSGIProcessGroup elytras </VirtualHost> The error I got (on firefox): Internal Server Error The server encountered an internal error or misconfiguration and was unable to complete your request. Please contact the server administrator at admin@elytrasfr.localhost to inform them of the time this error occurred, and the actions you performed just before this error. More information about this error may be available in the server error log. my logs : [Sun Apr 10 22:04:45.615774 2022] [wsgi:info] [pid 1088:tid 139742691768064] [remote 92.154.56.19:60814] mod_wsgi (pid=1088, … -
assertRedirects(response) triggers NoReverseMatch error;
I'm testing a scenario where a User successfully edits an answer in response to a question. Once the answer is edited, the user is redirected to a listing page with the question and all answers posted. The problem being encountered is that the user is not being redirected; a NoReverseMatch error is being raised: Reverse for 'question' with keyword arguments '{'id': 1}' not found. 1 pattern(s) tried: ['questions/(?P<question_id>[^/]+)/$'] self.assertRedirects() is trigger this error within in the test. Yet, I cannot pinpoint why it's being raised when question_id is being passed into the reverse("posts:question", kwargs={"question_id": answer.question.id}) call of assertRedirects()? It's saying that the key is 'id'? class TestEditInstanceAnswerPage(TestCase): '''Verify that a User who has posted an Answer to a given Question has the ability to edit their answer.''' @classmethod def setUpTestData(cls): cls.user = get_user_model().objects.create_user("TestUser") cls.profile = Profile.objects.create(user=cls.user) cls.answer_user = get_user_model().objects.create_user("TheAnswer") cls.answer_profile = Profile.objects.create(user=cls.answer_user) cls.tag = Tag.objects.create(name="Tag1") cls.question = Question.objects.create( title="How do I get an answer to my post", body="This is the content that elaborates on the title that the user provided", profile=cls.profile ) cls.question.tags.add(cls.tag) cls.answer = Answer.objects.create( body="This is an answer in response to 'How do I get an answer to my post'", question=cls.question, profile=cls.answer_profile ) cls.data = { "body": "This … -
django-elasticsearch-dsl Object of type 'AttrList' is not JSON serializable
I have a Django application where I need to implement a search system, for this application, elasticsearch seems to be the most suitable, but I came across a problem that I can't solve. I have in postgres a table with a column of type jsonb similar to this: [ { "act": 1900, "max": 2850, "min": 2850, "tgt": 2850, "desc": "L - Durchsatz (kg/h)", "name": "L - Durchsatz (kg/h)", "unit": "kg/h", "color": "red", "ordering": 1, "monitoring": true }, { "act": 283, "max": 425, "min": 425, "tgt": 425, "desc": "L - Siebbandgeschwindigkeit (m/min)", "name": "L - Siebbandgeschwindigkeit (m/min)", "unit": "m/min", "color": "red", "ordering": 2, "monitoring": true }, ... ] Django Model: class Collect(models.Model): recipe = models.ForeignKey(RecipeSentHistory, on_delete=models.CASCADE, null=True, default='1') general_info = models.JSONField(default=dict) record = models.JSONField(default=dict) justify = models.CharField(max_length=255, default='*') automatic = models.BooleanField(default=False) user = models.CharField(max_length=255, default='*') user_job_position = models.CharField(max_length=255, default='*') timestamp = models.DateTimeField(default=timezone.now) def __str__(self): return self.recipe.machine.name My serializer: class MyCollectSerializer(serializers.ModelSerializer): class Meta: model = Collect fields = [ 'justify', 'record', 'user', 'user_job_position', 'timestamp', 'automatic', 'recipe_id', 'general_info', ] read_only = True My documents.py: from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry from mpa.models import Collect @registry.register_document class CollectDocument(Document): general_info = fields.ObjectField( properties={ 'batch': fields.TextField(), 'machine': fields.TextField(), 'recipe_cep': fields.TextField(), 'recipe_mpa': fields.TextField(), 'fabrication_order': … -
Django: How to store certain objects of a model in another model
I am currently trying to create a user profile that will contain the courses that the user chose. Currently, the user profile model is UserProfile and the courses are objects of Course. I've tried using the ManyToMany field but that just results in UserProfile storing all courses in Course. The two models are stored in different apps. models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(default="default.jpg", upload_to="profile_pics") courses = models.ManyToManyField("course.Course", blank=True, default=None, related_name = "courses") def __str__(self): return f"{self.user.username} Profile" Any help is appreciated. Thanks.