Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Celery can't connect to Heroku Redis
Can someone help me to fixed this error, Im trying to used for the first time Django Celery + Heroku Redis but I got an error when I run " celery -A (project) worker -l info". Thank you Im using : redis==3.5.3, Django==2.1.7, python==3.7.7, celery==5.0.5 This is the error: ERROR/MainProcess] consumer: Cannot connect to redis://:**@ec2-3-213-108-16.compute-1.amazonaws.com:18480//: Error while reading from socket: (54, 'Connection reset by peer'). Trying again in 2.00 seconds... (1/100) Setting -
How to use prefetch_related and select_related at the same time in Django?
This is a part of models.py in my django app. class User(models.Model): user_id = models.AutoField(primary_key=True) uuid = models.CharField(max_length=32) name = models.CharField(max_length=10) phone = models.CharField(max_length=20) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class UserForm(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE, primary_key=True) access_info = models.CharField(max_length=250) etc_comment = models.CharField(max_length=250) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class UserAddress(models.Model): user_address_id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE) address_name = models.CharField(max_length=100) address_name_detail = models.CharField(max_length=100) address_type = models.CharField(max_length=11) address_coord = models.PointField() created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) I am using MySQL database and linked it to django database. My question is how to get all three data together just in a single query. As I know, I have to use django's prefetch_related or select_related method to get them together like this objs = User.objects.select_related('userform').get(user_id=1) But, what about getting them from three model classes? Please, let me know if you have any idea. -
Convert SQL Query to Django ORM
I am new to Django ORM and am struggling to convert the following query into ORM. Appreciate any help/guidance. The dates/times are not in a particular order. Thanks in advance SQL Query: ''' SELECT A.Person_id, A.Dept_id, A.score_date, A.score FROM borrowerdeptscore AS A INNER JOIN ( SELECT Person_id, Dept_id, MAX(score_date) AS Max_date FROM borrowerdeptscore GROUP BY Person_id, Dept_id ) AS B ON A.Person_id = B.Person_id AND A.Dept_id = B.Dept_id AND A.score_date = B.Max_date ''' The Django Class: ''' class BorrowerDeptScore (models.Model): Person= models.ForeignKey('Person') Dept= models.ForeignKey('Dept') score_date = models.DateTimeField()<br/> score = models.DecimalField()<br/> ''' The closest I got to an answer was the following, however I cannot add the "score" to the queryset. Not sure what I am missing or forgot here. latestscores = BorrowerDeptScore .objects.values('Person_id', 'Dept_id').annotate(max_date=Max('score_date')) -
Combined Returns in Python Function Based Views Django
I'm currently building a website with Django and I've gotten to a point where I need to print data on the screen(ListView) and update(UpdateView) data on the same page(template). From what I've found I cant do this easily with the Django generic views so I rewrote my view as a function-based view. This current piece of code updates what I need perfectly with some changes to the HTML. def DocPostNewView(request, pk): context = {} obj = get_object_or_404(DocPost, id=pk) form = GeeksForm(request.POST or None, instance=obj) if form.is_valid(): form.save() return HttpResponseRedirect("/" + id) context["form"] = form posts = DocPost.objects.all() return render(request, "my_app/use_template.html", context) ... And this following piece of code lists objects perfectly with some changes to the HTML. def DocPostNewView(request, pk): context = {} obj = get_object_or_404(DocPost, id=pk) form = GeeksForm(request.POST or None, instance=obj) if form.is_valid(): form.save() return HttpResponseRedirect("/" + id) context["form"] = form posts = DocPost.objects.all() return render(request, 'my_app/use_template.html', context={'posts': posts}) I just need to combine these and the only real difference is the return command at the bottom of both(the same) functions. HOW CAN I COMBINE THE RETURNS SO I CAN LIST DATA AND UPDATE DATA ON THE SAME PAGE??? Thanks -
How to escape MultipleObjectsReturned with django-import-export in django
Based on this here that was sufficiently answered and which helped me improve a lot, I have a problem getting the system to detect the streams in a particular klass. When I upload, if there are same stream names in different classes for the same school, the system returns MultipleObjectsReturned. When I reduce[edit] the streams so that it is 1 different stream name for every class, it works. How can I enable it to take in uploaded data whereby it is the same school with classes and the classes being 4 have the same name for their streams, i.e Form 1 has streams Eagle and Hawk, Form 2 has streams Eagle, Hawk, and same for Forms 3 and 4???? Any help will be highly appreciated. Here are the models, resources and views. Resources.py class KlassForeignKeyWidget(ForeignKeyWidget): def __init__(self,school_id,model = 'Klass',field="name",*args,**kwargs,): super().__init__(model=model, field=field, *args, **kwargs) self.school_id = school_id def get_queryset(self, value, row, *args, **kwargs): return Klass.objects.filter(school_id=self.school_id) class StreamForeignKeyWidget(ForeignKeyWidget): def __init__(self,school_id,model = 'Stream',field="name",*args,**kwargs,): super().__init__(model=model, field=field, *args, **kwargs) self.school_id = school_id def get_queryset(self, value, row, *args, **kwargs): return Stream.objects.filter(klass__school_id=self.school_id) class ImportStudentsResource(resources.ModelResource): def __init__(self, school_id,*args, **kwargs): super().__init__() self.school_id = school_id self.fields["klass"] = fields.Field(attribute="klass",column_name="class",widget=KlassForeignKeyWidget(school_id,),) self.fields["stream"] = fields.Field(attribute="stream",column_name="stream",widget=StreamForeignKeyWidget(school_id,),) def before_save_instance(self, instance, using_transactions, dry_run): instance.school_id = self.school_id class … -
Django 404 error even though I've created the path and view
I'm just beginning to learn Django. I've created a simple web sub-app called 'flavo' inside of another one called 'djangoTest' When I run http://127.0.0.1:8000/flavo it correctly displays Hello, World! then when I run http://127.0.0.1:8000/flavo/a it should show Hello, a! But instead I get: Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/flavo/a Using the URLconf defined in testDjango.urls, Django tried these URL patterns, in this order: admin/ flavo [name='index0'] flavo a [name='a'] The current path, flavo/a, didn’t match any of these. in testDjango/hello/views.py I have from django.http import HttpResponse from django.shortcuts import render def index0(request): return HttpResponse("Hello, world!") def a(request): return HttpResponse("Hello, a!") In testDjango/flavo/url/py I have from django.urls import path from . import views urlpatterns = [ path("", views.index0, name="index0"), path("a", views.a, name="a"), ] The only other file I've changed is , testDjango/testDjango/urls.py" from django.contrib import admin from django.urls import include, path urlpatterns = [ path('admin/', admin.site.urls), path('flavo', include("flavo.urls")), ] I'm confused why I can't access http://127.0.0.1:8000/flavo/a -
Djano. Getting "ConnectionRefusedError: [Errno 111" when trying to send an email
Description I am trying to send an email using django.core.mail.send_email() and constantly getting the ConnectionRefusedError: [Errno 111] Connection refused with the following traceback: Traceback (most recent call last): File "<console>", line 1, in <module> File "/home/EmilKadermetov/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/mail/__init__.py", line 61, in send_mail return mail.send() File "/home/EmilKadermetov/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/mail/message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) File "/home/EmilKadermetov/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 102, in send_messages new_conn_created = self.open() File "/home/EmilKadermetov/.virtualenvs/myvirtualenv/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 62, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/usr/lib/python3.8/smtplib.py", line 253, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python3.8/smtplib.py", line 339, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python3.8/smtplib.py", line 308, in _get_socket return socket.create_connection((host, port), timeout, File "/usr/lib/python3.8/socket.py", line 807, in create_connection raise err File "/usr/lib/python3.8/socket.py", line 796, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused My SMTP configurations in the settings.py: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOSTS = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'my_email@gmail.com' EMAIL_HOST_PASSWORD = 'my_passwod' Additional "Less security app access" in my google account is turned on. I can successfully connect to the smtp.gmail.com via telnet from the same machine. Using another smtp host changes nothing. I use: Django3.1.6 | Python 3.8.5 | Linux Mint 20.1 -
Sending Mail configuration in django
I am facing a problem when trying to test sending a message from the django app, but I get this error message : SMTPAuthenticationError at /accounts/contact_us (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials f13sm16175910wrt.86 - gsmtp') And I looked for all the possible solutions like : Enable two-step verification , Enable less secure app access settings . But it was in vain and did not work successfully. Could anyone help please ? this is my settings : EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'myname@gmail.com' EMAIL_HOST_PASSWORD = '****************' EMAIL_USE_TLS = True EMAIL_PORT = '587' this is my views.py: def contact_us(requset): subject = requset.POST.get('subject', '') message = requset.POST.get('message', '') from_email = requset.POST.get('from_email', '') send_mail(subject, message, from_email, ['myname@gmail.com']) return render( requset , 'accounts/contact_us.html' ) this is my contact_us.html: <div class="contact_form"> <form name="contact_form" action="" method="POST"> {% csrf_token %} <p><input type="text" name="subject" class="name" placeholder="subject" required></p> <p><textarea name="message" class="message" placeholder="message" required></textare></p> <p><input type="text" name="from_email" class="email" placeholder="email" required></p> <p><input type="submit" value="sent" class="submit_btn"></p> </form> </div> -
How to return access token to frontend after socialAuth in django
I have implemented social auth using django social auth. Now I need to return the access token to frontend(react), so that I can pass it in further requests and identify the user. I tried modifying the LoginView, but it didn't work as expected. Can someone suggest a way for this? urls.py url(r'^login/$', auth_views.LoginView.as_view(), name='login'), url(r'^logout/$', auth_views.LogoutView.as_view(), name='logout'), url(r'^oauth/', include('social_django.urls', namespace='social')), path('', include('testapp.urls')), I have not made any changes to the social_auth pipeline. -
How do I reverse One To Many (ForeignKey) relation?
I have two models File and Shared, I want to add many collaborators to one File not one collaborators to many File, here are my models: class File(models.Model): slug = models.SlugField(primary_key=True) file = models.FileField(upload_to=upload_file_to) owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) collaborators = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, on_delete=models.SET_NULL) class Shared(models.Model): file = models.ForeignKey('File', on_delete=models.CASCADE) code = models.CharField(max_length=15, unique=True) -
Django app cannot find base.html located inside the project's templates - Django 3.2
I am new to Django even though I have done web development using ASP.NET before. I created a Django project to perform User Management following this tutorial - https://realpython.com/django-user-management/. I created an app called users inside the project lipreading_website using the command - python manage.py startapp users. I then created the templates folder inside this app - users/templates and placed a base.html file in users/templates and created the rest of the HTML files in users/templates/users/. I then referenced the base.html from inside the HTML files created inside users/templates/users using {% extends "base.html" %}. I then followed this tutorial - https://www.youtube.com/watch?v=vXXfXRf2S4M&t=2s&ab_channel=Pyplane to add a few more apps - quizzes, results, questions and adding a new base.html file in the project's template -> lipreading_website/templates/base.html. I made the following changes to the settings.py file - TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, 'templates') ], 'APP_DIRS': True, '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', ], }, }, ] and proceeded to extend this file instead from one of the application's HTML files defined in quizzes/templates/quizzes/main.html. I want to extend the base.html in the project root templates folder, but it's still referencing the base.html created inside the users/templates/ folder. -
Override Django model field get_prep_value method
When getting a ValueError from a ForeignKey field in Django, the exception returns the response "Field ... expected a a number but got ..." using the field name. I'd like to change this exception to use the verbose_name if it exists, and the field name if it does not. How can I override this exception for all ForeignKey fields? Line 1818 in https://github.com/django/django/blob/main/django/db/models/fields/__init__.py def get_prep_value(self, value): value = super().get_prep_value(value) if value is None: return None try: return int(value) except (TypeError, ValueError) as e: raise e.__class__( "Field '%s' expected a number but got %r." % (self.name, value), ) from e -
Best way to struct data to Plot a chart in Django
In order to plot a chart with Highcharts I have to structure a queryset in a list of dictionaries that have to look like the following: [{ name: 'Europe', data: [{ name: 'Germany', value: 767.1 }, { name: "Cyprus", value: 7.2 }] }, { name: 'Africa', data: [{ name: "Senegal", value: 8.2 }, { name: "Ghana", value: 14.1 }] }] The following code is the way I tried. The data is structured as requested and the graph is plotted good, but the final list (listsocios) is missing some values and repeating another ones. I guess it is memory issue. Whats your thoughs? Whats would be the more effecient way to struct? class GraphSociosProvinciasView(TemplateView): template_name = 'socios/socios_prov_graph.html' def get_context_data(self,*args, **kwargs): context = super(GraphSociosProvinciasView, self).get_context_data(*args,**kwargs) listsocios=[] listsocprov=[] #Por cada provincia guardo los socios for n in range(1,25): sociosp=Socios.objects.all().filter(provincia=n) TotalSocios=sociosp.count() listsocprov.clear() if TotalSocios!=0: for socp in sociosp: listsocprov.append({'name': socp.apellido,'value': socp.numero_socio},) nombre_provincia=socp.get_provincia_display() listsocios.append({'name':nombre_provincia,'data':listsocprov}) print(listsocios) context={ 'sociosprov': listsocios, } return context -
Deploying django 2.2 app on ubuntu 20.04 LTS
I wrote my app using python 3.6 before. Now I want deploy it on ubuntu 20.04 and default python is 3.8. After creating virtual environment when I run pip install -r requirments.txt I get errors for specific packages in terminal. Here is errors for those packages: Building wheel for cffi (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/pouya795/www/marketpine-backend/venv/bin/python -u -c 'import io, os, sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-2h487j4r/cffi_5a23efe094aa4c5dbccb0ae69bfca883/setup.py'"'"'; __file__='"'"'/tmp/pip-install-2h487j4r/cffi_5a23efe094aa4c5dbccb0ae69bfca883/setup.py'"'"';f = getattr(tokenize, '"'"'open'"'"', open)(__file__) if os.path.exists(__file__) else io.StringIO('"'"'from setuptools import setup; setup()'"'"');code = f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d /tmp/pip-wheel-2i6w3ayj cwd: /tmp/pip-install-2h487j4r/cffi_5a23efe094aa4c5dbccb0ae69bfca883/ Complete output (36 lines): running build_ext building '_cffi_backend' extension creating build/temp.linux-x86_64-3.8 creating build/temp.linux-x86_64-3.8/c x86_64-linux-gnu-gcc -pthread -Wno-unused-result -Wsign-compare -DNDEBUG -g -fwrapv -O2 -Wall -g -fstack-protector-strong -Wformat -Werror=format-security -g -fwrapv -O2 -g -fstack-protector-strong -Wformat -Werror=format-security -Wdate-time -D_FORTIFY_SOURCE=2 -fPIC -DUSE__THREAD -DHAVE_SYNC_SYNCHRONIZE -I/usr/include/ffi -I/usr/include/libffi -I/home/pouya795/www/marketpine-backend/venv/include -I/usr/include/python3.8 -c c/_cffi_backend.c -o build/temp.linux-x86_64-3.8/c/_cffi_backend.o c/_cffi_backend.c:15:10: fatal error: ffi.h: No such file or directory 15 | #include <ffi.h> | ^~~~~~~ compilation terminated. error: command 'x86_64-linux-gnu-gcc' failed with exit status 1 ---------------------------------------- ERROR: Failed building wheel for cffi Running setup.py clean for cffi Building wheel for Pillow (setup.py) ... error ERROR: Command errored out with exit status 1: command: /home/pouya795/www/marketpine-backend/venv/bin/python -u -c 'import … -
Creating a serializer that only list objects related to user
I want to make a serializer that only list Groups that the user is related to. My User model have a group field with manytomany relations to the Group model. And I want the GroupSerializer to only list the groups that the user is related to. This is my serializer now. class GroupSerializer(serializers.ModelSerializer): class Meta: model = Group fields = ('id', 'name', 'description') read_only_fields = ('id',) Anyone know how I can do this? -
How to pass values using ajax post method. Values are passed into Views. But template doesn't have values through context
//I try to post my form values using a JQuery function. Calling my View and passed the values in context. Passing the context into a template and context doesn't have any value. //This is the JQuery function bookstay() { $.ajax({ type:'POST', url:'{% url 'book' %}', headers: {'X-CSRFToken': '{{ csrf_token }}'}, data:{ stay1: $('#stay1').val(), checkin1: $('#checkin1').val(), checkout1: $('#checkout1').val(), nights1: $('#nights1').val() }, success: function (data) { alert('Data passed successfully'); window.location.href = "stay/book"; }, }) } //This is the View. def book(request): cities = City.objects.all() context = {'cities': cities} if request.method == 'POST': stay1 = request.POST['stay1'] checkin1 = request.POST['checkin1'] checkout1 = request.POST['checkout1'] nights1 = request.POST['nights1'] print(stay1, checkin1) context = {'cities': cities, 'stay1': stay1, 'checkin1': checkin1, 'checkout1': checkout1, 'nights1': nights1} return render(request, 'stay/bookstay.html', context) return render(request, 'stay/bookstay.html', context) //This is the template <div> <h1>checkin1={{checkin1}}</h1> </div> -
I get the error. NoReverseMatch at /delete_mat/11/ in one of the apps in Django
Hail Devs. I created a second app in an existing Django project. The urls.py routes in the app work fine, but the views edit_mat, update_mat and delete_mat, which access the database despite performing the action do not reload the index page. The views that I don't access the database work perfectly. No idea what else to do. Can you help? erro: NoReverseMatch at /delete_mat/11/ Reverse for 'material' not found. 'material' is not a valid view function or pattern name. Request Method: GET Request URL: http://127.0.0.1:8000/delete_mat/11/ Django Version: 3.2 Exception Type: NoReverseMatch Exception Value: Reverse for 'material' not found. 'material' is not a valid view function or pattern name. Exception Location: C:\webcq\venv\lib\site-packages\django\urls\resolvers.py, line 694, in _reverse_with_prefix Python Executable: C:\webcq\venv\Scripts\python.exe Python Version: 3.8.6 Python Path: ['C:\\webcq', 'C:\\Users\\Lewis\\AppData\\Local\\Programs\\Python\\Python38\\python38.zip', 'C:\\Users\\Lewis\\\AppData\\Local\\Programs\\Python\\Python38\\DLLs', 'C:\\Users\\Lewis\\\AppData\\Local\\Programs\\Python\\Python38\\lib', 'C:\\Users\\Lewis\\\AppData\\Local\\Programs\\Python\\Python38', 'C:\\webcq\\venv', 'C:\\webcq\\venv\\lib\\site-packages'] Server time: Mon, 17 May 2021 21:27:15 +0000 Traceback Switch to copy-and-paste view C:\webcq\venv\lib\site-packages\django\core\handlers\exception.py, line 47, in inner response = get_response(request) … ▶ Local vars C:\webcq\venv\lib\site-packages\django\core\handlers\base.py, line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) … ▶ Local vars C:\webcq\materiais\views.py, line 49, in delete_mat return redirect('material') … ▶ Local vars view.py app from django.shortcuts import render, redirect from materiais.models import EspecComponentes, Componente, Codigo, EspecMaterial from materiais.forms import EspecComponentesForm # Create … -
Why Celery 5 require djcelery?
I was implementing what the celery documentation says. celery.py import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'proj.settings') broker = 'sqla+postgresql://user:pass@localhost/db' app = Celery('proj', broker=broker) # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings', namespace='CELERY') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print(f'Request: {self.request!r}') Error that I am facing. [2021-05-18 03:21:29,974: CRITICAL/MainProcess] Unrecoverable error: ModuleNotFoundError("No module named 'djcelery'") Traceback (most recent call last): File "/Users/proj/venv/lib/python3.9/site-packages/celery/app/base.py", line 1211, in backend return self._local.backend AttributeError: '_thread._local' object has no attribute 'backend' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Users/proj/venv/lib/python3.9/site-packages/celery/worker/worker.py", line 203, in start self.blueprint.start(self) File "/Users/proj/venv/lib/python3.9/site-packages/celery/bootsteps.py", line 112, in start self.on_start() File "/Users/proj/venv/lib/python3.9/site-packages/celery/apps/worker.py", line 136, in on_start self.emit_banner() File "/Users/proj/venv/lib/python3.9/site-packages/celery/apps/worker.py", line 170, in emit_banner ' \n', self.startup_info(artlines=not use_image))), File "/Users/proj/venv/lib/python3.9/site-packages/celery/apps/worker.py", line 232, in startup_info results=self.app.backend.as_uri(), File "/Users/proj/venv/lib/python3.9/site-packages/celery/app/base.py", line 1213, in backend self._local.backend = new_backend = self._get_backend() File "/Users/proj/venv/lib/python3.9/site-packages/celery/app/base.py", line 916, in _get_backend backend, url = backends.by_url( File "/Users/proj/venv/lib/python3.9/site-packages/celery/app/backends.py", line 70, in by_url return … -
Anonymous user for settings.AUTH_USER_MODEL in django model
Both registered and anonymous users can upload files. The UserFile model has an owner attribute connected to the AUTH_USER_MODEL. Thus, for registered users, when creating a new UserFile object, the owner attribute references self.request.user. Ideally, each file upload by an anonymous user would be accessible only by that anonymous user, and only for the length of time that the anonymous user's browser session is active. How can the owner attribute of UserFile be set such that the anonymous user can be referenced with it later? model: class UserFile(models.Model): owner = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete = models.CASCADE, blank = False, null = False) file = models.FileField( upload_to = 'uploads/', validators = [ FileExtensionValidator(allowed_extensions = ['txt', 'doc', 'odt']) ] ) For example (pseudocode): UserFile.objects.filter(owner__exact = <anonymous user tied to browser session XYZ>) As an aside, in the future, ideally the anonymous user could login or register, at which point the owner attribute on any UserFile they own would be set to that registered user. -
GET endpoint with comma separated UUIDs Django
I am new to Django. I am trying to add endpoint which gives user details back, with provided user ids. The endpoint url should look like /users/?id=user1_id,user2_id... I already have a url and viewset for /users/. However I want to add a new one. I am able to write a code in viewset with get_queryset() which give me expected result. But I am not sure how do I add a url pattern for /users/?id=user1_id,user2_id... request, which should call the new viewset. Can anynone help me with understand what can I use here? -
Error with Django application on Cloud Run using Cloud SQL PostgreSQL DB - cannot connect to database
I have this Django project on Google Cloud on Cloud Run. It is supposed to connect to the Cloud SQL PostgreSQL database and work, but it doesn't. Here is the database part of settings.py (I have removed the private data): DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'db', 'USER': 'user', 'PASSWORD': 'password', 'HOST': '/cloudsql/project:europe-west4:instance', 'PORT': '5432', } } However, when I try to do anything database-related (for example, log in), it throws the error OperationalError at /accounts/login/ could not connect to server: No such file or directory Is the server running locally and accepting connections on Unix domain socket "/cloudsql/*project*:europe-west4:*instance*/.s.PGSQL.5432"? If I remove the /cloudsql/ from HOST it gives the error OperationalError at /accounts/login/ could not translate host name "*project*:europe-west4:*instance*" to address: Name or service not known When I use the Cloud SQL proxy exe to test on my local computer it works. However, when I deploy it to Cloud Run it doesn't. -
Django show me an incorrect date due to time zone
I have a model in django that stores datetime fields: class Trip(models.Model): departureDate=models.DateTimeField() arrivalDate=models.DateTimeField() duration=models.IntegerField() #in seconds price=models.FloatField() I have introduced this datetime: 2021-05-18 12:29:00+02:00 2021-05-18 13:19:00+02:00. When I show it in the view, I see hour and minute 11:19. I have this in settings: LANGUAGE_CODE = 'en-us' TIME_ZONE = 'UTC' USE_I18N = True USE_L10N = True USE_TZ = True I need to show hour and minute 13:19, but I don`t want to put UTC=False. Thank you. -
where to find graphql graphene django api tutorial for basic
I have Django jwt script which is for graphene and when I write this installed backend creates user but I don't understand how to make registration form to fill field and send like this any small explained or documentation cant find ? thanks mutation { register( email: "email", username: "user", password1: "1234f56super", password2: "1234f56super", ) { success, errors, token, refreshToken } } -
Django Pillow Shrink Image AWS ignore Jpeg
This is an image shrinker from django import forms from .models import Card from django.core.files.storage import default_storage as storage from PIL import Image class CardForm(forms.ModelForm): class Meta: model = CARD fields = ('photo1',......) def save(self, *args, **kwargs): card = super(cardForm, self).save() image = Image.open(card.photo1) storage_path = storage.open(card.photo1.name, "wb") image.save(storage_path, "jpeg", quality=10, optimize=True) # set to png or aws ignores the code storage_path.close() return card It seems AWS does not accept jpeg in the above code, it is ignored in AWS(eg file size and quality won't change), But works locally, It's so weird, Why? And if i change it to storage_path, "png", then it works, But if i set it to png, Pillow would double the size of that png file, Which is also weird since i'm building a size shrinker and set only a 10th of it's original quality, I also prefer not to crop the image, what are my opinions? -
I'm getting an odd error when testing models
I have two models I am trying to write some tests around but getting an error ONLY when the 2nd test stub is added. Error Creating test database for alias 'default'... System check identified no issues (0 silenced). ..E ====================================================================== ERROR: test_project_details (projects.tests.ModelTest) ---------------------------------------------------------------------- Traceback (most recent call last): File "/Users/chriscummings/Desktop/avenue/projects/tests.py", line 27, in test_project_details project = Project.objects.get(pk=1) File "/Users/chriscummings/.local/share/virtualenvs/avenue-5F5WKxqz/lib/python3.8/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/chriscummings/.local/share/virtualenvs/avenue-5F5WKxqz/lib/python3.8/site-packages/django/db/models/query.py", line 435, in get raise self.model.DoesNotExist( projects.models.Project.DoesNotExist: Project matching query does not exist. ---------------------------------------------------------------------- Ran 3 tests in 0.292s Tests from django.test import TestCase from .models import Project, Parcel class ModelTest(TestCase): def setUp(self): self.project_details = { 'code': 'P0023213', 'state': 'SC', 'county': 'Lexington/Richland', 'description': 'A road widening.' } self.project = Project(**self.project_details) self.project.save() self.parcel_details = { 'code': '00342-34-244', 'owner': 'John Smith Inc.', 'site_address': '123 Main St', 'mailing_address': 'P.O. Box 42353' } self.parcel = Parcel(**self.parcel_details) self.parcel.save() def test_project_details(self): project = Project.objects.get(pk=1) self.assertEqual(project.code, self.project_details['code']) self.assertEqual(project.state, self.project_details['state']) self.assertEqual(project.county, self.project_details['county']) self.assertEqual(project.description, self.project_details['description']) print(project.description) # Prints fine if I comment out the next test. def test_parcel_details(self): # Commenting this out makes error go away. self.assertEqual(0,0) Models from django.db import models from django.contrib.auth import get_user_model from django.urls import reverse class Project(models.Model): code = models.CharField(max_length=50) state = models.CharField(max_length=4) county …