Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Inventory table and sales table - Python | django
I created an inventory table called Products. How do I make a sales table with the products in the inventory table and the products in the sales table replicate according to the quantity in the inventory table. And when I sell a product in the sales table, it decreases in the quantity of the stock table. -
How to Call Two Fields From One Model in Django View
I now have a model and I want to display two fields of it in the same view.Then display them in the details template. What is the best way to do that? my model: class Book(models.Model): class Meta : verbose_name_plural = 'Books' category = models.ForeignKey(Categorie,on_delete=models.CASCADE,null=True, related_name="apps") book_slug = models.SlugField(blank=True,allow_unicode=True,editable=True) book_title = models.CharField(max_length=50 , null=True) book_picture = models.ImageField(upload_to='imgs' , null=True) book_description = RichTextUploadingField(null=True,blank=True) book_size = models.CharField(max_length=20 , null=True) book_created_at = models.DateField(auto_now_add=True) book_updated_at = models.DateField(auto_now=True) book_auther = models.CharField(max_length=100 , null=True) my views: def book_details(requset ,book_slug): book = get_object_or_404 (Book, book_slug = book_slug) try : book = Book.objects.filter(book_slug = book_slug) except : raise Http404 similar_books = Book.objects.filter(book_auther = book_slug) ------ >>> Here is my query context ={ 'book' :book, 'similar_books':similar_books, } return render( requset,'book.html',context) my template: <div class="row"> {% for b in book %} <div> <img src="{{ b.book_picture.url }}" class="Rounded circle Image" height="150" width="150" alt=""> <a href="{{b.get_absolute_url}}">{{b.book_title}}</a> </div> {% endfor %} </div> <div class="row"> {% for sb in similar_books%} <div> <img src="{{ sb.book_picture.url }}" class="Rounded circle Image" height="150" width="150" alt=""> <a href="{{sb.get_absolute_url}}">{{sb.book_title}}</a> </div> {% endfor %} </div> -
Stock checker in python, test several objects simultaneously
Ultimately, my goal is to to know if one of my users submitted an existing Stock Symbol in my webapp's form. So, I have a string with several words. I want to identify an active finance symbol (EURUSD=X, AAPL, ...). Because the string will count no more than 10 words, I decided to test all word independently through a yfinance request. If the stock symbol exists, Yahoo API will send me data, otherwise there is an error message 'Unknown Stock symbol'. import yfinance as yfs string = str("23/01/2023 24/02/2021 hello Xlibidish sj monkey jhihi EURUSD=X") x = string.split() #API CALL Tickertest = yf.Ticker(x) ainfo = Tickertest.history(period='1y') print(len(ainfo)) Therefore, I need a function that: split all string's variable into words. Done. Test all words, one by one in the API Identify the API call that sends data (might be done with a length condition as the unknown symbols all have length < 40. -
Reverse for 'update-project' with arguments '('',)' not found. 1 pattern(s) tried: ['update\\-project/(?P<pk>[0-9]+)/\\Z']
Trying to create an update function for a Project Model in Django but i've run into a problem. Here's what i have so far update view function @login_required def updateProject(request, pk): project = Project.objects.get(id=pk) form = ProjectForm(instance=project) if request.method == 'POST': project.name = request.POST.get('name') project.description = request.POST.get('description') project.save() return redirect('project', pk=project.id) context = {'form': form, 'project': project} return render(request, 'projects/project_form.html', context) This is how I'm calling it in the template <li><a href="{% url 'update-project' project.id %}">Edit</a></li> and this is what the urlpattern is path('update-project/<int:pk>/', views.updateProject, name='update-project'), What am I missing? -
Use Python/Django Virtual Environment without MySQL
I'm following this tutorial for beginner Python/Django in VS Code: https://code.visualstudio.com/docs/python/tutorial-django I ran the following commands in my workspace folder: py -3 -m venv .venv .venv\scripts\activate The first command ran fine, but the second errored out: 'MySQL' is not recognized as an internal or external command, operable program or batch file. I see many answers for how to solve this online... by installing MySQL. But I don't want to use MySQL in the app I'm building. So, my question is... how do I remove this dependency that seems to have added itself? Note: I looked in the activate script, and I don't see anything directly referencing MySQL there, so I'm at a bit of a loss as to why it's trying to invoke it at all. Is MySQL just a base dependency of Python? -
django adding real time probelm
this is html include that add the product and make multi adding random , once it dosnt make duplicate , and once work normally . {% load i18n %} {% load static %} <form > <div class="tab_content active" data-tab="fruits"> <div class="row "> {% for productss in my_products %} <div class="col-lg-3 col-sm-6 d-flex " > <div class="productset flex-fill" > <div class="productsetimg"> {% if productss.product_icon %} <img src="{% url 'productss.product_icon.url' %}" alt="img"> {% else %} <img src="{% static 'assets/img/product/product1.jpg' %}" alt="img"> {% endif %} <h6>{% translate "Qty" %}: {{productss.bpq_real_quantity}}</h6> <div class=""> <i class=""></i> </div> </div> <div class="productsetcontent"> <h4><span id="productee_namee{{productss.id}}">{{productss}}</span></h4> <h6>{{productss.bpq_product_sell_price}}</h6> <div class="increment-decrement"> <div class="input-groups"> <input type="button" value="-" onclick="decrementValue{{productss.id}}()" class="button-minus dec button"> <input type="text" name="child" value="1" class="quantity-field" id="plus_field{{productss.id}}" name="quantity_required"> <input type="button" value="+" onclick="incrementValue{{productss.id}}()" class="button-plus inc button" > <input type="submit" value="{% translate "Add" %}" id="add_item_{{productss.id}}"> </div> </div> </div> </div> </div> </form> <script> console.log('plus_field{{productss.id}}') function incrementValue{{productss.id}}() { var value = parseInt(document.getElementById('plus_field{{productss.id}}').value, 10); value = isNaN(value) ? 0 : value; value++; document.getElementById('plus_field{{productss.id}}').value = value; } function decrementValue{{productss.id}}() { var value = parseInt(document.getElementById('plus_field{{productss.id}}').value, 10); value = isNaN(value) ? 0 : value; if (value > 1 ) { value--; } document.getElementById('plus_field{{productss.id}}').value = value; } </script> {% comment %} var quantity = $("#quantity_required").val(); $.ajax({ type: "POST", url: {% url … -
Create the cXML punch-out API in the Determine P2P application django project
I created an e-commerce site with django. I would like to integrate a cxml punchout to link the ecommerce site and the systems of my buyers, I would like to know here how to configure the cXML file below: <?xml version="1.0" encoding="UTF-8"?> <!DOCTYPE cXML SYSTEM "http://xml.cxml.org/schemas/cXML/1.2.028/cXML.dtd"> <cXML payloadID="?" timestamp="?" xml:lang="en-US"> <Header> <From> <Credential domain="?"> <Identity>?</Identity> </Credential> </From> <To> <Credential domain="?"> <Identity>?</Identity> </Credential> </To> <Sender> <Credential domain="?"> <Identity>?</Identity> <CredentialMac type="FromSenderCredentials" algorithm="HMAC-SHA1-96" creationDate="?" expirationDate="?">?</CredentialMac> </Credential> <UserAgent>Test</UserAgent> </Sender> </Header> <Request deploymentMode="test"> <PunchOutSetupRequest operation="create"> <BuyerCookie>1234ABCD</BuyerCookie> <Extrinsic name="User">which user</Extrinsic> <BrowserFormPost><URL>https://example.com/?BrowserFormPost</URL></BrowserFormPost> <Contact> <Name xml:lang="en-US">myname</Name> <Email>whichmail@email</Email> </Contact> <SupplierSetup><URL>https://testapp.com/?SupplierSetup</URL></SupplierSetup> </PunchOutSetupRequest> domaine of my app : www.testapp.com For other information how to inform them ??? to adapt it to my project -
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