Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Python SMTP - 'linesep' is an invalid keyword argument for encode()
I'm getting the following error in my Django project: 'linesep' is an invalid keyword argument for encode() Python version 3.8.2 and Django version 3.2.4. Here is my code. I'm getting the error when sendmail is being executed. try: sender = settings.SMTP_HOST_USER message = html_message msg = MIMEText(message, 'html') msg['Subject'] = subject msg['From'] = sender msg['To'] = recipient server = smtplib.SMTP(settings.SMTP_HOST, settings.SMTP_PORT) server.login(settings.SMTP_HOST_USER, settings.SMTP_HOST_PASSWORD) server.sendmail(sender, recipient, msg.as_string()) server.quit() return True except Exception as exp: print(str(exp)) return False -
How to pull random images from database(admin) in Django?
I want to pull random images from database with there id number This is my models.py code and Here i am making id field , name and image field from django.db import models from django.db import models from os import listdir import os.path from django.conf import settings from os.path import isfile from os.path import join as path_join from random import choice import internship.settings def random_img(): dir_path = os.path.join(internship.settings.BASE_DIR, 'media') files = [ content for content in listdir(dir_path) if isfile(path_join(dir_path, content)) ] return choice(files) # Create your models here. class images(models.Model): id_no = models.IntegerField() name = models.CharField(max_length=20) image = models.ImageField(upload_to='images') so i want to pull out and show it in a template but everytime i reload the page i need to show a new images .. So How can i do that? i cant able to get the logic -
Taking input, processing it in python code and display output in tables on html page
I am quite new to Django and struggling to do something very simple. I want to convert Boolean expressions into truth table using Django framework. I have python code I wanna know how I can connect it in a way that input from html goes to that python code, gets processed and output is displayed in tables on html page. -
How to write a SQL equivalent right join and insert in Django
I'm trying to convert a SQL query using Django ORM but not getting how to implement the right join and insert in a single query. Below is my SQL query insert into product_inventory ([material_stock] ,[opening_stock] ,[combined_string]) select product_inventorytemp.[material_group] ,product_inventorytemp.[opening_stock] ,product_inventorytemp.[combined_string] from product_inventory right outer join product_inventorytemp on product_inventorytemp.combined_string = product_inventory.combined_string where product_inventory.combined_string IS NULL Below is the Django ORM query that I have tried so far ProductInventory.objects.filter( combined_string__isnull=True ).select_related() Can someone please help me highlight what exactly wrong is with my ORM query, or it would be good to provide an example? Thanks in advance. -
Django: "Login with Facebook" button not working after deployed to pythonanywhere
When I run the app in localhost, it works fine. but after deployed to pythonanywhere, Login with Facebook button doesn't work. when I refresh Login page, in console, it shows => Failed to load resource: https://username.pythonanywhere.com/static/facebook/js/fbconnect.js the server responded with a status of 404 (Not Found) Refused to execute https://username.pythonanywhere.com/static/facebook/js/fbconnect.js as script because "X-Content-Type: nosniff" was given and its Content-Type is not a script MIME type. in template: <a href="{% provider_login_url 'facebook' method='js_sdk' %}"><button class="effect" style="width: 100%; background-color: rgb(58, 110, 255); height: 36px; border: none; color: white; border-radius: 3px; display: flex; justify-content: center;align-items: center;"><img style="height: 24px; width: 24px; background-color: white; padding: 1px; border-radius: 50%;" src="{% static 'images/fblogo.png' %}" alt=""><span style="margin-top: 2px; display: block; margin-left: 8px; font-size: 16px;"> Login with Facebook</span></button></a> <br> Another problem is: CSS doesn't load in admin page how to fix this? -
Caps between card elements
I have Bootstrap card elements in django project. How i can remove caps from card elements? Image <div class="container"> {% for post in posts %} {% if forloop.counter0|divisibleby:3 %} <div class="row text-center"> {% endif %} <div class="col-md-4" onclick="window.location.href=''" style="cursor: pointer"> <div class="card bg-light mb-3" style="max-width: 18rem;"> <div class="card-content"> <div class="card-header"><h4>{{ post.Otsikko| safe }}</h4></div> <p>{{ post.Lisätietoja| safe }}</p> <div class="card-footer"<small>{{ post.Lisätty| safe }}</small></div> </div> </div> </div> {% if forloop.counter|divisibleby:3 or forloop.last %}</div>{% endif %} {% endfor %} </div> -
How to get request.GET.get('variable') in multiple value
How to get the multiple value in input form html to django. I only get the first input value Enroll but when I click the second button which is Payment I cannot get the value also in third input I don't know if the JavaScript is the problem or in my views.py - Beginner programmer :( html and javascript <html> .... <script> function newAppend(name, img, side){ const msgCHAT = ` <div class="msg ${side}-msg"> <div class="msg-img" style="background-image: url(${img})"></div> <div class="msg-bubble"> <div class="msg-info"> <div class="msg-info-name">${name}</div> <div class="msg-info-time">${formatDate(new Date())}</div> </div> <div class="msg-text"><p>How can I help you?</p></div> <br> <div class="butnew"> <button type="submit" class="input-bot" name="input_text" id="inputBot" value="Enroll">Enrollment</button> <button type="submit" class="input-bot" name="input_text" id="inputBot" value="Pay">Payment</button> <button type="submit" class="input-bot" name="input_text" id="inputBot" value="Hi">Hi Username</button> </div> </div> </div> `; msgerChat.insertAdjacentHTML("beforeend", msgCHAT); msgerChat.scrollTop += 500; // =================================================================== const msgerInputTwo = get(".input-bot"); document.getElementById("inputBot").addEventListener("click", event => { event.preventDefault(); const msgTextTwo = msgerInputTwo.value; appendMessage(PERSON_NAME, PERSON_IMG, "right", msgTextTwo); botResponse(msgTextTwo); }); } function botResponse(rawText) { // Bot Response $.get("/chatbot/post", {input_text: rawText }).done(function (data) { console.log(rawText); console.log(data); const msgText = data; appendMessage(BOT_NAME, BOT_IMG, "left", msgText); }); } </script> </html> views.py def chatbot_process(request): ..... message = request.GET.get('input_text') message = message.lower() ints = predict_class(str(message)) response = get_response(ints, intents) response = str(response) return HttpResponse(response) def chatbot(request): return render(request, "chatbot/chatbot.html") URLS.py … -
why i am unable to send email to user to verifiy for completing registeration in django webapp
i want to send user a confomation eamil for sucessfull registeration instead of sending the mail template is showing in my terminal and not sending to user email id here is my code for user registeration my views.py class SignUpView(View): form_class = SignUpForm template_name = 'register.html' def get(self, request, *args, **kwargs): form = self.form_class() return render(request, self.template_name, {'form': form}) def post(self, request, *args, **kwargs): form = self.form_class(request.POST) if form.is_valid(): user = form.save(commit=False) user.is_active = False # Deactivate account till it is confirmed user.save() current_site = get_current_site(request) subject = 'Activate Your MySite Account' message = render_to_string('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), }) user.email_user(subject, message) messages.success(request, ('Please Confirm your email to complete registration.')) return render( request, 'activation_sent_success.html') return render(request, self.template_name, {'form': form}) class ActivateAccount(View): def get(self, request, uidb64, token, *args, **kwargs): try: uid = force_text(urlsafe_base64_decode(uidb64)) user = User.objects.get(pk=uid) except (TypeError, ValueError, OverflowError, User.DoesNotExist): user = None if user is not None and account_activation_token.check_token(user, token): user.is_active = True user.profile.email_confirmed = True user.save() login(request, user) messages.success(request, ('Your account have been confirmed.')) return redirect('accounts:home') else: messages.warning(request, ('The confirmation link was invalid, possibly because it has already been used.')) return redirect('accounts:home') my tokens.py file for genrating random token from django.contrib.auth.tokens import PasswordResetTokenGenerator … -
Django: prevent making migrations for some models
Django 3.2.6 I'd like some models not to made migrations at all. Is it possible? I tried: 1. https://docs.djangoproject.com/en/3.2/ref/models/options/#managed class Meta: managed = False 2. class PrimaryReplicaRouter: special_model_names = {'generalsettings', 'generalsettings', } def allow_migrate(self, db, app_label, model_name=None, **hints): if model_name in self.special_model_names: return False return True It doesn't help: migrations are created.It doesn't migrate. But migrations become unnecessarily noisy. I quote from here: https://docs.djangoproject.com/en/3.2/topics/db/multi-db/#allow_migrate makemigrations always creates migrations for model changes, but if allow_migrate() returns False, any migration operations for the model_name will be silently skipped when running migrate on the db. Well, I don't want to make migrations for some models. Is it possible? -
How to resolve Django server startup error
I am facing below error sporadically when i start my Django server. Please help me to resolve this issue. ERROR: File "/usr/lib/python3.8/asyncio/locks.py", line 164, in __init__ self._loop = events.get_event_loop() File "/usr/lib/python3.8/asyncio/events.py", line 639, in get_event_loop raise RuntimeError('There is no current event loop in thread %r.' **RuntimeError: There is no current event loop in thread 'django-main-thread'.** -
React + Django send raw password in HTTP request, security discussion
I am new to Django and I am working on the user authentication part. I used the Django provided User model, and use auth() and login() method when the user login. I have a question about the password security and hope have some discussion here. When the auth() function hashed the raw password and then compares the username and the hashed password. That means the front end needs to send the password in raw data. (Otherwise, it will be hashed twice). Is it not safe to send the password in raw data? If I want to hash the password in the frontend then send the request to Django, what can I do in this case? -
React CkEDITOR Image upload to django backend
I have used React as fronted and DRF for API and Django as backend. I have a ckeditor in React and want to upload a image from ckeditor. How can I acheive that -
DJANGO many to one
I need your help, is really basic. I have two models, Autor and Post with a many to one relationship. I'm having problems retrieving the data in the html page. What I want to do is list all the posts for a specific Autor within a FOR and besides that I need to show the first name and last name of the autor out of the FOR. I really appreciate your help. class Autor(models.Model): first_name = models.CharField(max_length=30, null=False, verbose_name='First Name') last_name = models.CharField(max_length=30, null=False, verbose_name='Last Name') def __str__(self): return self.first_name class Meta: db_table = 'autor' verbose_name = 'Autor' verbose_name_plural = 'Autors' ordering = ['id'] class Post(models.Model): autor = models.ForeignKey(Autor, on_delete=models.CASCADE) post = models.CharField(max_length=200, null=False, verbose_name='Post') def __str__(self): return self.post class Meta: db_table = 'post' verbose_name = 'Post' verbose_name_plural = 'Posts' ordering = ['id'] ``` -
django let's me save a model correctly via admin but not form/shell
I am having difficulty saving a Django model instance into my db. The instance consists of a FileField, which I think is what is causing the difficulty. My model is as follows: class initial_settings(models.Model): name = models.CharField(max_length=30, unique=True) epsilon = models.FloatField(default = 0.3) document = models.FileField(upload_to='documents/') def __str__(self): return self.name And when I open up a shell, create an instance, and save, I then run the command test = initial_settings(name = 'test1234', epsilon = 3, document = 'doc.csv').save() pd.DataFrame(csv.reader(open(test.document.path, 'r'))) Gives me an error, No such file or directory . But, if I open up the admin console and create an instance, it saves correctly and I am able to load it from shell. In the admin console, I can see that the instance created in shell is not being saved to the correct location ('media/documents') but instead direct to root dir, but I am not sure why. Any assistance is appreciated! P.S: Settings.py MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') -
How to make a button send data to a django function with ajax
What I am trying to do is create an html button that grabs data from the page and sends it to a django function. The button is not linked to a form or anything. I am relatively new to django and I have tried a billion different approaches to this problem with no success. Any suggestions would be greatly appreciated. -
Django - Fastest way to query multiple primary keys in order to create a list of model attribute and uuid to return?
So I have a functionality that should return a list of a user's followers, with the uuid and follower username. The reason the User username isn't the PK is because I'm using amplify and it returns a UUID for user id. As you can see below I'm just querying for all followers of a user then doing a for loop to get each followers user name and creating a dict with uuid and username that goes into a list. I have concerns this will be pretty slow. Is there a quicker way to do this? Model.py class AbstractBaseModel(models.Model): uuid = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created = models.DateTimeField('Created at', auto_now_add=True) updated_at = models.DateTimeField('Last updated at', auto_now=True, blank=True, null=True) class Meta: abstract = True def __repr__(self): return f'<{self.__class__.__name__} {self.uuid}>' class User(AbstractBaseModel): username = models.CharField(max_length=255, unique=True) email = models.EmailField(max_length=255, unique=True) class FollowUser(AbstractBaseModel): follower_id = models.ForeignKey(User, on_delete=models.CASCADE, related_name="follower_following") followee_id = models.OneToOneField(User, on_delete=models.CASCADE, related_name="followee_followed_by") View.py @api_view(['GET']) def get_followers(request, followee_id): try: followers = FollowUser.objects.filter(followee_id=followee_id).values_list('follower_id', flat=True) followers_list = list(followers) data = list() for follower_uuid in followers_list: try: username = User.objects.get(pk=follower_uuid).username except User.DoesNotExist: return Response(dict(error=f'follower id: {follower_uuid} does not exist in User model'), status=status.HTTP_400_BAD_REQUEST) data.append(dict(username = username, id = follower_uuid)) response_data = dict(followers=data) return JsonResponse(response_data, status=status.HTTP_200_OK) except FollowUser.DoesNotExist: return … -
Static files like JS not loading on Elastic Beanstalk Python 3.8
I am currently leaning to code and am trying to deploy a Django project using elastic beanstalk. I have added these lines of code to .ebextensions/django.config option_settings: aws:elasticbeanstalk:container:python: WSGIPath: myapp.wsgi:application aws:elasticbeanstalk:environment:proxy:staticfiles: /media: /media /static: /myapp/static And container commands container_commands: 01_migrate: command: "source /var/app/venv/*/bin/activate && python3 manage.py migrate" leader_only: true 02_collectstatic: command: "source /var/app/venv/*/bin/activate && python3 manage.py collectstatic" option_settings: aws:elasticbeanstalk:application:environment: DJANGO_SETTINGS_MODULE: myapp.settings I have already created superuser, so I removed the line that creates one. I deployed with these files, but my app on production server is ugly because static files are not loading. This screenshot is the login page of django admin. And these are error messages that say it couldn't find any static files. Here's my configuration on EB console Thank you in advance. -
Django Unique Key on M2M Table
Is there a way to tell Django to create unique key based on a M2M relation? I have the following table and I want the host_id and hostname_id pair to be unique. Table (app_host_names) id host_id hostname_id models.py class Hostname(models.Model): name = models.CharField(max_length=150, unique=True, blank=False, null=False) class Host(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) names = models.ManyToManyField(Hostname) -
Why can't I use projectname.file to import
I add a custom_site.py in my project, But I can't import it in admin.py and urls.py. I try to use sys, and use Pycharm to mark them as Sources Root, but it still can't import! It always Report an error like: from typeidea.custom_site import custom_site ModuleNotFoundError: No module named 'typeidea.custom_site' Why typeidea.custom_site can't import? I wonder. My project directory and my code are here: admin.py urls.py custom_site.py Project directory NEED HELP!!! Please help me as much as possible! The sooner the better! THANK YOU VERY MUCH! -
Creating a Jira issue through OAuth 2.0 (3LO) app fails with the error {"code":401,"message":"Unauthorized"}
I’m an intern developer and I’m integrating a product with the Jira software (cloud). I’m using python and Django web frameworks for development. I followed the https://developer.atlassian.com/cloud/jira/platform/oauth-2-3lo-apps/ documentation and successfully received the access token. The steps I followed are: Created an OAuth 2.0 (3LO) app in the developer console. Configured permissions for ‘Jira platform REST API’ and ‘User identity API’. I selected the rotating refresh tokens option. Added the callback URL as ‘http://localhost:8000/callback’ Direct user to authorization URL to get the authorization code. In the Authorization URL scope is defined as follows: scope = ['write:jira-work read:jira-user read:me read:jira-work'] As the response receives the code and state variables. Exchanged the code value to the access token. The received response is as follows: {"access_token":"token value appears here","scope":"write:jira-work read:jira-work read:jira-user read:me","expires_in":3600,"token_type":"Bearer"} Successfully received the clould_id using the access token. header = {'Authorization': 'Bearer {}'.format(client.token['access_token']), 'Accept': 'application/json'} response = requests.get('https://api.atlassian.com/oauth/token/accessible-resources', headers=header) Retrieved the public profile of the authenticated user successfully. response = requests.get('https://api.atlassian.com/me', headers=header) When I tried to create an issue, it ends up with the following error: {"code":401,"message":"Unauthorized"}. I’m referring to https://developer.atlassian.com/cloud/jira/platform/rest/v3/api-group-issues/#api-rest-api-3-issue-post I am using email (logged-in user email) and API token to authorize. Is there any problem with my auth parameter? It … -
why is django running extra queries (session, auth, time)
I'm trying to optimize my django queries using django-debug-toolbar My actual query is just a simple getter as you can see as the 4th one in this list: QUERY = 'SELECT SYSDATETIME()' - PARAMS = () 15.89 QUERY = 'SELECT TOP 21 [django_session].[session_key], [django_session].[session_data], [django_session].[expire_date] FROM [django_session] WHERE ([django_session].[expire_date] > %s AND [django_session].[session_key] = %s)' - PARAMS = (datetime.datetime(2021, 8, 21, 2, 24, 45, 234137), 'xx') QUERY = 'SELECT TOP 21 [auth_user].[id], [auth_user].[password], [auth_user].[last_login], [auth_user].[is_superuser], [auth_user].[username], [auth_user].[first_name], [auth_user].[last_name], [auth_user].[email], [auth_user].[is_staff], [auth_user].[is_active], [auth_user].[date_joined] FROM [auth_user] WHERE [auth_user].[id] = %s' - PARAMS = (30,) 15.87 QUERY = 'SELECT [mm_asset_type].[id], [mm_asset_type].[name], [mm_asset_type].[description] FROM [mm_asset_type]' - PARAMS = () However, just for that getter it's taking 50ms because of the first 3 queries. The individual time taken are: 15ms 16ms 15ms 8ms Is there some setting I can use to optimize this or remove these queries? -
NotImplementedError: `create()` must be implemented
If you see here, please stay. Thank you very much report errors:NotImplementedError: create() must be implemented. this's my class: class BookCreateView(CreateModelMixin, GenericAPIView): serializer_class = BookSerializer def post(self, request): return self.create(request) But there are already crate() out of CreateModelMixin So why does it report an error? -
Multiple processes spawning by Supervisorctl and stopping is not killing all of them
My supervisor config to start the django process is- [program:school] command=/usr/bin/python3 /home/pranavtotala48/blue_mountain/manage.py runserver 0.0.0.0:80 stdout_logfile=/home/pranavtotala48/supervisor_logs/logs.log directory=/home/pranavtotala48/blue_mountain user=root autostart=true autorestart=true stopsignal=QUIT On Starting the Supervisor school program, two python processes are started. And stopping the supervisor program only kills one process. Page up pranavtotala48@instance-2:~$ ps aux | grep 80 root 80 0.0 0.0 0 0 ? I< Aug20 0:00 [kblockd] root 324 0.0 0.4 280208 17996 ? SLsl Aug20 0:06 /sbin/multipathd -d -s systemd+ 421 0.0 0.1 26612 7480 ? Ss Aug20 0:00 /lib/systemd/systemd-networkd daemon 590 0.0 0.0 3800 2292 ? Ss Aug20 0:00 /usr/sbin/atd -f root 733 0.0 0.4 928352 18028 ? Ssl Aug20 0:04 /usr/bin/google_guest_agent _chrony 1325 0.0 0.0 4696 180 ? S Aug20 0:00 /usr/sbin/chronyd -F -1 root 9013 0.0 0.2 13808 9040 ? Ss 00:46 0:00 sshd: pranavtotala48 [priv] pranavt+ 9250 0.0 0.0 8168 732 pts/0 R+ 01:13 0:00 grep --color=auto 80 pranavtotala48@instance-2:~$ pranavtotala48@instance-2:~$ sudo supervisorctl start school school: started pranavtotala48@instance-2:~$ ps aux | grep 80 root 80 0.0 0.0 0 0 ? I< Aug20 0:00 [kblockd] root 324 0.0 0.4 280208 17996 ? SLsl Aug20 0:06 /sbin/multipathd -d -s systemd+ 421 0.0 0.1 26612 7480 ? Ss Aug20 0:00 /lib/systemd/systemd-networkd daemon 590 0.0 0.0 3800 2292 … -
Utilizing a Django slug, getting a no reverse path error
My apologies if you've already read a previous post I made about my Django slug problem. I cleaned up my old code, and perhaps have a better understanding of what I'm doing but I'm still lost as how to get a URL generated from a slug to work on my main landing page. I'm working on a portfolio. I have a landing page where I'm going to link out to individual detail pages. I'm using get_absolute_url in my models to do this. When testing this out, I can get the link to work on the individual project detail page, but not on the main landing pages. Which is funny, because I don't need these links to work on the individual project pages. My guess is that something in my views is not set up correctly. My views.py is set up like this: from django.shortcuts import render, get_object_or_404, get_list_or_404 from .models import Project def home(request): projects = Project.objects.all() return render(request, 'portfolio/home.html', {'projects': projects}) def individual_project_view(request, project_id): projectpage = get_list_or_404(Project, slug=project_id) return render(request, 'portfolio/project_detail.html',{'projectpage':projectpage}) def project_home(request): portfolioprojects = get_list_or_404(Project) return render(request, 'portfolio/project_detail.html', {'portfolioprojects':portfolioprojects}) And here is my urls.py for the individual landing pages, which are in a separate app. from django.contrib import … -
Django builtin url 'logout' reverse URL is returning a relative path
Been searching but can't find this specific issue. I created a separate app for my user authentication (name: user) and included the URLS using django.contrib.auth.urls. Login works. Logout fails. When using the named view {% url 'login' %} the path is absolute, and works fine (i.e. http://host/user/login). When using the named view {% url 'logout' %} in the same template, it gets a relative path to my displayed app. (i.e. http://host/app1/user/login) Django Directory: - djangoProject - djangoProject - app1 - user Django app settings (djangoProject/settings.py): INSTALLED_APPS = [ 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'user', 'app1', ] Django app URLS (djangoProject/urls.py) urlpatterns = [ path('app1/', include('app1.urls')), path('admin/', admin.site.urls), path('user/', include("django.contrib.auth.urls")), path('user/', include("user.urls")) // in case I add custom pages ] User App URLS (user/urls.py - nothing added, as using from django.contrib.auth.urls): urlpatterns = [ ] User App Views (user/views.py - nothing added. using built in django.contrib.auth): Now, in app1/templates/base.html, I use the following: {% url 'login' %} - which generates the URL - http://host/user/login/ {% url 'logout' %} - which generates the URL - http://host/app1/user/logout If I manually enter the URL http://host/user/logout I get logged out and redirected correctly. Any thoughts? Thanks so much!