Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Write reusable template part django
In my templates, in many places, I've got repeating parts, like: <th class="column-title"> <a href="?{% query_transform order_by='x' %}"> {{ objForm.x.label_tag }}</a> </th> <th class="column-title"> <a href="?{% query_transform order_by='y' %}"> {{ objForm.y.label_tag }}</a> </th> <th class="column-title"> <a href="?{% query_transform order_by='z' %}"> {{ objForm.z.label_tag }}</a> </th> Is there a way, to write some "function" to render such html part like: (pseudocode) in html: render("x") render("y") render("z") in python: def render(param): return " <th class="column-title"> <a href="?{% query_transform order_by='+param+' %}"> {{ objForm'+param+'.label_tag }}</a> </th>" PS. I know, that theoreticaly I can prepare ordered list in view, and then iterate over it in a template, but I think it is not a good solution ,as I prefer to build my view, fields order etc on the template side. -
How to sort TextFields (strings) in Django using ElasticSearch-dsl?
I cannot find the solution for this online so i hope anyone here could help. I have a ChardField in models.py i want to sort after rebuilding the index in ElasticSearch (version 7). I'm using 'django_elasticsearch_dsl' as my pip. I read something about adding 'fielddata' as a property in 'documents.py' or changing the TextField() type to KeywordField() but i have no idea how to do this properly. My documents.py so far: from django_elasticsearch_dsl import Document, fields from django_elasticsearch_dsl.registries import registry from .models import Journey @registry.register_document class JourneyDocument(Document): class Index: name = 'journeys' settings = {'number_of_shards': 1, 'number_of_replicas': 0} class Django: model = Journey # The model associated with this Document fields = [ 'id', 'departure_time', 'return_time', 'departure_station_name', 'return_station_name', 'covered_distance', 'duration', ] ..and my models.py is: class Journey (models.Model): id = models.BigAutoField(primary_key=True) departure_time = models.DateTimeField(auto_now = False, auto_now_add = False, default=timezone.now) return_time = models.DateTimeField(auto_now=False, auto_now_add=False, default=timezone.now) departure_station = models.ForeignKey(Station, on_delete=models.CASCADE, related_name='departure_station') departure_station_name = models.CharField(max_length=50, default="-") return_station = models.ForeignKey(Station, on_delete=models.CASCADE, related_name='return_station') return_station_name = models.CharField(max_length=50, default="-") covered_distance = models.DecimalField(max_digits=12, decimal_places=2, validators=[MinValueValidator(10, "Covered distance of the journey has to be bigger than 10.")]) duration = models.PositiveIntegerField(validators=[MinValueValidator(10, "Duration of the journey has to be bigger than 10s.")]) So how can i sort the query results … -
My React app's proxy not working in docker container
When I working without docker(just run React and Django in 2 sep. terminals) all works fine, but when use docker-compose, proxy not working and I got this error: Proxy error: Could not proxy request /doc from localhost:3000 to http://127.0.0.1:8000. See https://nodejs.org/api/errors.html#errors_common_system_errors for more information (ECONNREFUSED). The work is complicated by the fact that each time after changing package.json, you need to delete node_modules and package-lock.json, and then reinstall by npm install (because of the cache, proxy changes in package.json are not applied to the container). I have already tried specifying these proxy options: "proxy": "http://localhost:8000/", "proxy": "http://localhost:8000", "proxy": "http://127.0.0.1:8000/", "proxy": "http://0.0.0.0:8000/", "proxy": "http://<my_ip>:8000/", "proxy": "http://backend:8000/", - django image name Nothing helps, the proxy only works when running without a container, so I conclude that the problem is in the docker settings. I saw some solution with nginx image, it doesn't work for me, at the development stage I don't need nginx and accompanying million additional problems associated with it, there must be a way to solve the problem without nginx. docker-compose.yml: version: "3.8" services: backend: build: ./monkey_site container_name: backend command: python manage.py runserver 127.0.0.1:8000 volumes: - ./monkey_site:/usr/src/monkey_site ports: - "8000:8000" environment: - DEBUG=1 - DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 - CELERY_BROKER=redis://redis:6379/0 - CELERY_BACKEND=redis://redis:6379/0 … -
Receiving "NotImplementedError" when using TruncMonth in Django QuerySet
I am a complete beginner when it comes to programming and Django. What I am using: Django 2.2.8 pymongo 3.12.1 djongo 1.3.6 MongoDB 3.6.23 I am trying to create a queryset in which I take a date from my database and group it by month. The date from the database I am pulling from is formatted as "2022-11-26T00:00:00.000+00:00". So I am trying to annotate a new field of just the month using TruncMonth so that I can then group by months. I have also tried using "extract" but that doesn't seem to work either. I am trying to avoid using a method that uses "extra" as it has been deprecated. I have been doing this in python shell until I get the results I want. Here is my code: models.py: class Charts(models.Model): severity_type = models.CharField(max_length=25) num_findings = models.IntegerField() finding_date = models.DateTimeField() python shell: `>>>from charts.models import Charts from datetime import datetime from django.db.models.functions import TruncMonth Charts.objects.annotate(month=TruncMonth('finding_date')).values('month')` #Which throws this error `NotImplementedError: subclasses of BaseDatabaseOperations may require a datetime_trunc_sql() method` From what research I have done, it has something to do with the field being a datetime vs a date I believe. I found this article that seems to be on … -
How to use Visual Basic ".vb" methods in a Django Project
In my actually job they're using an old Visual Basic WinForms apps and can't do a migration to another language. The question is, i want to use the ".vb" files which exists and consume their methods whit python in a Django project. Sending and returning values and data from each one. How can i do this? Connect a "Visual Basic" code with Django/Python -
'form.save(commit=True)' not saving to database
I am trying to use a ModelForm to create a new model in my database. The thing is, it's not saving it to there when I call form.save(commit=True). I am using Elastic Beanstalk (the free tier) to host my website. I feel like this has something to do with the problem. This is my forms.py: from datetime import date from .models import Itinerary class CreateItinerary(forms.ModelForm): class Meta: model = Itinerary exclude = ["sights"] destination = forms.CharField(max_length=100) start = forms.DateField(widget=forms.NumberInput(attrs={'type': 'date'}), initial=date.today) end = forms.DateField(widget=forms.NumberInput(attrs={'type': 'date'})) class FindPlaces(forms.Form): types = ((1, "restaurants"), (2, "attractions"), (3, "parks"), (4, "national parks"), (5, "clothing stores"), (6, "malls"), (7, "department stores"), (8, "stadiums")) place_type = forms.ChoiceField(choices=types) This is my views.py file: from django.views import generic from .models import * from .forms import * class createItinerary(generic.TemplateView): template = "itineraries/create.html" def get(self, request, *args, **kwargs): return render(request, self.template, { "form" : CreateItinerary(request.POST, request.FILES), }) def post(self, request, *args, **kwargs): form = CreateItinerary(request.POST) if form.is_valid(): new = form.save(commit=True) return redirect("/sights/") else: form = CreateItinerary return render(request, self.template, { "form" : form, }) def plan_redirect(request, id): return redirect("/plan/%s" % id, request) class plan(generic.TemplateView): find_places_form_class = FindPlaces template = "itineraries\plan.html" def get(self, request, id, *args, **kwargs): object = get_object_or_404(Itinerary, pk=id) … -
get() returned more than one Post -- it returned 2
I got problem in django. Im creating online shop website and I add products section where my products listed(html). I add my products from admin site (models.py). When I want to add to products i give error like this : get() returned more than one Post -- it returned 2! These are my codes : views.py class PostDetail(generic.DetailView): model = Post template_name = "shop-single.html" def get_context_data(self, **kwargs): models = Post.objects.get() context = super().get_context_data(**kwargs) client = Client(api_key = settings.COINBASE_COMMERCE_API_KEY) domain_url = "https://www.nitroshop.store/" product = {"name" : f'{models.title}' , 'description': f'{models.subject}' , "local_price" : {'amount' : f'{models.product_price}' , "currency" : "USD"} , "pricing_type" : "fixed_price" , "redirect_url" : domain_url + "NXnUijYpLIPy4xz4isztwkwAqSXOK89q3GEu5DreA3Ilkde2e93em8TUe99oRz64UWWBw9gEiiZrg60GMu3ow" , "cancel_url" : domain_url + "products"} charge = client.charge.create(**product) context['charge'] = charge return context models.py from django.db import models from django.contrib.auth.models import User # Create your models here. STATUS = ( (0 , "Draft"), (1 , "Publish") ) class Post(models.Model): title = models.CharField(max_length = 200 , unique = True) slug = models.SlugField(max_length = 200 , unique = True) author = models.ForeignKey(User , on_delete = models.CASCADE , related_name = "shop_posts") updated_on = models.DateTimeField(auto_now = True) subject = models.CharField(max_length = 200 , default = "We offer you pay with Tether or Litecoin") caption … -
I'm getting a validation error with django form
I'm facing with a validation form problem. I have this model: class Documenti(models.Model): descr = models.CharField('descrizione ', max_length=200) data = models.DateField('data', blank=True) objects = models.Manager() class Meta: verbose_name = 'Documenti' this is the form: class DocForm(ModelForm): def __init__(self, *args, **kwargs): super(DocForm, self).__init__(*args, **kwargs) class Meta: model = Documenti exclude = ['id'] widgets = { 'data': forms.DateInput(format=FORMATO_INPUT_DATE, attrs={'type': 'date', 'class': 'stdh-data'}), 'descr': forms.TextInput(attrs={SIZE: '80'}), } and this is the edit function: def edit_doc(request, doc_id=None): """ :param request: :param doc_id: """ if not (doc_id is None): doc_that = get_object_or_404(Documenti.objects.all(), pk=doc_id) titolo = ED_DOCUMENTO else: doc_that = Documenti() titolo = INS_DOCUMENTO form = DocForm(request.POST or None, instance=doc_that) redirect_to = Documenti().get_absolute_url() + current_page(request) if form.is_valid(): # All validation rules pass doc = form.save(commit=False) doc.save() return HttpResponseRedirect(redirect_to) # Redirect after POST else: print(form) from documenti.urls import url_views_lista_doc url_after_close = full_url(request, 'doc:%s' % url_views_lista_doc) dizio = {FORM: form, TitleScheda: titolo, TAG_url_after_close: url_after_close, } return generic_render(request, HTML_generic_edit, dizio) I always get FALSE when I check form.is_valid(). I tried to get error list with {{ form.non_field_errors }} {{ form.field_errors }} but they seems void. No idea. many thanks in advance -
'tuple' object has no attribute 'split_contents'
I'm trying to use django-advanced-filters. Python 3.8.10 Django==3.2 django-advanced-filters==2.0.0 sqlparse==0.4.3 settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'advanced_filters', 'semantics', 'sites', ] Urlpatterns urlpatterns = [ path('admin/', admin.site.urls), url(r'^advanced_filters/', include('advanced_filters.urls')), ] Admin class SemanticsClusterAdmin(AdminAdvancedFiltersMixin, admin.ModelAdmin): raw_id_fields = ("page",) list_display = ["id", "detail_view", "page", "name", ] advanced_filter_fields = ( 'id', 'page', ) exclude = [] admin.site.register(SemanticsClusters, SemanticsClusterAdmin) Traceback $ python manage.py migrate Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/management/commands/migrate.py", line 75, in handle self.check(databases=[database]) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/management/base.py", line 419, in check all_issues = checks.run_checks( File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/checks/registry.py", line 76, in run_checks new_errors = check(app_configs=app_configs, databases=databases) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 13, in check_url_config return check_resolver(resolver) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/core/checks/urls.py", line 23, in check_resolver return check_method() File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 412, in check for pattern in self.url_patterns: File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/utils/functional.py", line 48, in __get__ res = instance.__dict__[self.name] = self.func(instance) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/urls/resolvers.py", line 598, in url_patterns patterns = getattr(self.urlconf_module, "urlpatterns", self.urlconf_module) File "/home/michael/Documents/PyCharmProjects/marketing3/venv/lib/python3.8/site-packages/django/utils/functional.py", … -
How do I pass urls into a component (django-components)?
I want to create a component for a dropdown menu and therefore I want to inject several names and urls as items. part of the component: <ul class="dropdown-menu dropdown-menu-lg-end" aria-labelledby="dropdownMenuButton1"> {% for item in items %} <li><a class="dropdown-item" href={{ item.url }}>{{ item.name }}</a></li> {% endfor %} </ul> {% component_block "bs_dropdown" items=??? %} {% endcomponent_block %} Any ideas? Thanks I tried injecting a single hard coded url and that worked. But of course that's not how it sould be. It would be possible to slot the items, but then one would have to know to use the class "dropdown-item" and that's also not how it should be. As a programmer I just want to pass names and urls. -
When building different mixions in django, it is not possible to reassign different functionality to the same function
I have a class to delete a user. There are three mixins (checks). For authentication For the fact that the user deletes no other user That the user is not used Checks are implemented through mixins class UserDeleteView(CustomLoginRequiredMixin, CustomUserPassesTestMixin, CheckedForUseMixin2, SuccessMessageMixin, DeleteView): template_name = 'users/delete.html' success_url = '/users/' model = get_user_model() success_message = \_('User deleted successfully') class CustomLoginRequiredMixin(LoginRequiredMixin): login_url = '/login/' redirect_field_name = 'next' def handle_no_permission(self): messages.error(self.request, _("You are not authorized! Please sign in.")) return super().handle_no_permission() class CustomUserPassesTestMixin(): def test_func(self): return self.get_object() == self.request.user def dispatch(self, request, *args, **kwargs): if not self.test_func(): messages.error(self.request, _("You do not have permission to change another " "user")) return redirect('list_users') return super().dispatch(request, *args, **kwargs) class CheckedForUseMixin2(): def test_func(self): user = self.get_object() return not (user.tasks_author.exists() or user.tasks_executor.exists()) def dispatch(self, request, *args, **kwargs): if not self.test_func(): messages.error(self.request, _("Can't delete user because it's in use")) return redirect('list_users') return super().dispatch(request) the second time reassigning test_func breaks the test logic. That is, test_func for some reason always starts returning true or false, regardless of whether the user has tasks. If I remove test_func, and move the check to an if block, or call the function, for example, test_func1, then everything works. https://github.com/zhek111/python-project-52 I tried to inherit from different classes (View, … -
What are "Forward Foreign Key (Relationship)" and "Reverse Foreign Key (Relationship)" in Django?
When reading the topics related to Django's model relationship and foreign key on some websites including Stack Overflow, I sometimes see the words Forward Foreign Key (Relationship) and Reverse Foreign Key (Relationship) but I couldn't find the definitions on Django Documentation: # "models.py" from django.db import models class Category(models.Model): name = models.CharField(max_length=20) class Product(models.Model): category = models.ForeignKey(Category, on_delete=models.CASCADE) name = models.CharField(max_length=50) price = models.DecimalField(decimal_places=2, max_digits=5) So, what are Forward Foreign Key (Relationship) and Reverse Foreign Key (Relationship) in Django? -
How Can I Display Multiple Models In a Django ListView?
I am trying to display several models via a ListView. After some research...I have determined that I can do something like... class MultiModelListView(LoginRequiredMixin,ListView): model = MultiModel context_object_name = 'thing_list' template_name = 'view_my_list.html' paginate_by = 15 def get_context_data(self, **kwargs): context = super(MultiModelListView, self).get_context_data(**kwargs) list1 = Model1.objects.filter(created_by=self.request.user) list2 = Model2.objects.filter(created_by=self.request.user) list3 = Model3.objects.filter(created_by=self.request.user) context['list1'] = list1 context['list2'] = list2 context['list3'] = list3 return context And then in my template....loop over each list.... {% for thing in list1 %} Show thing {% endfor %} {% for thing in list2 %} Show thing {% endfor %} {% for thing in list3 %} Show thing {% endfor %} This would work...except I really want to co-mingle the events and sort them by creation date which all of the models have....I really want to do an order by for all of the event...not by list per se...Is there a straightforward way to do this....Or do I need to create a "Master" model that has all of these models defined in order to achieve my goal? Thanks in advance for any thoughts. -
Django UpdateView Bootstrap Modal - i've got empty form in modal window
I've got empty Bootstrap modal form with Django UpdateView(CBV) Modal window show fields of empty form view.py class HistoryPamentsByService(ListView): model=Payments form_class=PaymentsForm template_name ='myflat/history_by_service.html' context_object_name='flats' slug_url_kwarg = 'slug' def get_context_data(self, **kwargs): context=super().get_context_data(**kwargs) form=PaymentsForm() payments=Payments.objects.filter(flats_id=self.kwargs['flats_id']) context['form']=form return context def get_form(self,*args,**kwargs): super().get_form(*args, **kwargs) form=PaymentsForm() return form def get_queryset(self): return Payments.objects.filter(slug=self.kwargs['slug'],flats_id=self.kwargs['flats_id']) class UpdatePayments(UpdateView): model=Payments pk_url_kwarg='pk' form_class=PaymentsForm template_name='myflat/update_modal.html' context_object_name='name_flat' urls.py urlpatterns = [ path('history_by_service/<slug:slug>/<int:flats_id>/', HistoryPamentsByService.as_view(),name='HistoryPamentsByService'), path('UpdatePayments/<int:pk>/',UpdatePayments.as_view(),name='UpdatePayments'), ] template history_by_service.html (for ListView) {% for flat in flats %} <tr> <td scope="row">{{ forloop.counter }} </td> <td>{{flat.name_service}}</td> <td>{{flat.amount_of_bill}}</td> <td>{{flat.amount_of_real}}</td> <td>{{flat.date_of_bill}}</td> <td>{{flat.date_of_payment}}</td> <td>{{flat.get_status_payment_display}}</td> <td>{{flat.comments}}</td> <td>{{flat.bill_save_pdf}}</td> <td> <form method="post" action="{% url 'UpdatePayments' flat.pk %}" enctype="multipart/form-data"> {% csrf_token %} <button type='submit' class='btn btn-success btn-sm' id="update_modal" data-bs-toggle="modal" data-bs-target="#update_modal{{flat.pk}}"> <i class="fa-regular fa-pen-to-square fa-fw"></i>Edit</button> {% include "myflat/update_modal.html" %} </form> {% endfor %} template update_modal.html <div class="modal fade" id="update_modal{{flat.pk}}" data-bs-backdrop="static" data-bs-keyboard="false" tabindex="-1" aria-labelledby="update_modal" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content" style="width:auto"> <div class="modal-header"> <h5 class="modal-title " id="update_modalLabel">{{flat.name_flat}}</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <form method="post" action="{% url 'UpdatePayments' flat.pk %}" enctype="multipart/form-data"> <div class="modal-body"> {% csrf_token %} {% for field in form %} {{field}} {% endfor %} <div class="modal-footer"> <button type="submit" class="btn btn-primary" > <i class="fa-solid fa-trash fa-fw" ></i>Save</button> <button type="button" class="btn btn-warning" data-bs-dismiss="modal"> <i class="fa-regular fa-circle-xmark"></i> Close </button> </div> </div> </form> </div> </div> </div> I try add … -
DEBUG = TRUE and you have "no urls configured." Yet, my URLs are configured and it displays standard DJANGO success page
SETTINGS.PY: INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'application.apps.ApplicationConfig', #already tried 'application', URLs.py/src: from django.contrib import admin from django.urls import path, include from application import views urlpatterns = [ path('admin/', admin.site.urls), path('', include('application.urls')), path('home/', views.signIn), ] URLs.py/application: from django.urls import path from . import views urlpatterns = [ path('', views.landing, name='landing'), path('create-account', views.createAccount, name='create-account'), path('forgot-password', views.forgotPassword, name='forgot-password'), path('home', views.signIn, name='home'), ] Are my URLs configured? I do not know why it is saying they have not been configured appropriately. I would appreciate any help -
Find multiple patterns with regex
For a given string, I would like to know if a pattern is identified in it. Ultimately, I want to be able to detect a command (/text, /msg etc.) and to run a function associated with it. string = str("/plot banana 24/02/2021 KinoDerToten") #In this example, I want to get the /plot tot be returned. cmd_search = re.findall(r"/plot", "/cmd", "/text", "/msg", string) print(cmd_search) #The parameters for re.findall are not working The message error is: TypeError: unsupported operand type(s) for &: 'str' and 'int' -
How to fix Database needs bootstrapping or is older than Kong 1.0
How to fix this error? nginx: [error] init_by_lua error: /usr/local/share/lua/5.1/kong/cmd/utils/migrations.lua:16: Database needs bootstrapping or is older than Kong 1.0. To start a new installation from scratch, run 'kong migrations bootstrap'. To migrate from a version older than 1.0, migrated to Kong 1.5.0 first. If you still have 'apis' entities, you can convert them to Routes and Services using the 'kong migrations migrate-apis' command in Kong 1.5.0. stack traceback: [C]: in function 'error' /usr/local/share/lua/5.1/kong/cmd/utils/migrations.lua:16: in function 'check_state' /usr/local/share/lua/5.1/kong/init.lua:562: in function 'init' init_by_lua:3: in main chunk dockerfile files FROM python:3.10 WORKDIR /app COPY requirements.txt . RUN pip install -r requirements.txt EXPOSE 8000 CMD ["python3", "manage.py", "runserver", "0.0.0.0:8000"] docker-compose files version: '3.9' services: kong-database: image: postgres:latest container_name: kong-database restart: always ports: - 15432:5432 networks: - default volumes: - db:/var/lib/postgresql/data environment: - POSTGRES_DB=kong - POSTGRES_USER=kong - POSTGRES_PASSWORD=kong kong: image: kong:latest container_name: kong restart: always ports: - 18000:8000 - 18443:8443 - 127.0.0.1:8001:8001 - 18444:8444 links: - kong-database:kong-database networks: - default environment: - LC_CTYPE=en_US.UTF-8 - LC_ALL=en_US.UTF-8 - KONG_DATABASE=postgres - KONG_PG_HOST=kong-database - KONG_PG_USER=kong - KONG_PG_PASSWORD=kong - KONG_CASSANDRA_CONTACT_POINTS=kong-database - KONG_PROXY_ACCESS_LOG=/dev/stdout - KONG_ADMIN_ACCESS_LOG=/dev/stdout - KONG_PROXY_ERROR_LOG=/dev/stderr - KONG_ADMIN_ERROR_LOG=/dev/stderr - KONG_ADMIN_LISTEN=0.0.0.0:18001, 0.0.0.0:18444 ssl konga: image: pantsel/konga container_name: kong-konga restart: always ports: - 1337:1337 networks: - default volumes: - data:/app/kongadata links: - … -
Django template filter not raising exception when error occurs
I am building a custom template filter in Django to check if a user has permissions to view certain links in my navigation. I am running into an issue where I want to know if the argument passed in is bad, which is an app_label, so I can throw an exception on that front and be notified. Here is my HTML of the filter in use, that works without the or but with it, the conditional simply returns False without throwing the exception which is where I am confused. Note: I have an app named 'reports', not 'repordts' so the exception should definitely be thrown. {% if request|has_perm_for_app_with_property:'repordts' or request|has_perm_for_app_with_property:'staff_reports' %} This version throws the exception correctly: {% if request|has_perm_for_app_with_property:'repordts' %} Here is the filter code: @register.filter() def has_perm_for_app_with_property(request, app_label): """ """ user = request.user # ensure prop is set in session if not request.session.get('property'): return False print(app_label) # gather perms and show error if bad name perms_for_app = Permission.objects.filter(content_type__app_label=app_label) if not perms_for_app: raise Exception(f'No Perms for App: {app_label}') # check to ensure the permission passed is accurate allowed = any([user.has_perm(perm) for perm in perms_for_app]) return allowed -
ModuleNotFoundError even though the Module is present
I am getting a ModuleNotFoundError for a module that exists. I have a __init__.py and imported sys but I am still getting a ModuleNotFoundError error on my django error. My file structure: |-my_app |-folder1 |-__init__.py |-calc.py |-folder2 |-__init__.py |-test.py I want to import a function from test.py in calc.py. This is my code: import sys from folder2.test import func1, func2 #my code When I run this, I am getting this error: ModuleNotFoundError: No module named 'folder2.test' How can I fix this error? -
Django ModelForm Hidden Field to 'True' in only a certain situation?
I've got the following Django Form; it has a field called 'finished', that is hidden. I set the default to False because there is only one situation where I want it set to True. The problem is that it still marks it as "False" and I can't figure out how to change it in that one situation. In my views.py I have this: context["test_form"] = TestForm( instance=self.object, hide_status=True, is_finished=True ) the form looks like this: class TestForm(ModelForm): finished = forms.BooleanField( widget=forms.HiddenInput(), initial=False, required=False ) status = forms.Select(attrs={"class": "form-control"}) def __init__(self, *args, **kwargs): hide_status = kwargs.pop("hide_status", None) is_finished = kwargs.pop("is_finished", None) super().__init__(*args, **kwargs) self.fields["status"].queryset = Status.objects.filter(active=True) self.fields["status"].widget.attrs["class"] = "form-control" if hide_status: self.fields["status"].widget = HiddenInput() if is_finished: self.fields["finished"].initial = True class Meta: model = Test fields = ["finished", "status"] The HTML is super simple: <form method="post" action="{% url 'my_app:test-update' %}"> {% csrf_token %} {{ test_form.as_p }} <button type="submit" class="btn btn-primary">Finish</button> </form> The rendered HTML looks like this: <input type="hidden" name="finished" value="False" id="id_finished"> What is the best way to get that set to True in this case? -
How to properly check authentication with Vue.js (Vue router) and Django
I am trying to check if a user is authenticated on protected routes in vue-router. I have Django rest framework that sets sessionid on login. I have seen people using vuex or local storage to store session information. But, If the token was forcibly expired on the server-side a user will be allowed to navigate since localStorage still says IsAuthenticated=true. In this case, is it the best choice to make a request to the Django backend such as fetch("url/auth/authenticated")? -
Djoser is ignoring my Authenitcation Token
I set up djoser and DRF's TokenAuthentication. It works perfectly for registering users, and i get a valid token returned. When I try to access /users/me or /token/logout with header: Authorization: Token {token} (and the token itself in the body for good measure) I get the response Error 403: "Authentication credentials not provided." I've tried making the request through axios and postman. I made other accounts and tried their keys but I get the same result. I've looked on the djoser docs but there is no help there, nor anywhere else, because it seems no one else has this issue. -
Can you connect to a Django backend via a python separate file? if both are running locally
For example, when I would create a ruby and react app. I could run the ruby app on local.host:3000 and the react app on local.host:4000. With some configuration, I could fetch information from my ruby backend and send information from by react frontend. Currently, I am working on building a bot on discord, with a django frontend/backend. I need to run the python bot at the same time as the Django website. I run the bot via "python main.py". I run the django project via "python3 manage.py runserver" runs on http://127.0.0.1:8000/. They both work fine at the same time, but I want the bot to be able to send information to the django project. I don't believe its like ruby. I cant just fetch to http://127.0.0.1:8000/ bc that is not the backend. That is the frontend of the site(?). So, is there anyway for me to get the URL of the django backend, so I can send information to it via my python bot. I cannot seem to find an article on this, any help would be greatly appreciated. Thanks! -
Error response from daemon: invalid volume specification: 'D:\project\bookstore:/code:rw'
I try to run the following code, but in the end I deal with the opposite error. (venv) PS D:\project\bookstore> docker-compose up [+] Running 0/0 Container bookstore-web-1 Creating 0.0s Error response from daemon: invalid volume specification: 'D:\project\bookstore:/code:rw' -
how can I configure supervisor for celery and celery beat on django project?
I install supervisor with this command: pipenv install supervisor where is the location of the supervisor configuration file for run celery worker and celery beat?