Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Unexpected Django ORM behavior
I have a function, which must make things according to its name, but it works weird for me. def get_or_create_artists_by_metadata(metadata: Dict[str, str]) -> List[Optional[Artist]]: if artists := metadata.get('artist'): artists = parse_artists_from_string(artists) # returns list of strings try: existing = Artist.objects.filter(title__in=artists) # 1 except Exception as err: log.exception('Database error!') log.exception(err) return [] new_artists_list = list(set(artists) - set(itertools.chain(*existing.values_list('title')))) objs = [Artist(title=artist) for artist in new_artists_list] try: new_artists = Artist.objects.bulk_create(objs) # 2 except Exception as err: log.exception('Error during artists creating!') return [*existing] result = [*existing] if new_artists: # 3 result.extend(new_artists) return result else: return [] For instance, I have 2 strings in artists var. On the step 1 I have nothing at first, empty QuerySet. Then on the step 2 I create new artists and at the same time I have some entries in existing var! So on the step 3 I have true, extend result, and there are 4 entries already. Please, explain me this behavior and how should I manipulate this. -
getting error : ModuleNotFoundError: No module named 'trialrisk.urls' in python
i am new here in django python, right now i am working with rest api, so i have created new app trialrisk, first i have added my app in settings.py file, after then when i am trying to add url in urls.py file i am getting error : ModuleNotFoundError: No module named 'trialrisk.urls' in python, here i have added my whole code and my folder structure, can anyone please look my code and help me to resolve this issue ? Folder Structure settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'trialrisk', ] urls.py from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('/', include('trialrisk.urls')) ] -
how to login in django from custom model
This is my table of register user photo This is model.py class SignupUser(models.Model): name = models.CharField(max_length=100) username = models.CharField(max_length=20) email = models.CharField(max_length=100) password = models.CharField(max_length=20) def __str__(self): return self.username this is my views.py for login my account page through this register user def login_page(request): ''' what code i write here ?? ''' context = {'form': SignupForm} return render(request, 'signup.html', context) please solve my views.py code on my login_page method .What i write here to login in this user profile ? -
How to integrate Flutterwave payment gateway
Does anyone know how to use forloop to get the total cost of product display in Flutterwave? I was able to integrate Flutterwave, but the total cost of my product added to cart is not showing in Flutterwave. -
I am unable to start Gunicorn on ec2 for Django
I am currently trying to set up my django website on ec2. If I run gunicorn --bind 0.0.0.0:8000 website.wsgi:application the website runs as long as I specify port 8000 at the end of the URL. I do not want to have to do this so my end goal is to use nginx. I created my gunicorn.service file via the following command: sudo nano /etc/systemd/system/gunicorn.service Its contents are as follows: [Unit] Description=gunicorn daemon After=network.target [Service] User=root Group=www-data WorkingDirectory=home/ubuntu/Fantasy-Fire/website ExecStart=/home/ubuntu/env/bin/gunicorn --access-logfile - --workers 3 --bind unix:/home/ubuntu/Fantasy-Fire/website/website.sock website.wsgi:application [Install] WantedBy=multi-user.target When I run sudo systemctl start gunicorn I get the following error: Failed to start gunicorn.service: Unit gunicorn.service is not loaded properly: Exec format error. See system logs and 'systemctl status gunicorn.service' for details. The details given via the gunicorn.service are Nov 29 04:34:13 ip-172-31-27-152 systemd[1]: /etc/systemd/system/gunicorn.service:8: Working directory path 'home/ubuntu/Fantasy-Fire/website' is not absolute. I am pretty certain the file path is absolute so I can't seem to find what the issue is. Please let me know if you need any info about my file structure. -
Convert SOAP API(XML) to Rest API (JSON) and visa versa in python
I'm new in SOAP API, i trying to use soap API of simple calculator from "http://www.dneonline.com/calculator.asmx" and my back end work on REST API. Now my problem is first get SOAP API and convert this on JSON and work on REST API and also for user request also comes to JSON form, convert this to SOAP API and send to server. -
google_app_engine runtime process for the instance running on port 46765 has unexpectedly quit
I have successfully installed on Ubuntu digital ocean server but it's automatically close in time interval after 1 or 2 days and need to start again and again on server i have check process on 8000 port is running but on server 8080 its is not working error was port close unexpectedly. I am attach Error image so understand you can understand easily. Error: the runtime process for the instance running on port 46765 has unexpectedly quit ERROR 2019-11-28 05:52:48,879 base.py:209] Internal Server Error: /input/ Traceback (most recent call last): File "/var/www/html/sym_math/google_appengine/lib/django-1.3/django/core/handlers/base.py", line 178, in get_response response = middleware_method(request, response) File "/var/www/html/sym_math/google_appengine/lib/django-1.3/django/middleware/common.py", line 94, in process_response if response.status_code == 404: AttributeError: 'tuple' object has no attribute 'status_code' ERROR 2019-11-28 14:25:50,789 base.py:209] Internal Server Error: /input/ Traceback (most recent call last): File "/var/www/html/sym_math/google_appengine/lib/django-1.3/django/core/handlers/base.py", line 178, in get_response response = middleware_method(request, response) File "/var/www/html/sym_math/google_appengine/lib/django-1.3/django/middleware/common.py", line 94, in process_response if response.status_code == 404: AttributeError: 'tuple' object has no attribute 'status_code' -
ImportError: cannot import name 'views' from 'greetingsApp.views' (Use multiple app in one project)
I am beginner in django, simply i tried to use multiple app in one project i got error: ImportError: cannot import name 'views' from 'greetingsApp.views' project description: /thirdProject /greetingsApp /views.py from django.http import HttpResponse def greetings_view(arg): return HttpResponse(' Good Morning....') /timeApp /views.py from django.http import HttpResponse import datetime def time_view(arg): time = datetime.datetime.now() save = ' Current Server timr'+str(time)+'' return HttpResponse(save) /thirdProject /urls.py from django.contrib import admin from django.urls import path from greetingsApp.views import views as v1 from timeApp.views import views as v2 urlpatterns = [ path('admin/', admin.site.urls), path('greetings/', v1.greetings_view), path('time/', v2.time_view), ] /settings.py INSTALLED_APPS = [ 'django.contrib.admin', ........ 'greetingsApp', 'timeApp', Run: ] F:\djangoProject\thirdProject>py manage.py runserver Error: File "F:\djangoProject\thirdProject\thirdProject\urls.py", line 18, in from greetingsApp.views import views as v1 ImportError: cannot import name 'views' from 'greetingsApp.views' (F:\djangoProject\thirdProject\greetingsApp\views.py) -
Django how to do a conditional redirect after POST?
I have a form that displays some of the fields in the user profile among other things. In this form the fields from the profile are disabled. If the details are outdated the user can go to the edit profile view and update the details. For this, I included a button in the template of the form. After updating the profile I want the user to return to the form. This last part is the one I am having problems with. The link to edit the profile from the form looks like: <a class="btn btn-outline-info" href="{% url 'profile'%}?next={% url 'submission_resume' %}">Edit Profile</a> This is how the url looks comming from the form: http://127.0.0.1:8000/users/profile/?next=/submissions/resume/ The problem is that in the edit profile view I do not know how to implement the conditional redirect: def profile(request): """ View and edit the profile. It requires user to be login """ if request.method == 'POST': form = UserModifyForm(request.POST, instance=request.user) if form.is_valid(): form.save() messages.success(request, f'Your account has been updated!') #??? if next in url go back to the form ??? #??? return redirect(???) ??? #??? else: ??? return redirect('profile') else: form = UserModifyForm(instance=request.user) #--> Dict for template with the forms context = { 'form': form, … -
Django custom log only record custom message not include error message
I have create a custom log, and I only want to store custom message. However when this file have some bugs, this log will also record error log. Anyone know how to achieve this? (I have separate system error log to different file.) from django.http import HttpResponse import logging logging.basicConfig(filename='storage/log/trademoney.log', level=logging.INFO, format='%(asctime)s : %(message)s') def set_log(request): logging.info('ohla') <--custom log return HttpResponse(ohla) <--system error (undefined) log (I want this custom log only store info I setup, I don't want system error log) 2019-11-29 12:22:52,888 : ohla <----I only want this log (I don't want system error log) 2019-11-29 12:22:52,895 : Internal Server Error: /blog/zh_TW/log/ Traceback (most recent call last): File "C:\Python3\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Python3\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python3\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\xampp\htdocs\python\demo\blog\modules\log.py", line 7, in set_log return HttpResponse(ohla) NameError: name 'ohla' is not defined 2019-11-29 12:22:52,897 : "GET /blog/zh_TW/log/ HTTP/1.1" 500 27 -
Opencv Camera Face Detection with Django
I tried to detect face with opencv camera and save the detected face image to database with opencv and django, but it does not seem to work. Any suggestion? while True: # Read the frame _, img = cap.read() # Convert to grayscale gray = cv2.cvtColor(img, cv2.COLOR_BGR2GRAY) # Detect the faces faces = face_cascade.detectMultiScale(gray, 1.1, 4) # Draw the rectangle around each face for (x, y, w, h) in faces: cv2.rectangle(img, (x, y), (x+w, y+h), (255, 0, 0), 2) # Display cv2.imshow('img', img) -
How exactly does django 'escape' sql injections with querysets?
After reading a response involving security django provides for sql injections. I am wondering what the docs mean by 'the underlying driver escapes the sql'. Does this mean, for lack of better word, that the 'database driver' checks the view/wherever the queryset is located for characteristics of the query, and denies 'characteristics' of certain queries? I understand that this is kind of 'low-level' discussion, but I'm not understanding how underlying mechanisms are preventing this attack, and appreciate any simplified explaination of what is occuring here. Link to docs -
Unsure of how to manage email configurations
I am attempting to create Reset Password functionality using Djoser. I am successfully hitting my API's auth/users/reset_password/ endpoint, which is then sending an email as expected. But the problem is occurring in the content of the email. It is sending a redirection link to my api, rather than to my frontend. Please note, any <> is simply hiding a variable and is not actually displayed like that Here is an example of what the email looks like: You're receiving this email because you requested a password reset for your user account at <api>. Please go to the following page and choose a new password: <api>/reset-password/confirm/<uid>/<token> Your username, in case you've forgotten: <username> Thanks for using our site! The <api> team The goal with this email is to send the user to the /reset-password/confirm/ url on my frontend, not on my api, which is currently occurring. Here are my DJOSER settings: DJOSER = { 'DOMAIN': '<frontend>', 'SITE_NAME': '<site-name>', 'PASSWORD_RESET_CONFIRM_URL': 'reset-password/confirm/{uid}/{token}', } The expected behavior is for the DOMAIN setting to alter the link that is being placed in the email, but it is not. I can't seem to find reference to this particular problem within the docs. Any help here would … -
Book choices django
My models: class Book(models.Model): # book types and placed BIOGRAFIA = 1 FANTASTYKA = 2 HISTORYCZNY = 3 HORROR = 4 POEZJA = 5 PRZYGODA = 6 ROMANS = 7 DRAMAT = 8 BRAK = 0 B00K_CHOICES = ( (BIOGRAFIA, 'Biografia'), (FANTASTYKA, 'Fantasy/Sci-Fi'), (HISTORYCZNY, 'Historyczny'), (HORROR, 'Horror'), (POEZJA, 'Poezja'), (PRZYGODA, 'Przygoda'), (ROMANS, 'Romans'), (DRAMAT, 'Dramat'), (BRAK, 'Brak informacji'), ) gatunek = models.IntegerField(choices=B00K_CHOICES, default=BRAK) My views: @login_required def gatunek_lista(request): ksiazki = Book.objects.all() return render(request, 'ksiazki.html', {'ksiazki': ksiazki, 'gatunek': Book.B00K_CHOICES}) My template: For sure something is wrong here for gatunek in B00K_CHOICES: print(choice) ('Biografia', 1, 'Biografia'), ('FANTASTYKA', 2, 'Fantasy/Sci-Fi'), ('HISTORYCZNY', 3, 'Historyczny'), ('HORROR', 4, 'Horror'), ('POEZJA', 5, 'Poezja'), ('PRZYGODA', 6, 'Przygoda'), ('ROMANS', 7, 'Romans'), ('DRAMAT', 8, 'Dramat'), I have a question, how to make my template (html) show all options = B00K CHOICE Please help -
Authentication always return none even though username and password is correct with the database - DJANGO
Before that , i want to say that i already see for many solutions and it still not working , thats why i ask this question So i try to make a login form and a login module , when i insert the username and password correctly -> i already copy the value from the database so it will same 100% ---> but authentication always return none i already print the value into the cmd and what i put is the same as the value in database .. this is the login.html <div id="login-page"> <div class="container"> <form class="form-login" method="post"> {% csrf_token %} <h2 class="form-login-heading">sign in now</h2> <div class="login-wrap"> <input type="text" name="username" class="form-control" placeholder="User ID"> <br> <input type="password" name="password" class="form-control" placeholder="Password"> <br> {% if messages %} <ul class="messages"> {% for message in messages %} <font color="red"><li {% if message.tags %} class="{{ message.tags }}"{% endif %}>{{ message }}</li></font> {% endfor %} </ul> {% endif %} <button class="btn btn-theme btn-block" type="submit" href=""><i class="fa fa-lock"></i> SIGN IN</button> <hr> </form> </div> </div> and this is the views for login and register def login_view(request): if request.method == 'POST': print("yes") username = request.POST.get('username') password = request.POST.get('password') print(username) print(password) guest = User.objects.get(username=username) rolee= UserProfileInfo.objects.get(user_id = guest.id).role print(rolee) user … -
Django Database Model Sum
I have business logic to ranking user by closing rate (selling some item) this is my models class Payments(models.Model): method = models.CharField(max_length=50) class Status(models.Model): status_name = models.CharField(max_length=50) class DataCustomer(models.Model): name = models.CharField(max_length=100, blank=True, null=True) payment_method = models.ForeignKey(Payments, on_delete=models.CASCADE, default=None) sales_name = models.ForeignKey(settings.AUTH_USER_MODEL, default=None, on_delete=models.CASCADE) status = models.ForeignKey(Status, default=None, on_delete=models.CASCADE, blank=True, null=True) If sales selling something with payment method CASH with status Deal get point 13 and if with payment method CREDIT with status Deal get point 8 how can i impelement the query in views.py and in template tag? -
No Post matches the given query. while there are items with same slug
Hi I have been working on a blog app, I can create posts and view them on local host. I then hosted the blog and I get No Post matches the given query. I suspect the problem is with my url from what how others have solved the same problem, but it doesn't work for me. Views.py ]5 -
Combine views in views.py into a single view?
I am building a project in which I have a couple of views in my views.py that I want to combine in a dashboard format (4 views side by side). They are sufficiently complex because each view takes in a number of variables and has a lot of logic server side, and I also intend to use them elsewhere alone. The question I have is what is the best way to combine separate views from views.py into a single view if I want to create a dashboard view (ie. I have a base template with header/footer, and then 4 views embedded in that base). My proof of concept was to call the view with the right variables and decode the rendered return, then pass it as a variable onto the template, and finally just insert it as safe code. See below. My gut tells me this is terrible practice, but I'm not sure the includes/extends system is appropriate for such a use. views.py def view1(request, r1_level, r2_level, d_level, call_code): ... return render(request, 'modules/logic/levels/' + call_code + '.html', { 'indicators': indicators, 'd_level': d_level, 'prof': prof, 'a_flag': a_flag } ) def dashboard(request, level_code): view1 = view1(request, r1_level, r2_level, d_level, call_code).content.decode("utf-8") ... return … -
Django - 'NoneType' object has no attribute 'year'
So every time I try to view someone's profile when they haven't entered a birth day I get this error 'NoneType' object has no attribute 'year'. I followed this post to add the birthday/age to the user profile so no reason to include my code since I got it from here https://stackoverflow.com/a/39761072/12229283. I tried adding a default to the model but that doesn't seem to work how do I make it so if a user doesn't enter a birthday just skip it and ignore it? Thanks -
Django - @login_required decorator while passing arguments with form POST
I am passing a variable from template to view with form POST method. And view uses @login_required decorator as it is needed. If user is not logged in it goes login page and come backs to the view again but the passed variable information was not there anymore. Is there any way to solve this? I found a old stackoverflow post here but it's not working for me. Below is my view function @login_required2 def become_booster(request): print(request.method) if request.method == "POST" or request.method == "GET": email = request.POST.get('email') print(email) user = CustomUser.objects.get(email= email) tiers = Tiers.objects.filter(user=user) form = SubscriptionForm return render(request,'select_tier.html',{'tiers':tiers,'form':form,'creator':user}) -
deploy django to AWS Elastic Beanstalk
I would like to deploy my django project to AWS Elastic Beanstalk. My project was not create through eb-virt. Do I need to redo the project again in eb-virt? I have no idea of how to deploy my project directly. -
Django, display certain hyperlinks based on user group
{% extends 'base.html' %} {% block content %} <p>Welcome to home page.</p> <p>{% user.groups.all() %}</p> {% endblock %} At the moment I'm trying to figure out how I could even get all the user's groups to show on the page. This results in an error.... Invalid block tag on line 5: 'user.groups.all()', expected 'endblock'. Did you forget to register or load this tag? I have tried to do if statements, but it seems break as soon as it meets one condition. For example if user is a part of test1 and test2 groups, I'd like for it to display test1 and test2, but it only displays test1. {% extends 'base.html' %} {% block content %} <p>Welcome to home page.</p> {% if user.groups.all.0.name == "test1" %} <p>test1</p> {% if user.groups.all.0.name == "test2" %} <p>test2</p> {% endif %} {% endblock %} -
issue with bootstrap table plugin when extended from base html
I have issue with extended from base html , to display correctly table with DataTables the table appear but not how its should be with show ,search etc.. its appear as simple table . good table look enter image description here bad table enter image description here in the extended html i use follows shown below structure Any idea? Please advice Thanks {% extends 'base.html'%} {% load staticfiles %} {% block content %} <!--accordion css--> <link href="{% static 'css/tasks_view_style.css' %}" rel="stylesheet"> <!---CSS Bootstrap 4Table--> <link href="{% static 'css/dataTables.bootstrap4.min.css' %}" rel="stylesheet"> <!---Table content--> <div class="card"> <div class="card-body"> <h5 class="card-title">Basic Datatable</h5> <div class="table-responsive"> <table id="zero_config" class="table table-striped table-bordered"> <thead> <tr> <th>Task Name</th> <th>Person Assign</th> <th>Date Sterted</th> <th>Due Date</th> <th>Status</th> <th>Completed</th> </tr> </thead> <tbody> <tr> <td>< alt="user" data-toggle="tooltip" data-placement="top" title="" data-original-title="Steave"> Tiger Nixon</td> <td>System Architect</td> <td>2019/04/25</td> <td>2019/05/25</td> <td><button type="button" class="btn btn-success text-white">In Progress</button></td> <td><div class="progress mt-2" style="height: 20px"> <div class="progress-bar progress-bar-striped font-weight-bold bg-info" style="width: 10%"> 10% </div> </div></td> </tr> </tbody> <tfoot> <tr> <th>Task Name</th> <th>Person Assign</th> <th>Date Sterted</th> <th>Due Date</th> <th>Status</th> <th>Completed</th> </tr> </tfoot> </table> </div> </div> </div> <!---End of Table Content --> </div> </div> <!---End content Table--> </div> </section> {% endblock content %} {% block extra_js %} <!-- Optional JavaScript --> <script … -
Dango/React axios and CSRF Failed: CSRF token missing or incorrect
I know there are all kinds of answers to this sort of question. I have read them. I have tried to implement their suggestions and still I get 403 Forbidden Errors and `CSRF Failed: CSRF token missing or incorrect.' responses. My front end is React and my backend Django with DRF django-rest-auth installed. I have a Login page: Here's the code for that page, pages/Login.js: import React, {useState} from "react"; import {Link, Redirect} from 'react-router-dom'; import axios from 'axios'; import logoImg from "../img/logo.svg"; import {Button, Card, Error, Form, Input, Logo} from '../components/AuthForms'; import {useAuth} from "../context/auth"; import Cookies from 'js-cookie'; function Login(props) { const [isLoggedIn, setLoggedIn] = useState(false); const [isError, setIsError] = useState(false); const [userName, setUserName] = useState(""); const [password, setPassword] = useState(""); const {setAuthTokens} = useAuth(); const referer = props.location.state.referer || '/'; const url = 'http://localhost:8000/rest-auth/login/'; const withCredentials = true; const method = 'post'; const data = {"username": userName, "password": password}; function postLogin() { console.log('XXX postLogin called.'); console.log('postLogin called. username is ' + userName); let cookies = Cookies.get(); const headers = {"Content-Type": "application/json", 'X-CSRFToken': cookies.csrftoken}; console.log('Headers is:', headers); console.log('AAA Cookies:', cookies); const something = axios.request({url, withCredentials, data, method, headers}).then( result => { console.log('postLogin called. username is ' + userName); … -
Sending data from Django application to another Python script
I have a Django application where some data can be saved on my database using a form. I would like to create a Python script that, as soon as a new record is created, sends that data to an external Python script as json, and this external Python script should perform some operation with this data. This question is not about code, but i'm trying to be as specific as possible: is there a way to create a system that sends data to another system? In this case the data i need to send is the records submitted from forms of my Django app to another Python script. I'm supposing that the external script should be listening to some sort of URL, maybe? How could i accomplish this? Maybe with Webhooks?