Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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? -
Hvaing some 500 (Internal Server Error) issue in my code
I am trying to call a function when there is a button click. But its showing the error that I have mentioned above. -
Getting error code 247 while deploying django app
I am trying to deploy my Django application to Digital ocean droplets, using the less expensive one, that gives me 512 mb of ram, 1 CPU and 10 gigs of SSD. Then, after I set up everything properly, I run docker-compose up --build to see if everything is fine. It launches all. In my docker compose, I use a postgres instance, a redis one and a celery one, and the django application I wrote. If that matters, here is the docker-compose file version: "3.9" services: db: container_name: my_table_postgres image: postgres ports: - 5432/tcp volumes: - my_table_postgres_db:/var/lib/postgresql/data environment: - POSTGRES_DB=my_table_postgres - POSTGRES_USER=dev - POSTGRES_PASSWORD=blablabla redis: container_name: redis image: redis ports: - 6739:6739/tcp environment: - REDIS_HOST=redis-oauth-user-service volumes: - redis_data:/var/lib/redis/data/ my_table: container_name: my_table build: . command: python manage.py runserver 0.0.0.0:5000 volumes: - .:/api ports: - "5000:5000" depends_on: - db - redis celery: image: celery container_name: celery restart: unless-stopped build: context: . dockerfile: Dockerfile command: ['python', '-m', 'celery', '-A', 'mytable' ,'worker', '-l', 'INFO'] volumes: - .:/api depends_on: - redis - my_table links: - redis volumes: my_table_postgres_db: redis_data: Then, all starts up quite slowly, but after I try to make a request from something like postman, in the terminal of docker compose, the main process … -
How to display a custom form with multiple widgets for a field in Django admin?
The Django docs say you can add a form to the admin UI: class ArticleAdmin(admin.ModelAdmin): form = MyArticleAdminForm I want a custom editing UI for a special field in my model, where I display multiple widgets. (It's not exactly the same, but an analogy might be a calendar widget where values on the calendar are editable.) Perhaps I could break the multiple values into multiple database objects and use an InlineAdmin, but I have app-specific reasons to not do that. I thought I'd use a Form object with some custom fields, but Django says it must be a ModelForm: <class 'myapp.admin.MyAdmin'>: (admin.E016) The value of 'form' must inherit from 'BaseModelForm'. Is it possible to display multiple widgets (basically a very custom form) for a single model value in Django admin? -
Django not logging in properly when custom backend and models are used
I'm trying to implement a custom authentication backend in Django but its behaving in a very strange way. The custom backend authenticate against a different model from the usual Django User model an upon successfully verifying the provided credentials the backend get or create our usual Django User instance which it returns. Login nevertheless doesn't work. From the documentation I learnt that I just needed to inherit the django.contrib.auth.backends.BaseBackend and override the authenticate() method which I did. As I've mentioned the custom authenticate() method basically verifies a set of credentials (username and password) against ones stored in the database (custom model, not django.contrib.auth.models.User) which if matched it would get or create an instance of django.contrib.auth.models.User via a proxy model which I named Profile; basically the Profile model has a reference of both django.contrib.auth.models.User and my custom model. When logging in though I keep redirected to the login page (It's like Django logs me in but doesn't set something somewhere such that when I try accessing a protected resource I'm redirected back to login). Also when I login which a django.contrib.auth.models.User object it works just fine and I can access the protected pages. Following are the reasons I opted for this … -
Model change with Celery and Json request list
I have a model and request json list of dicts from api and i need to add or change subject in this model But im not sure that my code is correct , using celery and it`s got an error : " counter_party = CounterParty.objects.get(GUID=item['CounterpartyGUID']) KeyError: 'GUID'" I tried pydantic as well and still coudnt solve this problems models.py class CounterParty(models.Model): GUID = models.UUIDField(default=uuid.uuid4, editable=True, unique=True) name = models.CharField(max_length=150) customer = models.BooleanField(default=False) contractor = models.BooleanField(default=False) class Meta: verbose_name_plural = 'Counter Party' tasks.py from u.celery import * from .models import CounterParty import requests from requests.auth import HTTPBasicAuth @app.task def create_counter_party(): response = requests.get("http://1c-prod-un/bp3/hs/BpAPI/WebApp/GetListCounterparty", auth=HTTPBasicAuth('#some-login', '#some-pass')) rep = response.json() try: for item in rep: counter_party = CounterParty.objects.get(GUID=item['CounterpartyGUID']) for key, value in item.values(): setattr(counter_party, key, value) counter_party.save() except CounterParty.DoesNotExist: for item in rep: new_values = {'GUID': item['CounterpartyGUID'], 'name': item['CounterpartyName'], 'customer': item['Customer'], 'contractor': item['Contractor']} new_values.update(item) counter_party = CounterParty(**new_values) counter_party.save() json request from an api: [ { "CounterpartyGUID": "#some-uuid", "CounterpartyName": "name1", "Customer": false, "Contractor": true }, { "CounterpartyGUID": "#some-uuid", "CounterpartyName": "name2", "Customer": false, "Contractor": true }, ] -
Visual Studio: Django template with DTL. Problem: HTML form tag doesn't accept DTL(Django Template Language) tag with double (")
My problem is when I write the HTML tag with the DTL(Django Template Language) tag for URL, VSC mark it as wrong (the reason is obvious: wrong string detecting). I'm not entirely sure what approach is the most proper. Should I use an escape character for the inner " or write this?: If an escape character is the most proper way how should be constructed? \" seems not working. -
How to solve Django : ModuleNotFoundError: No module named 'djoser'
I have installed djoser on my Django project, however , for some reason, It will not find djoser and throw : "ModuleNotFoundError: No module named 'djoser'" You can see djoser is on my settings.py installed apps and it's installed on my venv, which is also activate. -
Real Time data in Django
I want to observe data changes in real time in python to create a program that show list of online friends (i.e. every time a friend become online or offline I want update a list). I have a function that make an infinite loop to receive the presence a from am XMPP server. I can't seem to figure out how I could receive data in real-time and update. I use Django for backend and i want ti serve this data to a web page to show online Friends. I tried with Channels, but it’s unuseful for this case. s = socket.socket(socket.AF_INET, socket.SOCK_STREAM) sock = ssl.wrap_socket(s, ssl_version=ssl. ssl.PROTOCOL_TLSv1_2) sock.connect((hostname, port)) sock.sendall(“<presence/>”.encode()) while True: response = sock.recv(1024) How can i pass this results to my page view every time i get new update insidie loop? -
Django Project - post a non-empty array using ajax but receive an empty one
My JS goes: (data is not empty in both checkpoint1 and 2) $("#btn_filesUpload").click(async ()=>{ let data = await getFiles() //checkpoint1 $.ajax({ url: '/files_upload/', data: {'data': data}, type: 'post', headers: {'X-CSRFToken': csrftoken }, }).done(function (response) { //checkpoint2 if (response.success){ console.log("Successfully uploaded") } else{ console.log("Uploading failed") } }) }) In view.py def files_upload(request): files = request.POST.getlist('data') print(files) print('----') print(request.POST.getlist) return JsonResponse({ 'success': True }) in the terminal: [] ---- <bound method MultiValueDict.getlist of <QueryDict: {}>> if i replace the data in ajax to data:{'data':[1,2]} it works just fine. <bound method MultiValueDict.getlist of <QueryDict: {'data[]': ['1', '2']}>> Does anyone know why this happens?