Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use django default login
I'm trying to use django's default admin login function. This works for logging out, i.e. putting in html: <a href="{% url "log_out" %}"> and in urls.py: from django.contrib.auth.views import LoginView, LogoutView path("log_in/", LoginView.as_view(), name="log_in"), path("log_out/", LogoutView.as_view(), name="log_out"), clicking on the logout link takes the user to the django logout page and works correctly. But trying to do the equivalent to log in, i.e.: <a href="{% url "log_in" %}"> causes a TemplateDoesNotExist error. I would like to use django's default login page rather than creating my own template - how can i do this? -
How can I put the search by at the end ? django, bootstrap5
I'm making a simple website using django and bootstrap5. I've tried the class="de-flex justify-content-end" to put my search by at the end but it doesn't work. this is what it looks like: Here is the code: <body> <nav class="navbar navbar-expand-lg navbar-dark bg-dark"> <div class="container"> <a class="navbar-brand" href="{% url 'my_websites:home' %}"> my website </a> <button class="navbar-toggler" type="button" data-bs-toggle="collapse" data-bs-target="#navbarNav" aria-controls="navbarNav" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarNav"> <ul class="navbar-nav"> <li class="nav-item"> <a class="nav-link" href="{% url 'my_websites:about_me' %}"> About Me </a> </li> <li class="nav-item"> <a class="nav-link" href="{%url 'my_websites:blog' %}"> Blog </a> </li> <li class="nav-item"> <a class="nav-link" href="{% url 'my_websites:contact' %}"> Contact </a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdownMenuLink" role="button" data-bs-toggle="dropdown" aria-expanded="false"> More </a> <ul class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> <li><a class="dropdown-item" href="#">Join our club!</a></li> <li><a class="dropdown-item" href="#">Membership</a></li> <li><a class="dropdown-item" href="#">Be Ullie's friends!</a></li> </ul> </ul> <form class="d-flex justify-content-end"> <input class="form-control me-2" type="search" placeholder="Search" aria-label="Search"> <button class="btn btn-outline-success" type="submit">Search</button> </form> </div> </div> </nav> How do i put the search bar at the end? thank you very much for your response in advance! -
SMTPConnectError at [url] : (421, b'Server busy, too many connections') - Django email
I have a simple method (send_activation_email) called from a view which handles user registration by extending default django user auth. It sends an activation email. Now I get the error: SMTPConnectError at /accounts/register/ - (421, b'Server busy, too many connections') the method implementation: def send_activation_email(user, request): current_site = get_current_site(request) subject = 'Activate your membership Account' message = render_to_string('accounts/account_activation_email.html',{ 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) html_message = get_template('accounts/account_activation_html_email.html').render({ 'user': user, 'domain': current_site.domain, 'uid': urlsafe_base64_encode(force_bytes(user.pk)), 'token': account_activation_token.make_token(user), }) send_mail(subject=subject, message=message, from_email= None, recipient_list=[user.email], html_message= html_message #,fail_silently=False ) I have never come across this issue before and have not found any useful answers searching on here. Clearly, this has to do with SMTP and but the thing is I have had the same error trying different providers: sengrid, zoho, outlook. And definitely, the email goes through on console. The logs: Internal Server Error: /accounts/register/ Traceback (most recent call last): File "C:\Users\[**]\membership\myEnv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\[**]\membership\myEnv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\[**]\membership\accounts\views.py", line 70, in register send_activation_email(user, request) File "C:\Users\[**]\membership\accounts\views.py", line 217, in send_activation_email send_mail(subject=subject, File "C:\Users\[**]\membership\myEnv\lib\site-packages\django\core\mail\__init__.py", line 61, in send_mail return mail.send() File "C:\Users\[**]\membership\myEnv\lib\site-packages\django\core\mail\message.py", line 284, in send return self.get_connection(fail_silently).send_messages([self]) … -
Save a csv like string into Django model
I need to save an amazon response in to mysql db (Django) Here is the example response id purchase-date last-updated-date status 305-0847312-2761164 2022-04-11T22:23:27+00:00 2022-04-11T22:23:31+00:00 Pending 028-3270261-2897162 2022-04-11T22:17:27+00:00 2022-04-11T22:17:30+00:00 Pending 028-8245400-1649940 2022-04-11T22:15:29+00:00 2022-04-11T22:15:32+00:00 Pending 028-2661715-2120359 2022-04-11T21:57:24+00:00 2022-04-11T21:57:28+00:00 Pending 303-9076983-4225163 2022-04-11T21:53:52+00:00 2022-04-11T21:53:55+00:00 Pending 304-7440363-0208337 2022-04-11T21:49:14+00:00 2022-04-11T21:49:17+00:00 Pending 302-2070657-8345128 2022-04-11T21:30:12+00:00 2022-04-12T01:32:20+00:00 Shipped Each header( id, purchase-date, last-updated-date, status ) represents a field in a table, I tried the following code reader = csv.DictReader(res.payload.get("document")) for row in reader: Mytable.Objects.create(field_id=id, **row) Any Idea to achieve this? Regards -
Recommend chatbots similar to CakeChat by LukaLabs
I am currently working on a project to make a Django application that recommends songs based on the tone of the conversation between the user and the chatbot. I had initially planned to use CakeChat, but the project seems to be archived and will not run. I have looked into other options like GPT-3 by OpenAI but am unsure how it will work for my purpose and how to use it. Please recommend options that I can use. I will submit this as my final year graded project in 2 weeks. -
Which Database should I use for developing a Cloud Accounting System like FreshBooks?
I would like to develop a cloud based accounting system with Django. I am planning to use a microservice based architecture. The app will have All-In-One functinalities like: Invoicing Accounting Payments Project Management Client Management etc I understand SQL based databases are best for storing data that are highly relational. But for scalability NOSQL is best. Could you help me decide which one to go for? Thanks. Basically I am looking to make a clone of Freshbooks but with microservice architecture for educational puroposes. -
Django Celery task is showing me "attribute error"?
Hi i build django web application that fetch data from microsoft graph api and inside my django view.py i am calling my task 'add_api_data' from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from datetime import datetime, timedelta from dateutil import tz, parser from tutorial.auth_helper import get_sign_in_flow, get_token_from_code, store_user, remove_user_and_token, get_token from tutorial.graph_helper import * from celery import shared_task import time from tutorial import task import pandas as pd from tutorial.models import demo,assignment_details def education(request): add_api_data = task.add_api_data.delay() api_list = assignment_details.objects.all().values() return render(request, 'tutorial/education.html', {'api_list':api_list,}) def home1(request): context = initialize_context(request) add_data = task.add_csv_data.delay() title1 = demo.objects.all().values() return render(request, 'tutorial/demo1.html',{'title1':title1,'context':context}) my auth_helper.py # Copyright (c) Microsoft Corporation. # Licensed under the MIT License. # <FirstCodeSnippet> import yaml import msal import os import time # Load the oauth_settings.yml file stream = open('oauth_settings.yml', 'r') settings = yaml.load(stream, yaml.SafeLoader) def load_cache(request): # Check for a token cache in the session cache = msal.SerializableTokenCache() if request.session.get('token_cache'): cache.deserialize(request.session['token_cache']) return cache def save_cache(request, cache): # If cache has changed, persist back to session if cache.has_state_changed: request.session['token_cache'] = cache.serialize() def get_msal_app(cache=None): # Initialize the MSAL confidential client auth_app = msal.ConfidentialClientApplication( settings['app_id'], authority=settings['authority'], client_credential=settings['app_secret'], token_cache=cache) return auth_app # Method to generate a sign-in flow def … -
Django Rest Framework: How to make relative URLs clickable?
By passing an empty request to the context of ViewSet, it's possible to have the instance URLs rendered as relative URLs instead of absolute (i.e. the host is omitted). However, when https:// is missing from the URL DRF does not render the string as a clickable URL which makes jumping from one resource to the other rather difficult. -
Internet SPEED TEST using python
I have built a code where I can find out the downloading speed, uploading speed, etc in python. Now I want to give it a shape of a web application.What will be the approach I will take and how to do that any suggestions. -
Change BASE_DIR in django settings to up a directory
I am working on django project in which I tried to setup multiple settings files and now I am getting database migrations error/notification .I dont want to create new db and use the previous one . Previous dir Structure |myproject |-myproject |--settings.py |-db and in my base.py BASE_DIR = Path(__file__).resolve().parent.parent Current Dir |myproject |-myproject |--db(new db after running sever) |--settings |---base.py |---development.py |-db(old db) I dont how base_dir thing works .I want to use my old db and all other stuff .I tried google but I dont understand anything there.so how to I up one dir my BASE_DIR path . Thanks in advance any advice will be helpful. -
Django template tag returns HTML in hex
I created a custom templatetag to make a list, but upon use within a IMG tag, it returns the HTML in HEX. Templatetag from django import template register = template.Library() # use @register.assignment_tag # only when you're working with django version lower than 1.9 @register.simple_tag() def make_list(*args): return args HTML template {% make_list "hyperion_v2" "atomic_api" "full_history" "api_node" as logo_list %} {% for i in logo_list %} {{ i }} <img src="{% static 'images/{{ i }}.png' %}" class="{% if result.{{ i }} == True %}logoGreen{% else %}logoRed{% endif %} servicelogos card-img-top rounded" style="width: 50px; height: 50px;"> {% endfor %} HTML Response: hyperion_v2 <img src="/static/images/%7B%7B%20i%20%7D%7D.png" class="logoRed servicelogos card-img-top rounded" style="width: 50px; height: 50px;"> atomic_api <img src="/static/images/%7B%7B%20i%20%7D%7D.png" class="logoRed servicelogos card-img-top rounded" style="width: 50px; height: 50px;"> full_history <img src="/static/images/%7B%7B%20i%20%7D%7D.png" class="logoRed servicelogos card-img-top rounded" style="width: 50px; height: 50px;"> api_node <img src="/static/images/%7B%7B%20i%20%7D%7D.png" class="logoRed servicelogos card-img-top rounded" style="width: 50px; height: 50px;"> -
Speed up Django bulk_create with unique fields
I have a database with thousands of entries. Each entry has a unique field that I called unique_id and it's calculated on some other fields: class ModelA(models.Model): name = models.CharField(max_length=256, help_text="Type a name") created_at = models.DateTimeField(auto_now_add=True) unique_id = models.CharField(max_length=256, unique=True, editable=False, default=calculate_my_unique_id) This is the algorithm I'm using to prevent duplicates (omitting a bit of code): objectsToAdd = [] items_dict = ModelA.objects.in_bulk(field_name='unique_id') unique_id = generate_unique_id() if unique_id not in items_dict.keys(): objectsToAdd.append( ModelA( name=item_name, unique_id=unique_id ) ) if objectsToAdd: ModelA.objects.bulk_create(objs=objectsToAdd) The problem is that when table items grow, will grow also item_dict list and consequently the check time. Is there a more efficient way to simply skip duplicates from bulk insert? -
django-tinymce working with django-admin but not working in form template
in django admin django-tinymce is working but in template tinymce widget is not working. Please provide a solution django model my model.py class Question(models.Model): nameuser = models.ForeignKey(Profile,on_delete=models.CASCADE) title = models.CharField(max_length=200,blank=True,null=True) timestamp = models.DateTimeField(auto_now_add=True) contents = tinymce.HTMLField(blank=True,null=True) tags = models.ManyToManyField(Tags) id = models.UUIDField(default=uuid.uuid4, unique=True,primary_key=True,editable=False) form.py class QuestionForm(forms.ModelForm): class Meta: model = Question fields = ('title','contents','tags') def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields['title'].widget.attrs.update({'class': 'form-control','placeholder':'Enter Title'}) self.fields['tags'].widget.attrs.update({'class': 'form-control'}) in temlate it show only blank form-control template view -
Django admin: how to increase field label width in admin change form view?
I want to customize Django admin change_form.html template for some of my model. I would like to increase field label size and try by ovverriding change_form.html template. But it dosen't work. My own change_form.html is displayed but css style is not applied . When I open debug, an error is raised for change_form.js: django is not defined change_form.html {% extends "admin/change_form.html" %} {% load static %} {% block extrahead %} <!-- Custom --> <link rel="stylesheet" href="{% static 'ecrf/css/custom_change_form.css' %}"> {% endblock %} custom_change_form.css // pat is one of my field .column-pat { color: red !important; min-width: 200px; } admin.py class VisiteAdmin(SimpleHistoryAdmin): list_display = ('pat','vis_dat',timing_visit,'sai_log','sai_dat','ver','ver_usr','ver_dat') change_form_template = 'ecrf/admin/change_form.html' -
flutter web with django on diffrent host make error minifield:b6
hi guys i have one host my flutter web run on it and another one for django to send data to my flutter web after go to my website my site not show parametr just show this error minifield:b6 and in offline all works...like this: what can i do to solve this issue Doctor summary (to see all details, run flutter doctor -v): [√] Flutter (Channel beta, 2.9.0-0.1.pre, on Microsoft Windows [Version 10.0.19044.1586], locale en-US) [√] Android toolchain - develop for Android devices (Android SDK version 32.0.0) [√] Chrome - develop for the web [√] Android Studio (version 2020.3) [√] Connected device (2 available) • No issues found! [enter image description here][1] [1]: https://i.stack.imgur.com/Og2MG.jpg -
run django project without databasei,removed this code find some errors like this," settings.DATABASES is improperly configured."
DATABASES{ 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'xys', 'USER': 'postgres', 'PASSWORD': 'xyz', 'HOST': 'localhost', 'PORT': '5432', } No need of this code in django settings. My requirement in my project no need database in django settings -
How can i fix filter and pagination to work
I am trying to filter items based on prince range and then paginate the result. I have gone through the documentation but still doesnt work. i have tried all the logics i could come up with but not working still. Kindly help out if you know any means I can fix the error. The search shows the first page items but once i click on the subsequent pages, it doesnt display anything.If i use 'if request.Method==''POST:"',IT shows ,variable used before assignment. I aslo tried using 'if request.method =="GET" but it still didnt work. The search shows the first page items but once i click on the subsequent pages, it doesnt display anything.If i use 'if request.Method==''POST:"',IT shows ,variable used before assignment. I aslo tried using 'if request.method =="GET" but it still didnt work. Below is the code: # model.py class Property(models.Model): name =models.CharField(max_length=200) price = models.IntegerField(default=1000) bedroom = models.IntegerField(default=1) bathroom =models.IntegerField(default=1) status =models.CharField(max_length=200,blank=True,null=True) sqft =models.CharField(max_length=10,blank=True,null=True) acre =models.CharField(max_length=10,blank=True,null=True) Location = models.CharField(max_length=200,blank=True,null=True) describe =models.CharField(max_length=200,blank=True,null=True) img = CloudinaryField(blank=True,null=True) def __str__(self): return self.name class Meta: #db_table='accommodation' verbose_name_plural='Property' # view.py #i dont know if there's an error here because it doesnt show any result apart from the first page def availableProperty(request): #if request.method =="POST": name … -
Image sometimes does not display in HTML page (Django 3.0)
I created a somewhat clone of Instagram main page (for full transparency, please know that I do this for a psychological experiment). One of my users got a very strange bug : when going on my page, two images seemed to not be loaded (there was no broken link, and the images simply appeared to be skipped, see illustration below). Images not displaying illustration On reloading the page, the images indeed appeared normally, and other users did not get any bug. The thing is, I do not quite understand how this could happen, since I show the page only when all resources are loaded, through these lines of code : window.addEventListener('load', function () { document.getElementById("main-page").style.visibility = "visible"; }); Please find the code for the page below (I removed navbar code for lisibility, please let me know if full version is needed). <body id="main-page" style="visibility:hidden"> <section class="main"> <div class="wrapper"> <div class="left-col"> {% include 'instapp/status.html' %} {% include 'instapp/post.html' %} </div> <div class="right-col"> {% include 'instapp/recommandations.html' %} </div> </div> </section> <script> window.addEventListener('load', function () { document.getElementById("main-page").style.visibility = "visible"; }); </script> </body> And here is the code for displaying a single post : {% load static %} <div class="post"> <div class="info"> <div class="user"> … -
Django table connection based on the value type
I really want some help with this problem, because somehow I cannot solve it. The problem: I have a Parameter table, which is stores parameters I want to store the values in different parameters, based on the type of the parameter These are the type models: class JsonParameter(models.Model): value = models.JSONField() class StringParameter(models.Model): value = models.CharField(max_length=100) class DateParameter(models.Model): value = models.DateField() And I have a parameter model: class Parameter(TimeStampedModel): name = models.CharField(max_length=64) is_mandatory = models.BooleanField(default=True) value = SomekindOfMagic() So if I would like to create some parameters, like this param_1 = Parameter.objects.create(name="name of the param", is_mandatory=True, value="This is a string value") param_2 = Parameter.objects.create(name="name of the param", is_mandatory=True, value='{"object": "string"}') param_3 = Parameter.objects.create(name="name of the param", is_mandatory=True, value="2022-03-20") The param_1.value will be saved into the StringParameter table, the param_2.value will be saved into the JsonParameter table, and the param_3.value will be saved into the DateParameter table and the Parameter.value will contain a foreign key like object. Can I use the generic foreign key for this? Or do I have to use something else ? There is any solution for this ? Thanks guys :) -
Django HTML minifer removes closing tags for HTML and body
My django template renders this: <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <title>List of events</title> <link rel="stylesheet" href="/static/COMPILED/css/styles.css" /> <script src="/static/js/main.js"></script> </head> <body> <!-- insert default navigation text for every page --> aaaaaaaaaaaa </body> </html> When enabling the html minifier: INSTALLED_APPS = [ ... 'django_minify_html', ] MIDDLEWARE = [ ... 'django_minify_html.middleware.MinifyHtmlMiddleware', ] Now I get this: <!doctypehtml><html lang=en><meta charset=utf-8><title>List of events</title><link href=/static/COMPILED/css/styles.css rel=stylesheet><script src=/static/js/main.js></script><body> aaaaaaaaaaaa This is not a valid HTML. It is missing </body> and </html>. What is wrong? -
Signal Problem in creating instance of my model
please help I have a problem I'm trying to write a signal in my code when the user registers, create a portfolio and profile for the user, it can create a user and profile and portfolio correctly but when I want to create a market in admin(because only admin can create a market, not user) I got an error from my signal this line('instance.Portfolio.save(market=instance)'), My Signal @receiver(post_save, sender=User) def create_user_portfolio(sender, instance, created, **kwargs): if created: Portfolio.objects.create(user=instance) @receiver(post_save, sender=Market) def save_user_portfolio(sender, instance, **kwargs): instance.Portfolio.save(market=instance) And it is my portfolio model class Portfolio(models.Model): name = models.CharField(max_length=50, blank=False, null=True, default='portfolio') user = models.ForeignKey('accounts.User', on_delete=models.DO_NOTHING, related_name='investor') assets = models.ManyToManyField(Assets, related_name='assets') My user model class User(AbstractBaseUser, PermissionsMixin): username = models.CharField(max_length=255) email = models.EmailField(max_length=255, unique=True, db_index=True) is_verified = models.BooleanField(default=False) is_active = models.BooleanField(default=True) is_staff = models.BooleanField(default=False) is_author = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) auth_provider = models.CharField( max_length=255, blank=False, null=False, default=AUTH_PROVIDERS.get('email')) I have to say my portfolio and user are in a different app And it's my market model maybe you need it class Market(models.Model): name = models.CharField(max_length=50, unique=True, blank=False, null=False) currency = models.CharField(max_length=25, blank=False, null=False) My error is: 'Market' object has no attribute 'Portfolio' -
How to send user data and its profile image using POST request from axios api to Django Rest Framework?
User Data let final_data = { 'personal_data': { 'first_name': data.first_name, 'password': data.password, 'phone': data.phone, 'username': data.username, 'email': data.email, 'image': data.profile[0] }, 'address_data': { "address_1": data.address_1, "address_2": data.address_2, "city": data.city, "pin_code": data.pin_code, "state": data.state, "country": data.country } } Above Code is my form data which i have passed. I had also tried to pass this data using json.stringify still it not works AXIOS POST Request import API from "../Axios/AxiosService" const registerUser = (data) => API.post(`registration/`, data) export default { registerUser } HEADERS if (config.url = 'registration/') { requestOptions['headers'] = {'Content-Type': 'multipart/form-data;boundary=----WebKitFormBoundaryyrV7KO0BoCBuDbTL', 'Accept' : 'application/json'} } else { requestOptions['headers'] = {'Content-Type': 'application/json'} } if (localStorage.getItem("access_token")) { requestOptions['headers'] = {"Authorization": "Token " + localStorage.getItem("access_token")} } Above Code is AXIOS POST Request and also Passed headers accrodingly. Using Application/Json i get all data except image and from data i also tried to pass data.profile instead of data.profile[0] but it didn't works. Django Rest Framework error **In POST method of Django Rest Framework i had used below listed ways to get but in all methods i didn't get any data ** request.POST request.data request.Files -
How to change the name of image while uploading
models.py def productFile(instance, request, filename): old_name = str(filename) new_name = "http://" + str(request.get_host()) + "/"+ str(instance.id)+".png" renamed_image = os.rename(old_name, new_name) return 'profile/'.join( [renamed_image] ) class User(models.Model): mobile = models.CharField(max_length=20) otp = models.CharField(max_length=6) name = models.CharField(max_length=200) username = models.CharField(max_length=200) profile_dp = models.ImageField(upload_to = productFile ,null=True, blank=True) profile_url = models.CharField(max_length=200) settings.py STATIC_URL = '/static/' STATIC_ROOT = BASE_DIR / 'staticfiles' STATICFILES_DIRS = [BASE_DIR / 'static'] MEDIA_URL = '/images/' MEDIA_ROOT = BASE_DIR /'static/images' Required Output When i upload image in profile_dp the name image name should change into this format("http://" + str(request.get_host()) + "/"+ str(instance.id)+".png") Error i am getting productFile() missing 1 required positional argument: 'filename' -
Button for selection data of database from django app
enter image description hereI have a django app and database I need to create a button in my index.html , you click on it and can choose wich country you want to select but i have a probleme my button is like in the picture I have all the names in the same line and i have words .. who can help me ? I created models: class Country(models.Model): id = models.IntegerField(primary_key=True) name = models.CharField(max_length=1, blank=True, null=True) class Meta: db_table = 'country' def __str__(self): return f'{self.name}' my index.html <form method="POST"> <div class="form-group"> <div class="input-group"> <div class="input-group-prepend"> <span class="input-group-text"> <i class="fa fa-arrow-circle-o-right"></i> </span> </div> <select name="start_time" id="id_start_time" class="form-control"> <option>{{name}}</option> </select> </div> <!-- input-group.// --> </div> <!-- form-group// --> <div class="form-group"> <div class="input-group"> -
Openlitespeed - Unable to load static files in production
I am using a ubuntu server with openlite speed and cyberpanel. I have successfully deployed my app but regarding the static files, the browser throughs an error saying 'refused to load as its MIME type....', I have tried to include my static files in app/public/static folder and collectstatic command worked fine. but my static files are not loaded yet. In my settings.py I have given STATIC_URL = 'python/static/' STATIC_ROOT = '/home/example.com/public_html/public/static' & also tried, STATIC_URL = '/static/' STATIC_ROOT = '/home/example.com/public_html/public/static' Kindly guide me to solve this issue.