Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Problem in integrating twak.to with django
Hi guys I thought of adding the chatbot twak.to to my website but i'm unable to. I have used the package django-twakto But confused using its readme file Like from where are {% twakto_tags % } {% twakto_ script %} Totally confusing!! And how to add widget code of twak.to even though I added it to my html file it's still not visible.. Any help will be appreciated? -
how to register a tag in HTML django to make a string lowercase?
I have a python list, iterated over to display a bullet point list on a web page. I want to make each entry in the list lower case, but still keep the original case for what get's displayed. I'm getting the following warning via Django below: TemplateSyntaxError at / Invalid block tag on line 12: 'catEntry', expected 'empty' or 'endfor'. Did you forget to register or load this tag? My html: {% extends "cats/layout.html" %} {% block title %} cats {% endblock %} {% block body %} <h1>All cats</h1> <ul> {% for entry in entries %} {% newEntry= entry.lower() %} <li><a href = 'cats/{{newEntry}}.md' </a>{{ entry }}</li> {% endfor %} </ul> {% endblock %} thanks -
i get "internal server error' when i add 'django_social_share' to my installed app
I have a web app running on AWS LIGHTSAIL, everything works fine, but on installation of 'django_social_share', and addition to my installed app, I get internal server error when the page is refreshed. Removing django_social_share from installed app takes everything back to normal. Please I need help plus if there is any other library I can use to share post. Thanks!! -
Why is my information is not shown from the database
i need help with a db issue in my project. The problem is in saving the order with the attached profile into the DB. It doesn't save the user to the order, and as a result, the order is half-empty sometimes, and when you try to display all orders of the user, you get an empty list. Here is my code. def checkout_success(request, order_number): save_info = request.session.get('save_info') order = get_object_or_404(Order, order_number=order_number) print("Order", order) profile = UserProfile.objects.get(user=request.user) print(profile) # Attach the user's profile to the order order.user_profile = profile order.save() print(order.user_profile) # Save the user's info if save_info: profile_data = { 'default_phone': order.phone, 'default_billingCountry': order.billingCountry, 'default_billingPostcode': order.billingPostcode, 'default_billingCity': order.billingCity, 'default_billingAdress1': order.billingAdress1 } user_profile_form = UserProfileForm(profile_data, instance=profile) print("UPF", user_profile_form) if user_profile_form.is_valid(): print("UPF Valid") user_profile_form.save() messages.success(request, f'Order successfully processed! \ Your order number is {order_number}. A confirmation \ email will be sent to {order.emailAddress}.') if 'cart' in request.session: del request.session['cart'] template = 'checkout/checkout_success.html' context = { 'order': order, } return render(request, template, context) And here is the Order and profie model Model: Order class Order(models.Model): order_number = models.CharField(max_length=35, null=False, editable=False) user_profile = models.ForeignKey(UserProfile, on_delete=models.SET_NULL, null=True, blank=True, related_name='orders') # noqa:501 billingName = models.CharField(max_length=250, blank=True) emailAddress = models.EmailField(max_length=250, blank=True, verbose_name='Email Adress') # noqa:501 phone = … -
After running "makemigrations" and "migrate", the tables are not being created within PostgreSQL
I am trying to add additional tables to my database for a new app I have integrated in to my Django project. When I run the python3 manage.py makemigrations and python3 manage.py migrate, I can see the models have been created however, the relevant tables aren't being added to my database. The tables for Post, Preference and Comment are being added but the tables for Skill, SwapTags, Tagulous_SwapTags_title and Tagulous_SwapTags_hobbies aren't being added. (I can't see any errors to why their not being added) Here is my migrations file: # Generated by Django 3.2.2 on 2021-05-26 15:22 from django.conf import settings from django.db import migrations, models import django.db.models.deletion import django.utils.timezone import tagulous.models.fields import tagulous.models.models class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ] operations = [ migrations.CreateModel( name='Post', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('content', models.TextField(max_length=1000)), ('date_posted', models.DateTimeField(default=django.utils.timezone.now)), ('image', models.ImageField(default='default.png', upload_to='srv_media')), ('likes', models.IntegerField(default=0)), ('dislikes', models.IntegerField(default=0)), ('author', models.ForeignKey(on_delete=django.db.models.deletion.CASCADE, to=settings.AUTH_USER_MODEL)), ], ), migrations.CreateModel( name='Skill', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('name', models.CharField(max_length=255, unique=True)), ('slug', models.SlugField()), ('count', models.IntegerField(default=0, help_text='Internal counter of how many times this tag is in use')), ('protected', models.BooleanField(default=False, help_text='Will not be deleted when the count reaches 0')), ('path', models.TextField()), ('label', models.CharField(help_text='The name of the tag, without ancestors', max_length=255)), ('level', … -
Create a child form and modify parent at same time, Django
I have two models connected with a foreignkey parent and child, i would be able to create a child data and modify at the same time a field present in a parent model. thanks for any help -
convert the mentioned @ users to link in Django
How I can convert the @ + username to link that going to the user profile I by Django Filter My filter Successfully Identifies the users that mentioned @ but it is didn't convert them to link and it should shows @user1 but it shows instead <a href='http://192.123.0.0:8000/user1'>@user1</a> My Filter from django.template.defaultfilters import stringfilter register = template.Library() @stringfilter def open_account(value): res = "" my_list = value.split() for i in my_list: if i[0] == '@': try: stng = i[1:] user = Account.objects.get(username=stng) if user: profile_link = user i = f"<a href='http://192.168.43.246:8000/{profile_link}'>{i}</a>" except Account.DoesNotExist: print("Could not get the data") res = res + i + ' ' return res url_target_blank = register.filter(open_account, is_safe = True) THe filter in html {{ comment.content|open_account }} -
Problem adding user's email in Django admin
I created a custom model extending AbstractUser in order to authenticate users by email instad of by username (but not wanting to drop the username, because it will also be used). This was the first thing I made before running the first migration, everything worked correctly except in the Django admin, when I create a new user, I want these fields to be filled username email password And the admin only ask me for the username and password. How could I add the email too? Here's my codes models.py from django.db import models from django.contrib.auth.models import AbstractUser from django.contrib.auth.base_user import BaseUserManager from django.utils.translation import ugettext_lazy as _ class CustomUserManager(BaseUserManager): """ Custom user model manager where email is the unique identifier for authentication instead of username. """ def create_user(self, email, password, **extra_fields): """ Create and save a User with the given email and password. """ if not email: raise ValueError(_('The Email must be set')) email = self.normalize_email(email) user = self.model(email=email, **extra_fields) user.set_password(password) user.save() return user def create_superuser(self, email, password, **extra_fields): """ Create and save a SuperUser with the given email and password. """ extra_fields.setdefault('is_staff', True) extra_fields.setdefault('is_superuser', True) extra_fields.setdefault('is_active', True) if extra_fields.get('is_staff') is not True: raise ValueError(_('Superuser must have is_staff=True.')) if extra_fields.get('is_superuser') … -
How to access Active directory data to verify user from django model then return data based on that user in Django
The problem to solve is I need to make a URL i.e "http://172.0.0.1:8001/users_data/" which will be used by different machines in a company XYZ. Then in my views by using Active Directory I have to get user (user data) of that machine then I need to verify the user from Django model. After that I've to return data from different tables filtering/based on that specific user. If someone can share the example (using LDAP or any other library) for this ASAP would be very appreciable. -
How to apply background image in django without using css but only in html?
<pre> .container{ width :80%; max-width : 500px; padding: 20px; box-shadow: 10px 10px #E6E6FA; background-image: url("feed7.jpg"); border-radius : 10px; margin-bottom: 10px; margin-top: 50px;`enter code here` } </pre> how to insert background image in style tag in django. -
How to get current base urls path of django app
I'm making a reusable Django app, let's say its name is Polls. This app is supposed to work properly no matter where it's being configured in the urls.py of its parent app. Consider the following structure just like that in the Django tutorial mysite/ manage.py mysite/ __init__.py settings.py urls.py asgi.py wsgi.py polls/ __init__.py urls.py admin.py apps.py models.py views.py So, the polls app has its own urls.py and its own views.py which can be linked to any other app, such a mysite by adding a line to mysite/mysite/urls.py such as line 5 in this example urls.py: from django.urls import path, include urlpatterns = [ path('polls/', include('polls.urls')) ] In this example, all views of the polls app will have a link like https://somedomain.com/polls/the-relative-page-link However, the polls app should still function correctly even if we edited line 5 in the above code to other base path such as: urlpatterns = [ path('another-path/', include('polls.urls')) ] So that would change the like to https://somedomain.com/another-path/the-relative-page-link My problem is that some of the views of the "polls" app contain custom javascript code that communicate with another view that represents a server-side API. So in order for this communication to work properly regardless of whether polls URLs are … -
Django Pinax-notifications errors
I am trying to work with the django pinax-notifications and do not manage to migrate the database. I have followed every steps of the pinax installation tutorial. Is it something to do with the django Pinax template. I have also several times tried to delete the files in my migrations folder. https://github.com/pinax/pinax-notifications I have the following error: File "C:\portal\dashboard\core\urls.py", line 11, in <module> re_path("app/", include(('app.urls','app'), namespace='app')), File "C:\portal\dashboard\env\lib\site-packages\django\urls\conf.py", line 34, in include urlconf_module = import_module(urlconf_module) File "C:\Program Files\Python39\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 986, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 680, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 790, in exec_module File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "C:\portal\dashboard\app\urls.py", line 3, in <module> from app import views File "C:\portal\dashboard\app\views.py", line 18, in <module> NoticeType.create( File "C:\portal\dashboard\env\lib\site-packages\pinax\notifications\models.py", line 47, in create notice_type = cls._default_manager.get(label=label) File "C:\portal\dashboard\env\lib\site-packages\django\db\models\manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "C:\portal\dashboard\env\lib\site-packages\django\db\models\query.py", line 425, in get num = len(clone) File "C:\portal\dashboard\env\lib\site-packages\django\db\models\query.py", line 269, in __len__ self._fetch_all() File "C:\portal\dashboard\env\lib\site-packages\django\db\models\query.py", line 1308, in _fetch_all self._result_cache = list(self._iterable_class(self)) File "C:\portal\dashboard\env\lib\site-packages\django\db\models\query.py", line 53, in __iter__ results = compiler.execute_sql(chunked_fetch=self.chunked_fetch, chunk_size=self.chunk_size) File … -
how to return nested json using django rest framework
I am trying build a REST API using django. here is my models.py and serializers.py. models.py from django.db import models class Person(models.Model): city = models.CharField(max_length=100) dob = models.DateField(editable=True) personName = models.CharField(max_length=100) class Meta: ordering = ['-dob'] serailizers.py from rest_framework import serializers from .models import Person class PersonSerializer(serializers.ModelSerializer): class Meta: model = Person fields = [ 'id', 'city', 'dob', 'personName'] Here is my api - http://127.0.0.1:8000/api/city/Sidney/. I am trying to fetch data by city name. I am getting the json in below format. [{ "id": 1, "city": "Sidney", "personName": "Giles", "dob": "2011-02-02" }, { "id": 5, "city": "Paulba", "personName": "Sidney", "dob": "2016-07-16" }] But i want the json in below shown format - [ { "id": 123, "city": "Sidney", "personInCity": [ { "id": 1, "city": "Sidney", "personName": "Giles", "dob": "2011-02-02" }, { "id": 5, "city": "Paulba", "personName": "Sidney", "dob": "2016-07-16" } ] } ] i am not getting what change needs to be done in Serializers.py -
django: replace values() with filter() or only() but sum in same row
I got a query currently looking like this: a = InventoryStatus.objects.values("city").annotate(Sum("a")).annotate(Sum("b")) city is a choicefield, which means I need to do get_FOO_display() on it, but I can't as values() returns a non-query set of a list of tuples, so everything’s evaluated there already. If I change values() to filter() or only() it works, but assuming I got 2 db inputs, one adding 500 to a and one adding 500 to b, then it would create two rows in my table in the template, instead of summing both fields in same row. How could I get the value from my choicefield and sum both values in the same row? -
Referencing twice related field for django model query
So I am using Django to construct a Query and I have 3 models as defined: class Book(models.Model): ... class Upload(models.Model): ... book = models.ForeignKey(Book, on_delete=models.CASCADE) class Region(models.Model): ... page = models.ForeignKey(Upload, on_delete=models.CASCADE) Given these 3 models I wanted a query that lists all the books and annotate them with a segmented_pages variable that contains the count of all the Upload that have non-zero number of regions. Basically, counting the number of uploads per book that have atleast one region. I am assuming the basic structure of the query would look like this and mainly the logic inside filter needs to be modified as there is no convenient count lookup. Book.objects.annotate(segmented_pages=Count('upload', filter=Q(upload__region__count__gt=0)) Can someone please help me with the logic of the filter and a simple explanation of how to go about designing these types of queries using django models? -
Adding file in django 3.0
I'm trying to add a file in a form.In my views.py i am trying to fetch subject_id from subject model and session_year_id from SessionYearModel. But it is not processing.and gives a message of "Failed to add Notes". Below is the code. My views.py def staff_add_notes_save(request): if request.method != "POST": return HttpResponseRedirect(reverse("staff_apply_leave")) else: subject_id = request.POST.get("subject_id") session_year_id = request.POST.get("session_year_id") notesfile1 = request.FILES["notesfile"] subject_model = Subjects.objects.filter(id=subject_id) session_model = SessionYearModel.object.filter(id=session_year_id) try: notes = Notes.objects.create(subject_id=subject_model,session_year_id=session_model,notesfile=notesfile1) notes.save() messages.success(request, "Successfully added Notes") return HttpResponseRedirect(reverse("staff_add_notes")) except: messages.error(request, "Failed to add Notes") return HttpResponseRedirect(reverse("staff_add_notes")) staff_add_notes.html(TEMPLATE) <form role="form" action="/staff_add_notes_save" method="post" enctype="multipart/form-data"> {% csrf_token %} <div class="form-group"> <label>Subject </label> <select class="form-control" name="subject" id="subject"> {% for subject in subjects %} <option value="{{ subject.id }}">{{ subject.subject_name }}</option> {% endfor %} </select> </div> <div class="form-group"> <label>Session Year</label> <select class="form-control" name="session_year" id="session_year"> {% for session_year in session_years %} <option value="{{ session_year.id }}">{{ session_year.session_start_year }} TO {{session_year.session_end_year }}</option> {% endfor %} </select> </div> <div class="form-group"> <label>Add notes</label> <input type="file" name="notesfile" class="form-control"> </div> <div class="form-group"> {% if messages %} {% for message in messages %} {% if message.tags == 'error' %} <div class="alert alert-danger" style="margin-top:10px">{{ message }}</div> {% endif %} {% if message.tags == 'success' %} <div class="alert alert-success" style="margin-top:10px">{{ message }}</div> {% endif %} {% … -
Using django pytest with multiple config files
I am using Django with multiple configuration files for different environments that get detected automatically. For this, I pretty much have a setup like this: settings |__init__.py |base.py |dev.py |staging.py in init.py I configure how base.py should be extended depending on the environment like this: import os if os.getenv('STAGING_APP', None): from .staging import * else: #dev environment from .dev import * Now when I use pytest, the extensions aren't loaded and the settings are incomplete. The pytest.ini looks like this: DJANGO_SETTINGS_MODULE = settings.base How can I make it clear in the ini file that settings.base has to be extended with either dev or staging? -
Django template blocks not appearing in correct place in rendered template - resulting in jQuery "$ is not defined" error
I am using Django 3.2 This is my base template (snippet): {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <meta name="description" content={% block page_description %}""{% endblock page_description %}> <meta name="keywords" content={% block page_keywords %}""{% endblock page_keywords %}> <link rel='icon' href='{% static "img/favicon.ico" %}' type='image/x-icon'/ > <title>{% block page_title %}Demo{% endblock page_title %}</title> <!-- Bootstrap core CSS --> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/css/bootstrap.min.css" integrity="sha384-B0vP5xmATw1+K9KRQjQERJvTumQW0nPEzvF6L/Z6nronJ3oUOFUFpCjEUQouq2+l" crossorigin="anonymous"> <link rel="stylesheet" href="https://cdnjs.cloudflare.com/ajax/libs/font-awesome/4.7.0/css/font-awesome.min.css" integrity="sha512-SfTiTlX6kk+qitfevl/7LibUOeJWlt9rbyDn92a1DqWOw9vWG2MFoays0sgObmWazO5BQPiFucnnEAjpAB+/Sw==" crossorigin="anonymous" /> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Open+Sans%3A400%2C300%2C500%2C600%2C700%7CPlayfair+Display%7CRoboto%7CRaleway%7CSpectral%7CRubik"> <link rel="stylesheet" href="{% static 'css/footer.css' %}"> <link rel="stylesheet" href="{% static 'css/header.css' %}"> {% block head_styles %} {% endblock head_styles %} {% block head_js %} {% endblock head_js %} </head> <body> {% block header %} {% include "partials/header.html" %} {% endblock header %} {% block messages %} {% include 'partials/messages.html' %} {% endblock messages %} <!-- Page Content --> <div class="d-flex flex-column sticky-footer-wrapper"> {% block content %} {% endblock content %} </div> <!-- jQuery --> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.5.1/jquery.slim.min.js" integrity="sha512-/DXTXr6nQodMUiq+IUJYCt2PPOUjrHJ9wFrqpJ3XkgPNOZVfMok7cRw6CSxyCQxXn6ozlESsSh1/sMCTF1rL/g==" crossorigin="anonymous"></script> <!-- Bootstrap core JavaScript --> <script src="https://cdn.jsdelivr.net/npm/bootstrap@4.6.0/dist/js/bootstrap.bundle.min.js" integrity="sha384-Piv4xVNRyMGpqkS2by6br4gNJ7DXjqk09RmUpJ8jgGtD7zP9yug3goQfGII0yAns" crossorigin="anonymous"></script> <!-- Site footer --> {% block footer %} {% include 'partials/footer.html' %} {% endblock footer %} {% block body_js %} {% endblock body_js %} <script> $().ready(function() { }); </script> </body> </html> /path/to/header.html {% load … -
Password reset view, email is not sending
after resetting password Im instantly redirecting to the password_reset/done view and im not receiving the email. I send email manually to chceck if its working and everything is ok, so the problem is with the " path('password_reset/', auth_views.PasswordResetView.as_view(success_url=reverse_lazy('profile:password_reset_done')), name='password_reset'), ", Is this problem with the app_name or something, I cant find any working solution to this from django.urls import path, reverse_lazy from .views import ProfileDetail, FollowUser, RegisterUser from django.contrib.auth import views as auth_views app_name = 'profile' urlpatterns = [ path('<slug:slug>/profile/', ProfileDetail.as_view(), name='profile-details'), path('follow/', FollowUser.as_view(), name='follow'), path('register/', RegisterUser.as_view(), name='register'), path('login/', auth_views.LoginView.as_view(template_name='registration/login.html'), name='login'), path('logout/', auth_views.LogoutView.as_view(), name='logout'), path('password_reset/', auth_views.PasswordResetView.as_view(success_url=reverse_lazy('profile:password_reset_done')), name='password_reset'), path('password_reset/done/', auth_views.PasswordResetDoneView.as_view(), name='password_reset_done'), path('reset/<uidb64>/<token>/', auth_views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), path('reset/done/', auth_views.PasswordResetCompleteView.as_view(), name='password_reset_complete'), path('password_change/', auth_views.PasswordChangeView.as_view(), name='password_change'), path('password_change/done/', auth_views.PasswordChangeDoneView.as_view(), name='password_change_done'), ] main urls: from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('admin/', admin.site.urls), path('', include('post.urls', namespace='post')), path('profile/', include('user_profile.urls', namespace='profile')), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings config: EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = '587' EMAIL_USE_TLS = True EMAIL_HOST_USER = *** EMAIL_HOST_PASSWORD = *** DEFAULT_FROM_EMAIL = EMAIL_HOST_USER -
Server logged HTTP status code of 200, but Chrome HAR shows 403 - can the HTTP status code change?
I work on an application that uses Django / Gunicorn / Nginx / Amazon Load Balancer (ALB). A user that only has access to Chrome has submitted two different HAR files that have recorded a 403 for a simple JSON API endpoint that hasn't been known to have issues for other users. According to our logs from Nginx and Django middleware, those API requests returned 200 for that particular user. Primary Questions The network - Practically speaking, is there any likely scenario which can cause an intermediary network to change a 200 to a 403 by the intermediary network? For example, is there any plausible scenario in which a compromised router attempting a MITM attack could cause a 200 to change into a 403? The browser - Is there anything in particular about HAR files or Chrome in general which could cause a browser to take a 200 as a 403? For example, if a user's clock is off or a checksum on a packet is invalidated, could that result Secondary questions Nginx - Is there anything that could cause Nginx to record a 200 when a 403 was returned? ALB - Is there any situation in which ALBs can … -
How i can display only products uploaded by particular user?
First, i say that i am new programming django with python. Sorry, if asked small problems. And also , its seems a long code, but very clean. The problem I am facing that I want to display only user's products which is uploaded by him, not by admin or other user. [[like a user using his dashboard and seeing his products and items .]] Here is my models.py: #Product details uploaded class AffProduct(models.Model): product_title = models.CharField(max_length=255) uid = models.IntegerField(primary_key=True) specification = models.CharField(max_length=255) sale_price = models.IntegerField() discount = models.IntegerField() img1 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/") img2 = models.ImageField(max_length=255, null=True, blank=True, upload_to="images/") promote_method = models.TextChoices terms_conditions = models.CharField(max_length=255) promote_method = models.CharField( max_length=20, choices=promote_choices, default='PPC' ) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: app_label = 'affiliation' db_table = 'affproduct' managed = False Here views.py: def AddNewProduct(request): if request.method == "POST": product_title =request.POST['product_title'] uid = request.POST['uid'] specification =request.POST['specification'] sale_price = request.POST['sale_price'] discount = request.POST['discount'] img1 = request.FILES['img1'] img2 = request.FILES['img2'] promote_method = request.POST['promote_method'] terms_conditions = request.POST['terms_conditions'] newproduct = AffProduct(product_title=product_title, uid=uid, specification=specification, sale_price=sale_price, discount=discount, img1=request.FILES.get('img1'), img2=request.FILES.get('img2'), promote_method=promote_method, terms_conditions=terms_conditions) newproduct.save() ##** Here I am trying to fetch products uploaded by the particular user,So i can display products for particular user.{It,s like user using his dashboard … -
Using Django, why do I get a 404-error page not found, when I try to acces a page that should exist?
I made a project called trydjango where I can access products I created with the products/<int:my_id> [name='product'] link, but somehow it isnt working and I cant find the error. When i open http://127.0.0.1:8000/products/1/ , i get a 404 page not found error that looks like this Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/products/1/ Using the URLconf defined in trydjango.urls, Django tried these URL patterns, in this order: products/<int:my_id> [name='product'] products/ [name='product-list'] products/<int:my_id>/delete/ [name='product-delete'] about/ [name='home'] contact/ admin/ create/ initial/ The current path, products/1/, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. even though i have a product with the id=1 saved. I'm using the URL that I have configured in URL's and I can see that a product with the correct id exists when I access it from the page http://127.0.0.1:8000/products/, where I can see a list of all products with their id's. This is my url's: from django.urls import path from pages.views import home_view, contact_view, about_view from products.views import ( product_list_view, product_delete_view, product_create_view, render_initial_data, dynamic_lookup_view, ) urlpatterns = [ path("products/<int:my_id>", dynamic_lookup_view, name='product'), … -
Django-Python log error on MS Azure web app
Good afternoon, we have a Django web app deployed on MS Azure (App Service). We are unable to open correctly the log stream of the Web App by using the shell (local-cmd OR MS Azure shell on dashboard, same error). Here the attempt to open the log stream on Azure dashboard: user@Azure:~$ az webapp log tail --resource-group OUR_RESOURCES_GROUP --name OUR_WEB_APP_NAME Exception in thread Thread-1: Traceback (most recent call last): File "/opt/az/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/opt/az/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "/opt/az/lib/python3.6/site-packages/azure/cli/command_modules/appservice/custom.py", line 2345, in _get_log .decode(std_encoding, errors='replace'), end='') # each line of log has CRLF. File "/opt/az/lib/python3.6/logging/__init__.py", line 1320, in warning self._log(WARNING, msg, args, **kwargs) TypeError: _log() got an unexpected keyword argument 'end' Microsoft support tell us that this is a configuration problem, but we checked some times the python version and the other few configurations. May anyone help ? Thanks -
Put a button in the creation of a model
I would like to make sure that in addition to the title, color and description, I would like to make sure that when I create a model it makes me choose which url to render it when Ia person clicks the button. It's possible? models.py from django.db import models from colorfield.fields import ColorField class Aziende(models.Model): immagine = models.ImageField() nome = models.CharField(max_length=250) prezzo = models.FloatField() descrizione = models.CharField(max_length=250) nome_color = ColorField(default='#FF0000') def __str__(self): return self.nome class Meta: verbose_name_plural = "Aziende" home.html [...] <div class="container"> <div class="row"> {% for Aziende in Borsa %} <div class="col"><br> <div class="container text-center"> <div class="card" style="width: 18rem;"> <img src="{{ Aziende.immagine.url }}" class="card-img-top" alt="..."> <div class="card-body"> <h5 class="title" style="color: {{Aziende.nome_color}}" >{{Aziende.nome}}</h5> <p class="card-text">{{Aziende.descrizione}}</p> <p class="card-text fst-italic text-primary">Valore Attuale: €{{Aziende.prezzo}}</p> <a href="#" class="btn btn-primary">Più info</a> </div> </div> </div> </div> {% endfor %} </div> </div> [...] Thanks in advance! -
Correct approach to creating API endpoints
I'm creating an API in Django Rest Framework and i'm thinking about best approach to provide actions like adding a post to user reading list. Firstly i've done it by GET request, because it was looking most natural and url for example looks like /api/posts/{id}/add_to_reading_list/. Now i recognized that GET should be used only to retrieve data so i've changed it to POST method and now url is looking like /api/posts/add_to_reading_list/. The first thing is that i needed to create new serializer specially to handle this action which accepts only id field, because this endpoint should accept only already created posts. Is it how it should be done? I was thinking about sending whole post object in POST method, but doesn't it a waste of bandwidth when i need only id? It will prevent me of creating a new serializer for this specific case, but i don't think that it is a correct approach.