Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Connecting to external web socket api from Django
I am trying to connect to slack RTM(Real time messaging) api and update the database with the messages coming from the slack channel. How should I do that. Should I run a web-socket client in the background? If so, How to integrate the web-socket client with the Django application. Is celery, something that I should look into? I was looking into this for the past few hours. Went through a lot of questions. I am not able to figure out the right approach to do that. Any help is appreciated. -
How to convert excel file to pdf file in django
views.py: def getexcel(request): payload = json.loads(request.body.decode('utf-8')) if payload['type'] == 'excel': response = HttpResponse(content_type='text/xls') response['Content-Disposition'] = 'attachment; filename="EHR.xls"' wb = xlwt.Workbook(encoding='utf-8') #adding sheet ws = wb.add_sheet("sheet1") row_num = 0 font_style = xlwt.XFStyle() font_style.font.bold = True columns = ['Patient Id', 'OP No', 'First name', 'Middle Name', 'Last name', 'Full Name', 'Age', 'Gender', 'Phone Number', 'Address', 'Email address', ] for col_num in range(len(columns)): ws.write(row_num, col_num, columns[col_num], font_style) # Sheet body, remaining rows font_style = xlwt.XFStyle() #get your data, from database or from a text file... patients = models.PatientMaster.objects.filter(Q(emp_dept_id=payload['department_n_key']) & Q(created_on__range=(payload['fromdate'],payload['todate']))) for patient in patients: row_num = row_num + 1 ws.write(row_num, 0, patient.patient_id, font_style) ws.write(row_num, 1, patient.op_no, font_style) ws.write(row_num, 2, patient.first_name, font_style) ws.write(row_num, 3, patient.middle_name, font_style) ws.write(row_num, 4, patient.last_name, font_style) ws.write(row_num, 5, patient.full_name, font_style) ws.write(row_num, 6, patient.age, font_style) ws.write(row_num, 7, patient.gender, font_style) ws.write(row_num, 8, patient.phone_number, font_style) ws.write(row_num, 9, patient.address, font_style) ws.write(row_num, 10, patient.email, font_style) wb.save(response) print(response) return response Here i have done code for download Excel file. Its working fine. at the same way i want to download PDF or convert excel to PDF. For PDF i have tried some code: def getpdf(request): response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'attachment; filename="file.pdf"' p = canvas.Canvas(response) p.setFont("Times-Roman", 55) p.drawString(100,700, "Hello, World.") p.showPage() p.save() return response In the … -
Python passing list of dicts to nested for loop and functions gets list indice must be integer error [on hold]
Trying to make a database population script. There are pages, with each page having a title and a URL. python_pages = [ {"title": "Official Python Tutorial", "url":"https://docs.python.org/3/tutorial/"}, #changed to py3 url #clipping part after last / from all urls (i.e. "index.html" {"title":"How to Think like a Computer Scientist", "url":"http://www.greenteapress.com/thinkpython/"}, {"title":"Learn Python in 10 Minutes", "url":"https://www.stavros.io/tutorials/python/"}, ] #url changed from book django_pages = [ {"title":"Official Django Tutorial", "url":"https://docs.djangoproject.com/en/2.1/intro/tutorial01/"}, {"title":"Django Rocks", "url":"http://djangorocks.com"}, {"title":"How to Tango with Django", "url":"http://www.tangowithdjango.com/"} ] other_pages = [ {"title":"Bottle", "url":"http://bottlepy.org/docs/dev/"}, {"title":"Flask", "url":"http://flask.pocoo.org"} ] Then there are categories of pages, with each category having the following keys and values Category:{Pages] Views:# Likes:# I would like to use one function to create each category (in django although most of this is not django-related). The original script (https://pastebin.com/Q09XJtvX) used a single dictionary for the categories, like so: cats = {"Python": {"pages": python_pages}, "Django": {"pages": django_pages}, "Other Frameworks": {"pages": other_pages} } and the following for loop and functions to make categories and pages: for cat, cat_data in cats.items(): c = add_cat(cat) for p in cat_data["pages"]: add_page(c, p["title"], p["url"]) #print check for c in Category.objects.all(): for p in Page.objects.filter(category=c): print("- {0} - {1}".format(str(c), str(p))) #bracketed numbers are placeholders for later outputs (str c … -
django.urls.exceptions.NoReverseMatch: Reverse for 'account_inactive' not found. 'account_inactive' is not a valid view function or pattern name
I am using django-rest-auth registration api, I overridden that by using my own SERIALIZER and model. So I am getting error. I have tried by setting active at the time user created. But that is not working. Let me know how to resolve this type of problem. [12/Jan/2019 17:24:06] "POST /rest-auth/registration/ HTTP/1.1" 400 68 Internal Server Error: /rest-auth/registration/ Traceback (most recent call last): File "/Users/test/project/vblah/lib/python3.6/site-packages/django/core/handlers/exception.py", line 34, in inner response = get_response(request) File "/Users/test/project/vblah/lib/python3.6/site-packages/django/core/handlers/base.py", line 126, in _get_response response = self.process_exception_by_middleware(e, request) File "/Users/test/project/vblah/lib/python3.6/site-packages/django/core/handlers/base.py", line 124, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/test/project/vblah/lib/python3.6/site-packages/django/views/decorators/csrf.py", line 54, in wrapped_view return view_func(*args, **kwargs) File "/Users/test/project/vblah/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/Users/test/project/vblah/lib/python3.6/site-packages/django/utils/decorators.py", line 45, in _wrapper return bound_method(*args, **kwargs) File "/Users/test/project/vblah/lib/python3.6/site-packages/django/views/decorators/debug.py", line 76, in sensitive_post_parameters_wrapper return view(request, *args, **kwargs) File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_auth/registration/views.py", line 46, in dispatch return super(RegisterView, self).dispatch(*args, **kwargs) File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_framework/views.py", line 495, in dispatch response = self.handle_exception(exc) File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_framework/views.py", line 455, in handle_exception self.raise_uncaught_exception(exc) File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_framework/views.py", line 492, in dispatch response = handler(request, *args, **kwargs) File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_framework/generics.py", line 192, in post return self.create(request, *args, **kwargs) File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_auth/registration/views.py", line 65, in create user = self.perform_create(serializer) File "/Users/test/project/vblah/lib/python3.6/site-packages/rest_auth/registration/views.py", line 81, in perform_create None) File "/Users/test/project/vblah/lib/python3.6/site-packages/allauth/account/utils.py", line 183, in complete_signup … -
Transferring Data from a Form to a django View
I have a form: class GenereteReport (forms.ModelForm): olddate = DateField (widget = forms.DateInput (attrs = {'type': 'date'})) newdate = DateField (widget = forms.DateInput (attrs = {'type': 'date'})) class Meta: model = Transactions fields = ['typeOper', 'category'] I need to select data from a database ranging from olddate to newdate class ChartData (APIView): authentication_classes = [] permission_classes = [] def get (self, request, format = None): labels = [] default_items = [] transacts = Transactions.objects.all () for transact in transacts: labels.append (transact.category.name) default_items.append (int (transact.suma)) data = { "labels": labels, "default": default_items, } return response (data) what to do instead of transacts = Transactions.objects.all () to select data in the date range that is in the form from the base link to the repository https://github.com/IvanYukish/PersonalFinanceManager -
Django Model - JOIN Tables without adding models
I have two databases to connect to for my Django App. I have only read access for one of the database, from where I want to pull only a few columns for my model into the other database where I have read and write access. It does not make sense to 'inspectdb' the read access databases with 100+ tables and the 100+ columns for just a few columns. How do I add the column from another database to my existing model in the simplest manner using a join? Can I use a raw sql query with parameters to add the field into my model? class APPNAME(models.Model): class Meta: db_table = 'APPNAME' item= models.PositiveIntegerField(db_column='Item') issue = models.CharField(max_length=200, db_column='Issue') detail = models.TextField(db_column='Detail') created_at = models.DateTimeField(auto_now_add=True, db_column='Create Datetime') updated_at = models.DateTimeField(auto_now=True, db_column='Update Datetime') external_column = How to join this column??? -
Django apps , functionalities and models
This is a pretty beginner question, as i have recently learned Django, I have these questions since i could not find a clear answer for any. Suppose that we want to build a voting system, and we have users with votes, i have a confusion with the admin user, i should create an app called users? or i should use the users default table by django? for each app i'll have a model, and for sure database-wise, for example a user will have many votes on many projects, therefore how can i connect these relationships across models in the right way? Thanks in advance -
Nginx and Django - JWT problems
I'm using Django Rest Framework to create an API. It works great when I run it locally, but when I deploy it to my server I'm having an issue with JWT. When I'm trying to POST new data, I receive an error that says: "detail": "Authentication credentials were not provided." Of course, I'm passing the Authorization header: authorization: JWT eyJ0eXAiOiJK..... On my server, I'm using nginx with the gunicorn. Here's my nginx config: upstream api { server unix:/home/bartalamej/api.sock fail_timeout=0; } server { listen 80; root /var/www/html; index index.html index.html; server_name api.mysite.cz; location /v1 { rewrite ^/v1/(.*)$ /$1 break; include proxy_params; proxy_set_header X-Forwarded-Proto $scheme; proxy_set_header REMOTE_USER $remote_user; proxy_set_header Authorization $http_authorization; proxy_set_header USE_X_FORWARDED_HOST True; proxy_pass http://api; } location /media { alias /home/bartalamej/api/media; } location /static { alias /home/bartalamej/api/static; } } Any help would be appreciated :) -
How to make REST api calls that needs auth_token?
I'm working on a Django-REST application that contains APIs that work with login mechanism. I'm able to create API endpoints for login and logouts. Login takes username, password and returns auth_token which is around 30 characters. Logout takes auth_token and destroys it. In between these login and logouts, there are few API calls that make use of auth_token. How is it generally implemented ? How are the requests made with auth_token in general? Where are those tokens stored? How do the backend validates it? Can someone please explain me how it is done basically? -
Test View in Django that requires Login session Sellenium
I would like to test a View in Django using Sellenium that has a decorator, that requires being logged in: @method_decorator(login_required, name='dispatch') This is how mu code looks like: class TestAddOrder(LiveServerTestCase): def setUp(self): self.selenium = webdriver.Firefox() super(TestAddOrder, self).setUp() def tearDown(self): self.selenium.quit() super(TestAddOrder, self).tearDown() def test_add_order(self): selenium = self.selenium selenium.get('http://127.0.0.1:8000/orders/create/') date = selenium.find_element_by_name('date').send_keys('01/31/2019') hours = selenium.find_element_by_id('id_hour').send_keys('18') submit = selenium.find_element_by_name('submit').send_keys(Keys.RETURN).send_keys(Keys.RETURN) And the error: selenium.common.exceptions.NoSuchElementException: Message: Unable to locate element: [name="date"] How can I keep the session of logged in user when trying to automise my test with Sellenium? -
How to retrieve and submit a form in Angular 6 that has been generated by a Django template
I have an Angular 6 app and am trying to display and submit a form that is generated from Django. I retrieve the form and display it using innerHtml. It shows up fine but when I click on the Submit button it doesn't call the function that I have attached to it. If I copy and paste the generated html then the submit button works fine (although I get a 403 response I think because of copying and pasting the CSRF token). Here is the code for my Angular component and template files and also the Django template: login.component.html <div *ngIf="!loggedIn; else successMessage" [innerHTML]="loginForm"></div> <ng-template #successMessage> Logged in </ng-template> login.component.ts import { Component, Input, OnInit } from '@angular/core'; import { HttpClient } from '@angular/common/http'; import { DomSanitizer, SafeHtml } from '@angular/platform-browser'; @Component({ selector: 'app-login', templateUrl: './login.component.html', styleUrls: ['./login.component.css'] }) export class LoginComponent implements OnInit { @Input() loggedIn: boolean; id_username: string; id_password: string; loginForm: SafeHtml; constructor(private router: Router, private httpClient: HttpClient, private sanitizer: DomSanitizer) { } ngOnInit() { this.getLoginForm(); } getLoginForm() { this.httpClient.get('https://myserver/account/login/', { responseType: 'text' }).subscribe(res => { this.loginForm = this.sanitizer.bypassSecurityTrustHtml(res); console.log(this.loginForm); }); } login() { console.log("Logging in user"); var response = this.httpClient.post('https://myserver.com/account/login/', { id_username: this.id_username, id_password: this.id_password }).subscribe(res => … -
social auth app django integrity error when user is logged out
Im trying to integrate facebook login to my app. When i associate a facebook account to the user and then logout,The login with facebook is working as intended.But if the user has his facebook disconnected and when i click login with facebook,Im getting an integrity error at : IntegrityError at /oauth/complete/facebook/ duplicate key value violates unique constraint "accounts_user_email_key" DETAIL: Key (email)=() already exists. Im using social-auth-app-django -
Feature Extraction using MFCC
I want to know, how to extract the audio (x.wav) signal, feature extraction using MFCC? I know the steps of the audio feature extraction using MFCC. I want to know the fine coding in Python using the Django framework -
How to add similar posts in Detailview in Django 1.11
I want to add similar posts section to my blog django applition in Class DetailView on detail page -
Django ModelMultipleChoiceField not saving
I got a ManyToMany field with the django-admin's ModelMultipleChoiceField working: When I add one element from the left side to the right side and click "Save" in the admin UI, then reload the Detail-Page where this ModelMultipleChoiceField is showing up, the saved elements can clearly be seen on the right side. The code for this working model looks like this: # project/account/models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager, PermissionsMixin from model_utils import Choices class User(AbstractBaseUser, PermissionsMixin): following = models.ManyToManyField('self', related_name='followers', blank=True, symmetrical=False) # project/account/forms.py from django import forms from django.contrib.auth import get_user_model from django.contrib.admin.widgets import FilteredSelectMultiple from .models import User class UserChangeForm(forms.ModelForm): following = forms.ModelMultipleChoiceField( queryset=User.objects.all(), required=False, widget=FilteredSelectMultiple( verbose_name='Following', is_stacked=False ) ) followers = forms.ModelMultipleChoiceField( queryset=User.objects.all(), required=False, widget=FilteredSelectMultiple( verbose_name='Followers', is_stacked=False ) ) class Meta: model = get_user_model() fields = ('following', 'followers') def __init__(self, *args, **kwargs): super(UserChangeForm, self).__init__(*args, **kwargs) if self.instance and self.instance.pk: self.fields['following'] = forms.ModelMultipleChoiceField( queryset=User.objects.all().exclude(pk=self.instance.pk), required=False, widget=FilteredSelectMultiple( verbose_name='Following', is_stacked=False ) ) self.fields['followers'] = forms.ModelMultipleChoiceField( queryset=User.objects.all().exclude(pk=self.instance.pk), required=False, widget=FilteredSelectMultiple( verbose_name='Followers', is_stacked=False ) ) self.fields['followers'].initial = self.instance.followers.all() # project/account/admin.py from django.contrib.auth import get_user_model from django.contrib import admin from django.contrib.auth.models import Group from django.contrib.auth.admin import UserAdmin as BaseUserAdmin from .models import User from .forms import UserChangeForm, UserCreationForm class Admin(BaseUserAdmin): form … -
Unable to handle webhooks for srs RTMP live streaming server with django
I returning 200 OK with HttpResponse fro django but the other side SRS is printing the following in the log http post on_connect uri failed. client_id=115, url=http://127.0.0.1:8000/livestream, request={"action":"on_connect","client_id":115,"ip":"127.0.0.1","vhost":"__defaultVhost__","app":"live","tcUrl":"rtmp://127.0.0.1:1935/live","pageUrl":""}, response=, code=2128, ret=1018(Bad file descriptor) as per SRS docs callbacks expect 200 ok with 0 to indicate success. Am I missing anything? -
Django Dumpdata file contains debug logs
I'm dumping some data from my django app with the command python manage.py dumpdata > db.json Unfortunately the db.json contains some startup logs in the first lines of the files. The file looks like: DEBUG $HOME=/home/web DEBUG matplotlib data path /usr/local/lib/python3.5/dist-packages/matplotlib/mpl-data DEBUG loaded rc file /usr/local/lib/python3.5/dist-packages/matplotlib/mpl-data/matplotlibrc DEBUG matplotlib version 2.2.2 DEBUG interactive is False DEBUG platform is linux [{ ... then the json file ... }] I guess it's coming from my logs configuration, but I couldn't figured it out. Here is my logs config in setting.py: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse', }, 'require_debug_true': { '()': 'django.utils.log.RequireDebugTrue', }, }, 'formatters': { 'verbose': { 'format': '%(asctime)s %(levelname)s [%(module)s:%(funcName)s:%(lineno)d] %(message)s', }, 'simple': { 'format': '%(levelname)s %(message)s', }, }, 'handlers': { 'console_simple': { 'class': 'logging.StreamHandler', 'filters': ['require_debug_true'], 'formatter': 'simple', 'level': 'DEBUG', }, 'console_verbose': { 'class': 'logging.StreamHandler', 'filters': ['require_debug_false'], 'formatter': 'verbose', 'level': 'INFO', }, }, 'loggers': { 'django.request': { 'handlers': ['console_simple', 'console_verbose'], 'level': 'ERROR', 'propagate': False, }, }, 'root': { 'handlers': ['console_simple', 'console_verbose'], 'level': 'DEBUG', }, } Any ideas? -
error Session in SSR React app with Django
I'm building an app with server-side rendered app and using Django as an API server. The Django server handles the session and to manage the session properly I should get the session ID and send it with each request but in serve-side rendering I need to make a request on the Node.js server and after the page renders I make it on the front-end, the problem is the when I fetch any data from the Django server it sends the correct sessionId from cookies but only from on the front-end side but on the Node server-side it doesn't send the cookies to the Django API server so every time I order some data I get it assoiciated a new session. Notes: I'm sending the credentials with the request. I'm using req.universalcookies on the node back-en from universal-cookie-express -
How to fix Django error name 'username' is not defined
I am a beginner so please keep that in mind when answering my question. I have set up my views.py to include a register user function. The username variable is throwing NameError at /register name 'username' is not defined when I try and register. I know that means that the username has not been defined, however I thought it was inheriting from the Django class models.User which I have imported? I have made a registration page before and have not had to define the User variables such as username, email, password, etc. for it to function. Many thanks. views.py def register_view(request): if request.method == 'POST': # Post request. form = UserRegisterForm(request.POST) if form.is_valid(): username == form.cleaned_data.get('username') messages.success(request, f'Account created for {username}!') return redirect('home') else: # Get request. form = UserRegisterForm() return render(request, 'users/register.html', {'form': form}) urls.py from django.contrib import admin from django.urls import path from django.conf.urls import include from . import views from users import views as register_view urlpatterns = [ path('register', views.register_view, name='register'), ] forms.py from django import forms from django.contrib.auth.models import User from django.contrib.auth.forms import UserCreationForm class UserRegisterForm(UserCreationForm): email = forms.EmailField() class Meta: model = User fields = [ 'username', 'first_name', 'last_name', 'email', 'password1', 'password2', ] -
django-tables2 permissions in TemplateColumn
I feel like I have read about this a hundred times but I still can't figure out how to use permissions within a django-tables2 TemplateColumn. My goal is to be able to render buttons in a column based on permissions that a user may have or may not have on a given model. That does not sound complicated to me and from what I have read I should be able to use something like {% if perms.myapp.delete_mymodel %} to achieve what I'd like to do. Here is the code I'm trying to get to work as I expect: import django_tables2 as tables MY_MODEL_ACTIONS = """ {% if perms.myapp.change_mymodel %} <a href="{% url 'myapp:my_model_edit' pk=record.pk %}" class="btn btn-sm btn-warning"><i class="fas fa-edit"></i></a> {% endif %} {% if perms.myapp.delete_mymodel %} <a href="{% url 'myapp:my_model_delete' pk=record.pk %}" class="btn btn-sm btn-danger"><i class="fas fa-trash"></i></a> {% endif %} """ class MyModelTable(tables.Table): # some columns actions = tables.TemplateColumn( verbose_name="", template_code=MY_MODEL_ACTIONS, ) class Meta(BaseTable.Meta): model = MyModel fields = ( # some columns "actions", ) When rendering the table no issues are triggered but the column just do not display any buttons (yes I do have the permissions for them to show up). Removing the {% if … %} … -
set and configure django project on cpanel
I have finished the development of my Django application and I'm ready to deploy it. I rented a host for deploying C Panel and installing Django on it. until this level everything is OK but I have a problem in uploading my configuration of my local project on my C Panel. but I don't know how should I do this and deploy it? i'm new in Django,please help me. thanks a lot. -
Django: Show different view based on User
I'd like to create a school management system for my personal project. Let's say there is an Admin for every School. But there is some Admin that can manage more than one schools, and they can switch between schools to manage each school. I've thought one way to do it, by using different URL path eg. urlpatterns = [ url(schools/<int:pk>/, SchoolView.as_view()), ] Is there a way so I do not separate by using different URL path for each schools? So, for each admin, they have similar URL path, but the view render different school based on Admin user. But I don't really know how to do that? Can I get an advice how to do it. Many thanks! -
Using Django Models in standalone script - database not updating
I am trying to update records in my SQLite3 db using the Django ORM and the update() function. I can see that after running the update() function in my standalone script, the database has in-fact been updated, but the changes are not reflected on my website until I run on my server: sudo systemctl restart gunicorn I suspect the issue has to do with the way I import my models into my standalone script. ROOT_DIR = /path/to/root/dir sys.path.insert(0, ROOT_DIR) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'AppName .settings') import django django.setup() from main.models import Bet, Investment, Profile from django.contrib.auth.models import User Bet.objects.filter(id=4).update(revenue=10) I would expect to see the updates reflected on my site without having to restart gunicorn. More context: I am running a create() function in the same standalone script which is updating the database and being reflected on my site as expected without having to restart gunicorn. -
working with real dabatbase in testing _ django Restframework
I need an actual connection to my database for testing not testing environment. I have to request: 1. fetching data from a web service and stores to the database with post request. 2. getting those result stored in the database. so with RequestsClient() and CoreAPIClient() I figure out these are for working with Live and production environments but when I try to request to my endpoints. comes with 500 internal error. I found a parameter allow_database_queries when you want to request. I thought that should establish the connections to mySQL but there are no documentations about it. self.client = RequestsClient() # or CoreAPIClient() self.client.headers.update(allow_database_queries='yes', Authorization="bmhh "+ self.token) self.client.post('http://127.0.0.1:8000/stations/') -
Django: How to use modal as a form to update an object
I'm trying to use modal as a edit form but I don't know good way. Currently my views.py is like this. def edit_entry(request, entry_pk): entry = get_object_or_404(Entry, pk=entry_pk) if request.method != 'POST': form = EntryForm(instance=entry, user=request.user) else: form = EntryForm(instance=entry, data=request.POST, user=request.user) if form.is_valid(): form.save() and I have a template for this view. What I want to do is from the page that lists a bunch of entry objects, the edit form for the object is shown when I click edit button. {% for entry in entries %} ... <button class="btn btn-outline-primary" data-toggle="modal" data-target="#editEntryModal">Edit</button> <!-- modal for the object --> Anyone who could give me tips?