Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why I got "http://~" as redirect url parameter althoguh I set "https://~" to LOGIN_REDIRECT_URL in mozilla-django-oidc?
I've been trying to integrate Django app with Keycloak using mozilla-django-oidc and fix the problem as refered to in the title. I configured LOGIN_REDIRECT_URL in settings.py LOGIN_REDIRECT_URL = "https://~" and prepared Django template. {% if request.user.is_authenticated %} <p>Current user: {{ request.user.email }}</p> <form action="{{ url('oidc_logout') }}" method="post"> {{ csrf_input }} <input type="submit" value="logout"> </form> {% else %} <a href="{{ url('oidc_authentication_init') }}">Login</a> {% endif %} However I clicked the "Login", then I got the error message which is invalid redirect url because redirect url parameter was changed to http://~. I looked through the code of mozilla-django-oidc, and seemed that there's no function changing "https://~" to "http://~" as redirect url parameter and set "https://~" to LOGIN_REDIRECT_URL so there might be something wrong with reverse proxy which is Istio in my case. I haven't configured it to anything by myself so far. In case of using Ngnix, this problem can be solved like this. I'd like you to answer what's the cause of problem and how to fix it. I appreciate for your time to read this. -
AttributeError at /login/ 'NoneType' object has no attribute 'has_header'
Я делаю авторизацию на сайте django, используя этот гайд: https://proproprogs.ru/django/delaem-avtorizaciyu-polzovateley-na-sayte. Я создал views class LoginUser(DataMixin, LoginView): form_class = AuthenticationForm template_name = 'shop/login.html' def get_context_data(self, *, object_list=None, **kwargs): context = super().get_context_data(**kwargs) c_def = self.get_user_context(title="Авторизация") return dict(list(context.items()) + list(c_def.items())) потом в urls.py добавил path login urlpatterns = [ path('', index, name='index'), path('add_product', add_product, name='add_product'), path('login/', LoginUser.as_view(), name='login'), ] но при переходе на сайт через http://127.0.0.1:8000/login/ у меня появляется ошибка AttributeError at /login/ 'NoneType' object has no attribute 'has_header' Пытался гуглить но там конкретно такой проблемы как у меня не было, в основном писали про render и HttpRequest, но в моем коде его даже негде написать. Пытался гуглить но там конкретно такой проблемы как у меня не было, в основном писали про render и HttpRequest, но в моем коде его даже негде написать. -
The view products.views.get_product didn't return an HttpResponse object. It returned None instead
ValueError at /product/apple-ipad-air-5th-gen-64-gb-rom-109-inch-with-wi-fi5g-purple/ The view products.views.get_product didn't return an HttpResponse object. It returned None instead. how can i solve this problem please help me ` from django.shortcuts import render,redirect from products.models import Product from accounts.models import * from django.http import HttpResponseRedirect from products.models import * from django.utils.timezone import datetime # Create your views here. def get_product(request, slug): product = Product.objects.get(slug=slug) # comment = Comment.objects.get(slug=slug) if request.method == "POST": star = request.POST.get('star') name = request.user.first_name body = request.POST.get('body') review = Comment(star=star, name=name,body=body,date_added = datetime.today()) review.product = product review.save() return redirect(f'/product/{slug}', slug=product.slug) try: context = {'product': product, } if request.GET.get('size'): size = request.GET.get('size') price = product.get_product_price_by_size(size) context['selected_size'] = size context['updated_price'] = price return render(request, 'product\product.html' , context = context) except Exception as e: print(e) ` i am making a ecommerce website and i add review option then i got this error -
Display messages/notifications in NetBox
I would like some help with messages in NetBox, please. I'm writing a custom validator and I need to display a warning message if for example a device name doesn't fit the company's policy. I can't use the standard fail method in the CustomValidator class - the edit request should be fulfilled, it's just supposed to warn the user as well. I would like to use a box message like this one, just with the warning level. I tried something like this: from extras.validators import CustomValidator from django.contrib import messages class device_validator(CustomValidator): def validate(self, instance): if instance.name is not instance.name.upper(): messages.info(request, "Names of devices should be in all-caps.") return But clearly, my syntax is wrong. I get the "Server Error" window and following message: <class 'NameError'> name 'request' is not defined How do I define the request? Could someone please give me an example how to display a message in this context? Thank you. -
How to create a Django project that allows a User to install plugins from a marketplace Just like WordPress
I would like to create a Django project that allows me to sell services as packages. Here I mean, Users should visit my market place, choose a package they want, then click on Install. Just Like WordPress. This process should automatically do configurations in the background including running the required pip install app commands add the app into installed apps make necessary migrations collect static files I'm confused on how to implement this, and need your help on this. I have been able to create a Django project, and am able to package convert apps into packages. I also understand the consequences of conflicts in migrations and circular dependencies associated with multiple apps. What I want is to allow a user of my system to be able to install a package whenever they need to add it on their options, by just clicking install. -
add a custom attribute to the form using a class based view without use ModelForm class in django
is possible to add a custom attribute (like class="form-control") in all forms of a class based view without define ModelForm? -
Django Add 2 Numbers and get Name and print it back in an html
I'm new to python and django What is the correct syntax to render number and text? I want to get the name and add 2 numbers from addition.html and print it back to results.html I tried this code def add(request): my_context = { "fname" : (request.GET['first_name']), val1 = int(request.GET['num1']), val2 : int(request.GET['num2']), res : val1 + val2 #return render(request, "result.html", {'result': res}) } return render(request, "result.html",my_context) -
how to send data using FCM without a notification message
I am using FCM for my app, which uses Django as the back end and the front end written by flutter. I can send notifications from my Django app in certain situations and it works as expected. All I need now is to send some data to the flutter app which will behave on it somehow, but without sending a message or notification to the user. here is how am sending notifications from my Django backend : from pyfcm import FCMNotification push_service = FCMNotification(api_key="****") def send_single_notification(deviceID,title,body): try: push_service = FCMNotification(api_key="****") registration_id = deviceID message_title = title message_body = body result = push_service.notify_single_device( registration_id=registration_id, message_title=message_title, message_body=message_body) except: print("failed to send notification") def send_multi_notification(list_of_ids,title,body): try: registration_ids = list_of_ids message_title =title message_body = body result = push_service.notify_multiple_devices(registration_ids=registration_ids, message_title=message_title, message_body=message_body) except: print("failed to send notification") just need to send only data .. -
How to render Nextjs pages using django-nextjs on Django
I'm getting ERR_TOO_MANY_REDIRECTS everytime that I'm trying to load http://localhost:8000/about/ despite localhost:8000 loading the next index page correctly. my next about page: function about() { return <h1>about</h1>; } export default about; Django Views from django.http import HttpResponse from django_nextjs.render import render_nextjs_page_sync def index(request): return render_nextjs_page_sync(request) def about(request): return render_nextjs_page_sync(request) Django urls from django.contrib import admin from django.urls import include, path from . import views urlpatterns = [ path('admin/', admin.site.urls), path("", include("django_nextjs.urls")), path("", views.index, name="index"), path("about/", views.about, name="about"), ] https://github.com/QueraTeam/django-nextjs have been following django-nextjs offical docs. Is there something that I'm missing? -
A function passed to Response(APIView) prints normally, but in response returns none
Made a function to generate a report about different models. Applied it on a specified url 'report/', need to make it write "Report "" generated" in a view, but it writes "none", but it prints normally what i need. views.py class Report(APIView): def get(self, request): ro = ADMReport() courses_report = ro.course_report(ro.course_qs) groups_report = ro.studentgroup_report(ro.studentgroup_qs) result1 = ro.report_generating(groups_report) print(result1) result2 = ro.report_generating(courses_report) print(result2) return Response({'Done: ': result1}) services.py class FileManager: @staticmethod def pd_to_excel(report_tuple): report, name = report_tuple pd_report = pd.DataFrame(report, index=list(report.values())[0].keys(), columns=report.keys()) pd_report.to_excel(f'{slugify(name)}_report.xlsx', sheet_name='Sheet1') return f'Report "{name}" generated' urls.py urlpatterns = [ path('', include(router.urls)), # 127.0.0.1/api/v1/courses, 127.0.0.1/api/v1/groups path('report/', Report.as_view(), name='report') Expecting passing returned result looking as "Report "%name%" generated" to APIView instead of "none". -
Is root urls.py means config/urls.py in Django?
I am super newbie on programming using django as a backend. I am making a login function with JWT (using simplejwt). Trying to make it while watching simplejwt official doc, I don't know what is root urls.py means in doc. In the first line of the above picture. "root urls.py" === config/urls.py ?? Am I right...? -
Django and whitenoise - caching "too much"
I am using Whitenoise to serve static files (images, css, js) for a Django site. Now my problem is that the static files seem to be "cached to much"(?) when working locally. Description of actions: Initially my static files are served correctly I edit a file in static/ I run ./manage.py collectstatic (which correctly identifies one updated file). When going to http://127.0.0.1:8000/ my browser consistently shows the old stale version of the file. I have even tried completely removing the generated staticfiles/ folder - and the browser still seems to be able to dig out an old version of the file? This is when running locally in debug mode. Do not have a consistent understanding of how it is in production, but I think it works better (as it should?) there. My configuration: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', .... INSTALLED_APPS = [ # My apps 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] ... ... STATIC_URL = 'static/' STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS = [ ("js" , BASE_DIR / "static/js"), ("css" , BASE_DIR / "static/css"), ("img" , BASE_DIR / "static/img") ] I guess the problem is that I do not really understand the Whitenoise model … -
Django built-in login failed from react
django @method_decorator(csrf_exempt, name='dispatch') class UserLoginView(GenericAPIView): permission_classes = (AllowAny,) serializer_class = UserLoginSerializer def post(self, request): serializer = self.serializer_class(data=request.data) user = serializer.validate(request.data) if user is None: return Response(status=status.HTTP_400_BAD_REQUEST) else: user.before_last_login = user.last_login login(request, user) user.save() user = UserSerializer(user) return Response(data={'id': user.data['id'], 'img': user.data['image']} , status=status.HTTP_200_OK) react const res = await axios.post(`${APIURL}/account/login/`, { id: id, password: pwd, }); when I try to login from react, I get suceessful response( Response(data={'id': user.data['id'], 'img': user.data['image']}, status=status.HTTP_200_OK) ) but failes, still user is annonymousUser in django. How can I fix this error? -
Django. I can't understand the error of removing products from the catalog
I'm making a catalog, I can't understand why products are not displayed by catalog categories, it gives an error 404. The sections in the catalog work as they should. Here is the code: I am grateful in advance for any hint! models.py ` from django.db import models from django.urls import reverse class Catalog_text(models.Model): text_left = models.TextField('Text1') text_right = models.TextField('Text2') signature = models.CharField(max_length=255, verbose_name="Signature") class Meta: verbose_name = 'Text1' verbose_name_plural = 'Text2' class Catalog(models.Model): sections = models.CharField(max_length=150, db_index=True, verbose_name="Name") img = models.ImageField(upload_to='img/catalog/') slug = models.SlugField(max_length=150, db_index=True, unique=True, null=True) class Meta: ordering = ('sections',) index_together = (('id', 'slug'),) verbose_name = 'catalog' verbose_name_plural = 'catalogs' def __str__(self): return self.sections def get_absolute_url(self): return reverse('catalog', kwargs={"slug": self.slug}) class Category(models.Model): catalog = models.ForeignKey(Catalog, related_name='catalog', on_delete=models.CASCADE, verbose_name='Select a directory' ) name = models.CharField(max_length=150, db_index=True, verbose_name="Name") img = models.ImageField(upload_to='img/catalog/') slug = models.SlugField(max_length=200, db_index=True, unique=True, null=True) class Meta: ordering = ('name',) index_together = (('id', 'slug'),) verbose_name = 'Category' verbose_name_plural = 'Categories' def __str__(self): return self.name def get_absolute_url(self): return reverse('catalog-detail', kwargs={"slug": self.slug}) class Product(models.Model): category = models.ForeignKey(Category, related_name='category', on_delete=models.CASCADE, verbose_name='Select a category' ) name = models.CharField(max_length=255, db_index=True,unique=True, null=True, verbose_name="Название") text = models.TextField('Текст') url = models.CharField(max_length=255, db_index=True, verbose_name="Link to the website") pdf = models.FileField(upload_to='pdf/') slug = models.SlugField(max_length=200, db_index=True, unique=True, null=True) class … -
pass loop from view.py to html template in Django
I try to get the data in my models "Machines" and then need to get Additional information form other table related to each machine. I try bellow code in views.py and render it to specified html page. def allmachinesLOGO(request): machines=Machine.objects.all() c="" for m in machines: if m.tb_order_set.filter(status="2").exists(): c="2" else: c="0" context ={'machines':machines,'condition':c} return render(request,'pline/machineslogos.html',context) {% if condition == "2" %} <h4> working</h4> <img class="btn-circle" style="width: 15px" src="{% static 'images/icons/icons8-green-circle-48.png' %}" alt="image" /> {% else %} <h4>stop</h4> {{ condition }} <img class="btn-circle" style="width: 15px" src="{% static 'images/icons/icons8-red-circle-48.png' %}" alt="image" /> {% endif %} what's the correct way to pass loop from views.py to template in Django -
Image files were deleted by itself in AWS-S3
I'm using python Django framework for server and AWS-S3 for store uploaded image. Also, i'm using django-storages library for handle S3. But sometimes images were deleted by itself not through django server. Image urls were still exist in DB. So i changed create, put, delete, get action to get in bucket policy But still deleted by itself. django-storages setting in settings.py is this AWS_SECRET_ACCESS_KEY = S3['secret_key'] AWS_REGION = 'ap-northeast-2' AWS_STORAGE_BUCKET_NAME = 'loopusimage' AWS_S3_CUSTOM_DOMAIN = '%s.s3.%s.amazonaws.com' % ( AWS_STORAGE_BUCKET_NAME, AWS_REGION) AWS_DEFAULT_ACL = None DATA_UPLOAD_MAX_MEMORY_SIZE = 1024000000 FILE_UPLOAD_MAX_MEMORY_SIZE = 1024000000 DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage and changed bucket policy is this "Version": "2012-10-17", "Statement": [ { "Sid": "Statement1", "Effect": "Allow", "Principal": "*", "Action": "s3:GetObject", "Resource": "arn:aws:s3:::loopusimage/*" } ] } What should i do to solve my problem? -
Django disable ForeignKey field in Form
I've been working on a project lately, and I want to disable fields based on different conditions. Now what I wanted to was disabling a models.ForeignKey. But this doesn't work, even though I tried many solutions from multiple forums. I tried this: self.fields["area"].widget.attrs["disabled"] = True``` I already used this in other projects and it worked totally fine. But the select in the Form is still clickable and you can change the choices. Also I tried disabling it in the Widgets directly, didn't work either. -
At the django-admin statics not lodaing /static/admin/css/base.css not found
urlpatterns = [some_urls] + static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) BASE_DIR = os.path.dirname(os.path.dirname(os.path.dirname(os.path.abspath(__file__)))) STATIC_URL = "/static/" STATIC_ROOT = os.path.join(BASE_DIR, "static/") STATICFILES_DIRS = [ os.path.join(BASE_DIR, "static"), ] statics configured DEBUG = TRUE python manage.py collectstatic did 1000 times cache cleared I have no idea what to do, can anyone help me please -
Django SQL: related tables, use latest() on field of parent table
class OrderHeader(models.model): order_id = models.CharField(unique=True,max_length=100) last_modified = models.DateField() class OrderLine(models.model): line_nbr = models.IntegerField(unique=True) order = models.ForeignKey(OrderHeader,on_delete=models.Cascade) class RefundLine(models.model): line_nbr = models.IntegerField(unique=True) order = models.ForeignKey(OrderHeader,on_delete=models.Cascade) refund_type = models.IntegerField(default=1) How do I find the last_modified of RefundLine where refund_type = 1? I can not make head or tail of the django documentation. My guess RefundLine.objects.filter(refund_type=1).latest(order__last_modified) results in an error order__last_modified is not defined -
search/filter dropdown button just refreshes page when clicked? How do I fix this
I'm making a project that includes a button that when clicked, turns into a search bar with a dropdown of filtered results. When the button is clicked, the dropdown and search bar appear, but only for a split second, because the page refreshes and they disappear. How do I fix this? The button is inside of a form. Keep in mind this is a django project. Here is the form with the button included: <form method="post"> <div class="dropdown"> <button onclick="event.stopPropagation(); myFunction()" class="dropbtn">Dropdown</button> <div id="myDropdown" class="dropdown-content"> <input type="text" placeholder="Search Company..." id="myInput" onkeyup="filterFunction()" value="{{company}}"> {% for company in companies %} <a href="#">{{ company.name }}</a> {% endfor %} </div> </div> <input type="date" value="{{ date_applied }}"> {% csrf_token %} <p><input type="submit" value="Add application"></p> </form> Here is the javascript for the button: <script> function myFunction() { document.getElementById("myDropdown").classList.toggle("show"); } function filterFunction() { var input, filter, ul, li, a, i; input = document.getElementById("myInput"); filter = input.value.toUpperCase(); div = document.getElementById("myDropdown"); a = div.getElementsByTagName("a"); for (i = 0; i < a.length; i++) { txtValue = a[i].textContent || a[i].innerText; if (txtValue.toUpperCase().indexOf(filter) > -1) { a[i].style.display = ""; } else { a[i].style.display = "none"; } } } </script> I would really appreciate any guidance. -
Alternative to Heroku to run a non-commercial Django + Postgres app
I created a small volunteering project on Django using Postgres and deployed it to Heroku. From the 28th of Nov 2022, Heroku will remove all the free dynos. I'm not making money on the site, and I guess won't make (at least too much) - so I'm choosing a free alternative to Heroku. I found these services: https://heliohost.org/ https://www.qovery.com But they also didn't work for me. I'm pretty new to web development, so I'm looking for a relatively easy and free solution. There won't be too much traffic on the website. -
I want to implement SSO (Azure AD) on Django admin login but cant figure out how to do that
I'm required to implement SSO on the admin login in a django application. say xyz(dot)com/admin where xyz is my application. so instead of default login procedure I need it through azure ad sso. How should i implement this? I'm fairly new to django and couldent find relevent resources to do so. -
How can I update a OnetoOne related models instance in restframework?
I have two related model a user model and profile model. here's how the data looks like { "id": 2, "phone_number": 9843945748, "email": "someEmial@gmail.com", "profile": { "first_name": "Updated", "last_name": "Updated", "avatar": null, "date_of_birth": "1995-22-01" } } How do I override update() method in serializer to just updated the profile fields. bypassing the USER MODEL required field which is email, phone_number. -
Django and Xcode exception when running website locally
I have a functioning Django site, but when I run the website locally, I get the following exception error. It doesn't appear to occur on the hosted site. Nothing I can find is not working, it is just a puzzle to me why this error is coming up and I would like to fix it because it is annoying - but I don't know where to start looking. Is there a common XCode Django connection that I am overlooking? ---------------------------------------- Exception occurred during processing of request from ('127.0.0.1', 56089) Traceback (most recent call last): File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/socketserver.py", line 683, in process_request_thread self.finish_request(request, client_address) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/socketserver.py", line 360, in finish_request self.RequestHandlerClass(request, client_address, self) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/socketserver.py", line 747, in __init__ self.handle() File "/Users/u1123114/Documents/projects/kinbank_website/website/myvenv/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 171, in handle self.handle_one_request() File "/Users/u1123114/Documents/projects/kinbank_website/website/myvenv/lib/python3.9/site-packages/django/core/servers/basehttp.py", line 179, in handle_one_request self.raw_requestline = self.rfile.readline(65537) File "/Applications/Xcode.app/Contents/Developer/Library/Frameworks/Python3.framework/Versions/3.9/lib/python3.9/socket.py", line 704, in readinto return self._sock.recv_into(b) ConnectionResetError: [Errno 54] Connection reset by peer ---------------------------------------- -
Image files were deleted by itself in AWS S3 bucket [closed]
I'm using python Django framework for server and AWS-S3 for store uploaded image. Also, i'm using django-storages library for handle S3. But sometimes images were deleted by itself not through django server. Image urls were still exist in DB. So i changed create, put, delete, get action to get in bucket policy But still deleted by itself. What should i do to solve my problem?