Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use annotate and KeyTextTransform and KeyTransform to extract first element of nested array?
I am using Django 2.2 and postgres I have a jsonb field called actions And this is test value actions={ "accept": [ { "id": 123, # some random action id "created": "{:%Y-%m-%dT%H:%M:%S.%f%z}".format(datetime.now()), "user_id": 247, # some random user id } ] }, SO I want to use values_list and annotate. I do not know how to just get the actions.accept.0.created WHat I tried .annotate(first_accept=KeyTextTransform(0, KeyTextTransform("accept", "quotation__actions"))) This fails. I get the error django.db.utils.DataError: invalid input syntax for integer: "accept" LINE 1: ...te_type", ("sometable"."actions" #>> ARRAY['accept',0.. .annotate(accept_actions=KeyTextTransform("accept", "quotation__actions")) This works but it gives me '[{"id": 123, "created": "2020-10-16T12:28:16.452071", "user_id": 247}]' as a string. I can subsequently parse that string yes, but I prefer to directly access the created of the first element of the array. How do I do that? -
installing django-rest-knox with Anaconda Env
I am new to django. Trying to install django-rest-knox into anaconda env but its not working. can you please let me know the right command to install it. Thank you. -
Configure postgres database on a docker-compose first build for "background_tasks" use
I have a Django project that works great. The database is not registered in the repository. So when I do a docker-compose up from scratch, the project can't find the tables corresponding to "background tasks"... Task is refered in urls.py por immediate read on django project start. What would be the way to launch the project without previously editing the code calls to this table? docker-compose: version: '3' services: db: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres - POSTGRES_HOST_AUTH_METHOD=trust ports: - "5432:5432" volumes: - ./postgres-data:/var/lib/postgresql/data web: build: . command: bash -c " python manage.py runserver 0.0.0.0:8000 & python manage.py migrate & python manage.py process_tasks" volumes: - .:/code ports: - "8000:8000" - "5555:5555" depends_on: - db Log error: db_1 | 2020-10-16 11:48:35.090 UTC [32] ERROR: relation "background_task" does not exist at character 24 db_1 | 2020-10-16 11:48:35.090 UTC [32] STATEMENT: SELECT (1) AS "a" FROM "background_task" WHERE "background_task"."verbose_name" = 'zmq_puller' LIMIT 1 db_1 | 2020-10-16 11:48:35.090 UTC [33] ERROR: relation "background_task" does not exist at character 24 db_1 | 2020-10-16 11:48:35.090 UTC [33] STATEMENT: SELECT (1) AS "a" FROM "background_task" WHERE "background_task"."verbose_name" = 'zmq_puller' LIMIT 1 web_1 | Traceback (most recent call last): web_1 | File "/usr/local/lib/python3.9/site-packages/django/db/backends/utils.py", line 84, … -
django website creates the model object but does not upload files to aws s3
i'm using a django 1.11 with Mysql im trying to but when i submit the form the object is created but no files this is only when i added aws s3 setting everything works fine when i store files locally so the problem is not in the form or the saving process also i tried to implement the same setting of aws s3 on a different website and it works fine so i think the settings for aws s3 are correct the only thing that i could not verify is the the data base the working website has a default sqlite db and the not working website has a My Sql database so is there additional steps that i have to do if im working with a non sqlite db to the aws s3 settings? this is my aws s3 settings #====== aws3 settings=============== AWS_ACCESS_KEY_ID = '**********' AWS_SECRET_ACCESS_KEY = '***************************' AWS_STORAGE_BUCKET_NAME = 'new-test-django2' AWS_S3_FILE_OVERWRITE = False AWS_DEFAULT_ACL = None DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' this is my course_db settings in settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'course_db', 'USER': 'root', 'PASSWORD': '******', 'HOST': '127.0.0.1', 'PORT': '3306', 'OPTIONS': { # Tell MySQLdb to connect with 'utf8mb4' character set 'init_command': "SET sql_mode='STRICT_TRANS_TABLES', … -
How to compare columns of a 2 different tables in Django views?
I have 2 tables Questions and Answers. 2 tables having answer column. I want to compare Questions table answer column with answers table answer column and show the result using session. Please guide me to solve this. def result(request): if request.method=="POST": user_ans = Answers.objects.get(answer=answer) ques_ans = Questions.objects.get(answer=answer) result = 0 if ques_ans == user_ans: reslut +=1 else: result -=0.33 return render(request, 'result.html', {'result': result}) else: return render(request, 'result.html') -
'ObtainAuthToken' object has no attribute 'request'
I am trying to create a Login ViewSet in django and I've used ObtainAuthToken to get the token. Here is my code snippet for this class LoginViewSet(viewsets.ViewSet): serializer_class = AuthTokenSerializer def create(self, request): return ObtainAuthToken().post(request) But it is raising the error as 'ObtainAuthToken' object has no attribute 'request' Thank you in advance. -
Error in Django while adding a table on admin page
I'm making a simple booking app in Django. I've made a model where I'll store booking data for each day of the week and tried to add a table based on it on admin page. But when I click "save", I receive an error: Traceback (most recent call last): File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\db\backends\utils.py", line 84, in _execute return self.cursor.execute(sql, params) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\db\backends\sqlite3\base.py", line 413, in execute return Database.Cursor.execute(self, query, params) The above exception (no such table: baseapp_bookingmodel) was the direct cause of the following exception: File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\core\handlers\base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\contrib\admin\options.py", line 614, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\views\decorators\cache.py", line 44, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\contrib\admin\sites.py", line 233, in inner return view(request, *args, **kwargs) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\contrib\admin\options.py", line 1653, in add_view return self.changeform_view(request, None, form_url, extra_context) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\utils\decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\utils\decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\contrib\admin\options.py", line 1534, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\contrib\admin\options.py", line 1580, in _changeform_view self.save_model(request, new_object, form, not add) File "C:\Users\katja\PycharmProjects\django\venv\lib\site-packages\django\contrib\admin\options.py", line … -
Heroku adds an extra "/checkout" in the URL when completing order with Stripe using Django
I have a small ecommerce project hosted on Heroku that I've built using Django, when clicking "complete order" on the checkout page I should be taken to the template "checkout_success" but instead I get stuck on the same page due to the URL trying to find a path with an extra "/checkout". I've posted some screenshots below to further explain. Checkout app URLS.py: from django.urls import path from . import views from .webhooks import webhook urlpatterns = [ path('', views.checkout, name='checkout'), path('checkout_success/<order_number>', views.checkout_success, name='checkout_success'), path('cache_checkout_data/', views.cache_checkout_data, name='cache_checkout_data'), path('wh/', webhook, name='webhook'), ] Heroku Logs Error: **notice the extra "/checkout" in the POST URL. Same in the browser console URL I've tried an array things from adding and taking away "/" in my settings.py file and other URL paths. I'm sure this is something im overlooking but i've been stuck with this bug for days now. If anyone could help that would be great! And if any additional info is needed i'll be happy to provide. Thanks! -
Returned a template response with no `template_name` attribute set on either the view or response (drf-yasg2)
I setup everything as per the docs of drf-yasg2 but I'm getting this error and I can't find whats causing it. I went through the docs and there is nothing I can use from there. It looks like every response is falling back to the TemplateHTMLRenderer instead of using drf-yasg2 ReDoc or SwaggerUI renderers. def render(self, swagger, accepted_media_type=None, renderer_context=None): if not isinstance(swagger, Swagger): # pragma: no cover return TemplateHTMLRenderer().render( swagger, accepted_media_type, renderer_context ) self.set_context(renderer_context, swagger) return render_to_string( self.template, renderer_context, renderer_context["request"] ) This condition will never return false if not isinstance(swagger, Swagger): because the Response class from djangorestgramework (response.py) is calling this method with the self.data instead of a rendered as a parameter: ret = renderer.render(self.data, accepted_media_type, context) I have no idea what I'm doing wrong here. In my project I use: drf-yasg2==1.18.5 djangorestframework==3.8.0 Django==2.0.1 urls.py from rest_framework import permissions from drf_yasg2.views import get_schema_view from drf_yasg2 import openapi schema_view = get_schema_view( openapi.Info( title="Snippets API", default_version='v1', description="Test description", ), public=True, permission_classes=(permissions.AllowAny,), ) urlpatterns = [ url(r'^swagger(?P<format>\.json|\.yaml)$', schema_view.without_ui(cache_timeout=0), name='schema-json'), url(r'^swagger/$', schema_view.with_ui('swagger', cache_timeout=0), name='schema-swagger-ui'), path('redoc/', schema_view.with_ui('redoc', cache_timeout=0), name='schema-redoc'), settings.py -> INSTALLED_APPS INSTALLED_APPS = [ 'rest_framework', 'myappname', 'rest_framework.authtoken', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'fcm_django', 'storages', 'colorfield', 'drf_yasg2', ] The error Internal Server Error: /swagger/ … -
Heroku - Django App Crased Error H10 status
heroku logs --tail --app the-milky-way-airlines 2020-10-16T10:26:30.053966+00:00 app[web.1]: [2020-10-16 10:26:30 +0000] [9] [INFO] Booting worker with pid: 9 2020-10-16T10:26:30.059087+00:00 app[web.1]: [2020-10-16 10:26:30 +0000] [9] [ERROR] Exception in worker process 2020-10-16T10:26:30.059088+00:00 app[web.1]: Traceback (most recent call last): 2020-10-16T10:26:30.059088+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2020-10-16T10:26:30.059089+00:00 app[web.1]: worker.init_process() 2020-10-16T10:26:30.059089+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 119, in init_process 2020-10-16T10:26:30.059089+00:00 app[web.1]: self.load_wsgi() 2020-10-16T10:26:30.059089+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi 2020-10-16T10:26:30.059090+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2020-10-16T10:26:30.059090+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/base.py", line 67, in wsgi 2020-10-16T10:26:30.059090+00:00 app[web.1]: self.callable = self.load() 2020-10-16T10:26:30.059091+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 49, in load 2020-10-16T10:26:30.059091+00:00 app[web.1]: return self.load_wsgiapp() 2020-10-16T10:26:30.059091+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/app/wsgiapp.py", line 39, in load_wsgiapp 2020-10-16T10:26:30.059091+00:00 app[web.1]: return util.import_app(self.app_uri) 2020-10-16T10:26:30.059092+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/site-packages/gunicorn/util.py", line 358, in import_app 2020-10-16T10:26:30.059092+00:00 app[web.1]: mod = importlib.import_module(module) 2020-10-16T10:26:30.059092+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.8/importlib/init.py", line 127, in import_module 2020-10-16T10:26:30.059092+00:00 app[web.1]: return _bootstrap._gcd_import(name[level:], package, level) 2020-10-16T10:26:30.059092+00:00 app[web.1]: File "", line 1014, in _gcd_import 2020-10-16T10:26:30.059093+00:00 app[web.1]: File "", line 991, in _find_and_load 2020-10-16T10:26:30.059093+00:00 app[web.1]: File "", line 961, in _find_and_load_unlocked 2020-10-16T10:26:30.059093+00:00 app[web.1]: File "", line 219, in _call_with_frames_removed 2020-10-16T10:26:30.059093+00:00 app[web.1]: File "", line 1014, in _gcd_import 2020-10-16T10:26:30.059094+00:00 app[web.1]: File "", line 991, in _find_and_load 2020-10-16T10:26:30.059094+00:00 app[web.1]: File "", line 973, in _find_and_load_unlocked 2020-10-16T10:26:30.059094+00:00 app[web.1]: ModuleNotFoundError: No module named 'the_milky_way_airlines' 2020-10-16T10:26:30.059216+00:00 app[web.1]: [2020-10-16 … -
Django - document.querySelector finds the base.html tags only
I have the django app with traditional base.html approach, which is extended in every other template. However, I have a problem with reaching out html tags which are outside the base.html template. var myHeading = document.querySelector(".contentfont"); console.log(myHeading); gives me: <div class="contentfont"> <!-- JS --> <script src="/static/js/squad_picker.js" type="text/javascript"></script> <h1 id="test" class="heading test"> test page </h1> <div class="container"> <div class="jumbotron"> </div> </div> </div> but when I try for example var myHeading = document.querySelector(".contentfont > h1"); it always gives me null. The same happens while trying to access anything which is not inside base.html directly by id or class. I add the part of base.html: <div class="contentfont"> {% block content %} {% endblock %} </div> and the html which is extending it: {% extends 'my_app/base.html' %} {% load static %} {% block content %} <!-- JS --> <script src="{% static 'js/squad_picker.js' %}" type="text/javascript"></script> <h1 id='test' class="heading test">test page </h1> <div class="container"> <div class="jumbotron"> </div> </div> {% endblock %} -
Can't get django pagination work with related fk set
I'm a django beginner and i'm trying to build a website using only generic CBV. In my models i have a class called Project and another class called ProjectFile as follow: class Project(models.Model): STATUS = ( ('Ongoing', 'Ongoing'), ('Ended', 'Ended'), ('Abandoned', 'Abandoned'), ) name = models.CharField(max_length=200, unique=True, error_messages={'unique':"This project name already exists"}, null=True) description = models.TextField(null=True) status = models.CharField(max_length=100, null=True, choices=STATUS) start_date = models.DateField(null=True) end_date = models.DateField(blank=True, null=True) team = models.ForeignKey(Team, on_delete=models.CASCADE) def __str__(self): return self.name class ProjectFile(models.Model): file = models.FileField(upload_to='project_files/') date_created = models.DateTimeField(auto_now_add=True, null=True) project = models.ForeignKey(Project, on_delete=models.CASCADE) I've created a CBV view to list all the projects called ProjectList as follow: class ProjectList(ListView): model = Project context_object_name = 'projects' paginate_by = 5 def get_queryset(self): return Project.objects.all().order_by('name') def get_context_data(self, **kwargs): ctx = super(ProjectList, self).get_context_data(**kwargs) ctx['projects_count'] = self.get_queryset().count() ctx['ongoing_count'] = Project.objects.filter(status='Ongoing').count() ctx['ended_count'] = Project.objects.filter(status='Ended').count() return ctx and i added the pagination in template like this: {% if is_paginated %} <nav class="pagination is-centered is-rounded"> {% if page_obj.has_previous %} <a class="pagination-previous" href="?page= {{ page_obj.previous_page_number|stringformat:"d" }}{{ getvars }}{{ hashtag }}"><i class="fa fa-hand-o-left"></i>&nbsp;{% trans "Previous" %}</a> {% else %} <a class="pagination-previous" disabled>{% trans "Previous" %}</a> {% endif %} {% if page_obj.has_next %} <a class="pagination-next" href="?page={{ page_obj.next_page_number|stringformat:"d" }}{{ getvars }}{{ hashtag }}">{% trans "Next" %}&nbsp;<i … -
Django - ListView url not connecting to desired view
I am new to Django and have hit a wall with a certain part of my project and I hope someone can help. I have two ListViews in my views.py file which I would like to work similar to published/draft posts (I'm actually using sanitised and unsanitised reports). Currently, every time I try to access the "Unsanitised" list view (unsanitised_list.html), it just directs me to the the sanitised list view (intelreport_list.html) views.py: class IntelReportListView(ListView): model = IntelReport context_object_name = 'all_logs' def get_queryset(self): return IntelReport.objects.filter(create_date__lte=timezone.now()).order_by('-create_date') class UnsanitisedListView(LoginRequiredMixin, ListView): login_url = '/login/' redirect_field_name = 'intel_db/unsanitised_list.html' model = IntelReport def get_queryset(self): return IntelReport.objects.filter(sanitised__isnull=True).order_by('-create_date') models.py class IntelReport(models.Model): gpms_choices = ( ***REDACTED*** ) gpms = models.CharField(max_length=20, blank=True, null=True, choices=gpms_choices) officer = models.CharField(max_length=50) create_date = models.DateTimeField(auto_now_add=True) sanitised = models.BooleanField(default=False) source_eval_choices = ( ***REDACTED**** ) source_eval = models.CharField(max_length=50, blank=True, null=True, choices=source_eval_choices) intel_eval_choices = ( ***REDACTED*** ) intel_eval = models.CharField(max_length=100, blank=True, null=True, choices=intel_eval_choices) report = models.TextField(max_length=5000, blank=True, null=True) def sanitised_log(self): self.sanitised = True self.save() def get_absolute_url(self): return reverse('log_details', kwargs={'pk':self.pk}) def __str__(self): return str(self.pk) urls.py from django.urls import path from intel_db import views urlpatterns = [ path('welcome/', views.AboutView.as_view(), name='about'), path('logs/', views.IntelReportListView.as_view(), name='log_list'), path('logs/<int:pk>/', views.IntelReportDetailView.as_view(), name='log_detail'), path('logs/new_log/', views.IntelReportCreateView.as_view(), name='new_log'), path('unsanitised/', views.UnsanitisedListView.as_view(), name='unsanitised'), path('logs/<int:pk>/sanitise_log/', views.sanitsed_report, name='sanitised_report'), ] and on my landing … -
How to handle django application having multiple databases in celery
I am using multiple databases in my django application and the database is selected on the basis of url. All the views are working properly and use the database as required. Now, I have an API which exports the data into excel and I am trying to shift main logic of this API to a background tasks using celery. The issue I am facing is that celery is using default database for querying which is not required. So how can I make celery use database based on url. I am using python 3.7, django 2.2.11, django rest framework 3.11.0, celery 4.4.3. Any help would be appreciated. Thanks in advance! -
How to save for a simple model I need to save the User key automatically How to get objects owned by a user? in Django
i have such a model class Summaries(models.Model): user = models.OneToOneField(User, on_delete = models.CASCADE, primary_key = True) father_name = models.CharField(max_length=60, blank=True) myfile = models.FileField(upload_to="document") class Summary_Createes(models.Model): suser = models.ForeignKey(Summaries, on_delete = models.CASCADE) for the active, current user "Summary_Createes" The user who saved this model should only see it for himself how can i filter such data i need filter -
Python Django prevent password reuse
I'm currently trying to prevent users from using their old passwords (configurable, like say last 5 passwords) I have the following Infos: User passwort in cleartext from the form during validation (form.cleaned_data['new_password1']) Their current hashed Password (pwd_before_change) Their last x passwords also hashed (pws) Funnily enough my code works for the current password, but not for my old ones: pwd_before_change = user_to_change.password .... old_pws = Passwords.objects.filter(username=user_to_change).order_by('-password_changed')[:allowed_reuse].values_list('password', flat=True) .... if old_pws: for pws in old_pws: if check_password(form.cleaned_data['new_password1'], pws) or \ check_password(form.cleaned_data['new_password1'], pwd_before_change) messages.error(request, f'You are not allowed a password which was already used in the last ' f'{allowed_reuse + 1} iterations') return render(request, 'registration/password_change.html', { 'form': form }) Any ideas what the issue may be? (additional info, I'm using Argon2). Do I really need to encode the cleartext password again with all possible "salt" in the old passwords and check? (this would make the method depending on the hasher function which would not be ideal + I thought the check passwort function was exactly for scenarios like this?) -
Django trying to add images with forms
I have two models with two different forms. One has a ForeignKey for another model, making a 1-N relationship. The problem is when i try to add images , is not working. The form where i change the (name/TabletForm2) is working so , only when i try to add (image/TabletFormImagem) is not working. The problem is that My model's def get_image(instance, filename): return os.path.join('intervencao/fotografias', str(instance.intervencao), filename) class Intervencao(models.Model): name= models.CharField(verbose_name="Name", max_length=200, blank=True, null=True) class Imagem(models.Model): intervencao = models.ForeignKey(Intervencao, related_name='intervencaoObjectsImagem', on_delete=models.CASCADE) imagem = models.ImageField(upload_to=get_image, blank=True, null=True, verbose_name="Fotografia") def __str__(self, ): return str(self.intervencao) My View def project_detail_chefe(request, pk): form = TabletForm2(request.POST) form2 = TabletFormImagem(request.POST, request.FILES) if request.method == "POST": if form.is_valid(): form.save() return redirect('index') else: form = TabletForm2(request.POST) if form2.is_valid(): //when i print something here to see if the form2 is valid , never enter here. form2.save() return redirect('home') else: form2 = TabletFormImagem() context = { 'form':form, 'form2':form2, } return render(request, 'tablet/info_chefes.html', context) tablet/info_chefes.html <div class="col-md-12"> <div class='form-group'> <label for="{{ form.subject.id_for_label }}" id="titulo">Name:</label> <em>{{ form.name}}</em> </div> </div> <div class="col-md-12"> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{ form2.as_p }} <button type="submit">Upload</button> </form> </div> Forms class TabletForm2(forms.ModelForm): class Meta: model=Intervencao fields = ['data_intervencao_fim','ferramenta'] class TabletFormImagem(forms.ModelForm): class Meta: model=Imagem fields = ['imagem'] -
Include the same Django Admin class to multiple apps
For example, I have 3 apps: app1, app2 and all_apps. First 2 apps are nested in apps and have a lot of models. Now I want to include some admin classes to app1 and app2, and also to all_apps/admin.py (for example some configuration). What I need to do make that admin classes visible in both appX and all_apps? I tried to import it to both, but it appeared only in admin of app where it is located. Is it possible to include the same admin class twice (if it is for 2 different apps)? I know that it requires proxy-class if I need to include it twice to the same app, but what if they are different? -
Could not find path on running the django-private-chat, am I doing something wrong?
Details: django-private-chat version: 0.3.0 Django version: 3.1.2 Python version: 3.8.3 Operating System: Windows 10 I have installed all the requirements in my virtual environment, Django-private-chat is giving this error on running the server: Using the URLconf defined in tests.urls, Django tried these URL patterns, in this order: ^dialogs/(?P<username>[\w.@+-]+)$ [name='dialogs_detail'] ^dialogs/$ [name='dialogs'] The empty path didn't match any of these. Could someone point out what I am doing wrong? -
Failed to start gunicorn daemon, gunicorn.service: Failed to load environment
When i run sudo journalctl -u gunicorn I get: Oct 14 12:49:22 django-ubuntu-helpme systemd[1]: gunicorn.service: Failed to load environment > Oct 14 12:49:22 django-ubuntu-helpme systemd[1]: gunicorn.service: Failed to run 'start' task:> Oct 14 12:49:22 django-ubuntu-helpme systemd[1]: gunicorn.service: Failed with result 'resourc> Oct 14 12:49:22 django-ubuntu-helpme systemd[1]: Failed to start gunicorn daemon. I suppose something doesn’t add up with my directories. I have /etc/systemd/system/gunicorn.service which is: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=myname Group=myname EnvironmentFile=/home/myname/myapp/env WorkingDirectory=/home/myname/myapp ExecStart=/home/myname/myapp/env/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ myapp.wsgi:application [Install] WantedBy=multi-user.target The directories I’m working in are as follows. myapp/ has my requirements.txt file, env/, and another app/ dir. Within myapp/app, I have manage.py, an env file that containt my SECRET_KEY which I've exported, and another app/ dir. Within myapp/app/app, I have settings.py and wsgi.py. What am I doing wrong? -
Django. An autocomplete field of a form doesn't work
I faced a problem during developing a search filter for my web-app. I need one field of a filter to be an autocomplete field, but unfortunately it doesn't work as expected. When I type smth in this field it displays nothing although it has to display some options. I use Bootstrap for this field, the class is 'basicAutoComplete', and as you can see in the picture below (please do not pay attention to bad positioning of the fields) there is no information displayed. But if I remove 'basicAutoComplete', all my buildings appears in dropdown list as you can see in the second picture. Can someone tell me how to fix it? class 'basicAutoComplete' no class Here is my code: views.py def device_rooms_search(request): device_rooms = DeviceRooms.objects.all() deviceRoomsFilter = DeviceRoomsFilter(request.GET, queryset=device_rooms) device_rooms = deviceRoomsFilter.qs builds = Buildings.objects.all() context = {'device_rooms_list': device_rooms, 'deviceRoomsFilter': deviceRoomsFilter} return render(request, "database/device_rooms/device_rooms_search.html", context) filters.py class DeviceRoomsFilter(df.FilterSet): name = df.CharFilter(field_name='room_number', lookup_expr='icontains') descr = df.CharFilter(field_name='description', lookup_expr='icontains') class Meta: model = DeviceRooms fields = ['name', 'facility_id', 'building_id', 'device_room_type', 'descr'] models.py class DeviceRooms(models.Model): id = models.CharField(max_length=7, primary_key=True) room_number = models.CharField(max_length=30, unique=True) device_room_type = models.ForeignKey(DeviceRoomTypes, on_delete=models.CASCADE) building_id = models.ForeignKey(Buildings, on_delete=models.CASCADE) facility_id = models.ForeignKey(Facilities, on_delete=models.CASCADE) description = models.CharField(max_length=200, null=True) search.html <form method="get" action=""> {% … -
(Django)Should I use same function for similar kind of function or create different for each
They are somewhat similar like all are comment related function. def someFucntion(request,query): if query == 'func1': # to something... elif query == 'func2': # to something... else: # to something else... -
How to highlight word in Django template from query keyword?
I want to highlight keywords in Django template which are the same keywords getting from the query. The below image illustrates how it highlights the keyword. In this example, the query contains two keywords "plastic" and "automotive" I want Django template to get those query keywords and highlight the same keyword contained in each Description. I guess it may uses {{ request.GET.query }} but I can not figure out any more. Please teach me how to make it. -
How can I count my followers in django template?
Well I have count the my following (people who i follow) but i dont understand how can i count my follower (people who follow me). model.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follower = models.ManyToManyField(User, related_name ='is_following',blank=True,) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) objects = ProfileManager() def __str__(self): return f'{self.user.username}' views.py(profiledetailview) def get_context_data(self, *args, **kwargs): context = super(UserProfileDetailView, self).get_context_data(*args, **kwargs) user = context['user'] '''#Trying with this but it is not working i guess this is wrong way to this but i am not sure!!''' allprofile = UserProfile.objects.all() followers = 0 for u in allprofile.follower: if u == user.userprofile: followers+=1 context['followers']=followers return context (My roughly idea: I was thinking somehow i gain all the profiles and than loop through them to check the particular user profile if there is profile within their follower than add one some follower variable.) You can ignore this if you know other way i have tried my idea but that couldn't work. you guys know them please tell me. -
(Django)How open diffrent templete .html for diffrent category like Mobile, Cars?
I have a category model. I want to open mobile form for mobile category and Cars form for car models