Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Unable to setup in VPS for production
1) I'm unable to get the default django page at ip_address:8000 I've set up a VPS with nginx and gunicorn. I see the default nginx page on visiting ip_address but when I run gunicorn at 0.0.0.0:8000 I get timed out. I understand that I need to include in nginx.conf and allow the port from VPS firewall, but I do not have a step by step guide for all the setup from testing in host to finally changing all settings for ready to use production environment. Could anyone please share a guide/steps? 2)I'm unable to setup gunicorn for daemon. I followed a digital ocean tutorial but even if I'm using root user and changed permissions of all necessary directories to 0777, it is throwing permission denied error. Could anyone please help out here? -
Problem with uploading files to HDFS using Django
I build web application with Angular 6 frontend, Django 1.11 backend and Hadoop 3.1. It seems to me that the problem is associated with uploading large files. My method in Django looks line shown below. Everything seems to be working fine with small files in different formats. However very often when I try to upload larger files I get the error shown at the bottom. Does anyone have an idea what can be wrong and how can I fix it? If not can you recommend the fastest way of sending files of all formats and sizes? def post(self, request): key = request.META.get('HTTP_AUTHORIZATION').split()[1] user_id = Token.objects.get(key=key).user_id user_name = User.objects.get(id=user_id).username upload_file(request.FILES['file'], user_name) return Response(status=status.HTTP_201_CREATED) def upload_file(file, user_name): response = requests.put(url + ':9870/webhdfs/v1/user/' + str(user_name) + '/' + str(file) + '?op=CREATE&user.name=myuser&createflag=&createparent=true&overwrite=false' , data=file, headers={'content-type':'application/octet-stream'}) return response ERROR: django_1 | Internal Server Error: /cloud/ django_1 | Traceback (most recent call last): django_1 | File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 600, in urlopen django_1 | chunked=chunked) django_1 | File "/usr/local/lib/python3.6/site-packages/urllib3/connectionpool.py", line 354, in _make_request django_1 | conn.request(method, url, **httplib_request_kw) django_1 | File "/usr/local/lib/python3.6/http/client.py", line 1239, in request django_1 | self._send_request(method, url, body, headers, encode_chunked) django_1 | File "/usr/local/lib/python3.6/http/client.py", line 1285, in _send_request django_1 | self.endheaders(body, encode_chunked=encode_chunked) django_1 | … -
How to change admin menu order for installed third party apps in Django
I am customizing the order of the Admin items in Django using Mezzanine. I am a novice to Django, but I've been following the docs here. I am able to order custom apps/models fine in settings.py like so: ADMIN_MENU_ORDER = ( ('Person', ('person.Job', 'person.address')), ('Place', ('place.Purpose')) ) The problem is including external apps. As one example, I am using django-robots==3.0. I've noticed when I hover over the menu links in /admin that the URLs follow a pattern to the model definitions: '{app-label}.{model-name}' -> (all lower) applabel/modelname. For example, 'person.Job' maps to /admin/person/job. The automatically included links for the robots app in admin are /admin/robots/url/ and /admin/robots/rule/. I tried adding the following, but it doesn't work: ADMIN_MENU_ORDER = ( ('Person', ('person.Job', 'person.address')), ('Robots', ('robots.Url', 'robots.Rule')), ('Place', ('place.Purpose')) ) How can I look up the namespace label and model name? In the docs it gives an example for django-filebrowser as Media Library: ...("Content", ("pages.Page", "blog.BlogPost", "blog.Comment", ("Media Library", "fb_browse"),))... How can I look up the named urlpattern, in this case fb_browse for all other external apps? -
Using request.session to populate a django form
I want to save a form in session so that a user doesn't have to reapply filters when going to a different url. Here is the error I'm getting: 'unicode' object has no attribute 'get' This is the code I have: views.py def someview(request): if request.method == 'POST': form = Form(request.POST, initial=request.session.get('save_form', None)) if form.is_valid(): clean_form = json.dumps(form.cleaned_data, indent=4, sort_keys=True, default=str) request.session['save_form'] = clean_form else: pass else: form = Form() forms.py class Form(forms.Form): startdate = forms.DateField( label='Start date', initial= '2018-01-01', widget=forms.TextInput(attrs={'class':'datepicker'}) ) enddate = forms.DateField( label='End date', initial= datetime.date.today() - datetime.timedelta(days=1), widget=forms.TextInput(attrs={'class':'datepicker'}) ) manager = forms.MultipleChoiceField( required=False, choices=managers, widget=forms.SelectMultiple(), ) Being a beginner in Django, I'm not sure where to go from here. I'm pretty sure the error is in the initial argument. But, printing it, it seems print what I would expect. TIA -
Handling images using django forms
I'm trying to upload image using django forms, and then assign it to my model object image field. forms.py class MemberRegistrationForm(forms.ModelForm): birthday=forms.DateField(input_formats=settings.DATE_INPUT_FORMATS) class Meta: model=Member fields=('birthday','photo',) models.py class Member(models.Model): user=models.OneToOneField(settings.AUTH_USER_MODEL,on_delete=models.CASCADE) birthday=models.DateField(blank=True,null=True) photo=models.ImageField(upload_to='account/%Y/%m/%d',blank=True) def __str__(self): return "{} /'s profile ".format(self.user.username) settings.py if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) Parsing form page <form class="" action="." method="post"> {{form.as_p}} {{form_member.as_p}} {% csrf_token %} <input type="submit" name="" value="Create my account"> </form> Display page <img width="90px;" height="180px;"src="{{member.photo.url}}" alt=""> views.py I guess problem is here.I can not extract the uploaded image from form and assign it to my model object field def user_signup(request): if request.method == 'POST': form = UserRegistrationForm(request.POST) form_member=MemberRegistrationForm(request.POST,request.FILES) if form.is_valid() and form_member.is_valid(): user=form.save(commit=False) user.set_password( form.cleaned_data['password'] ) user.save() member=Member.objects.create(user=user, photo=request.FILES['photo'], #HERE I'M NOT SURE IF THIS THE RIGHT WAY OR NOT birthday=form_member.cleaned_data['birthday']) return render(request, 'account/registeration_done.html', {'user':user, 'member':member, 'form':form, 'form_member':form_member, }) -
Django: get_queryset method for a Search View to filter with multiple fields
I am working on an HTML form to filter multiple model fields. Question: How to build the view so a single queryset is returned even with changing queries? HTML My form will pass the inputs as kwargs so request will be like this - /search/?order_by=newest /search/?q=<string>&order_by=newest /search/?q=<string>&order_by=newest&country=US These would filter upon: The string in query (q=...) The order_by to order the queryset The country to filter the results by a location field View: I'm trying to have a single query in the view to remove complexity and keep the view as simple as possible. How can I take all of these potential variations and pass through a single get_queryset method? Here is what I have right now. def get_queryset(self): keywords = self.request.GET.get('q') or None order_by = self.order_by_options.get( self.request.GET.get('order_by')) or '-date_of_price' if keywords: query = SearchQuery(keywords) vectors = SearchVector('name', weight='A') qs = self.model.objects_for_search.annotate(search=vectors).filter( search=query).order_by('sold', order_by, '-modified') else: qs = self.model.objects_for_search.order_by('sold', order_by, '-modified') return qs[0:500] The issue with the code above is that the more attributes I add, the more if statements. This code has the if statement for keywords, and that doesn't feel elegant/pythonic to me. Adding another if statement for the country query would definitely be odd. -
Django Admin Remove default save message
I have added this extra message in my model admin and basically i want to remove the default one. Is there someone that can help me to do this? my actual message: def save_model(self, request, obj, form, change): # add an additional message user = request.user messages.info(request, "Dear " + str(user)+ " "+ " please note that your parking plot has been reserved") super(ParcareModelAdmin, self).save_model(request, obj, form, change) The default one kinda sucks! Thank you! -
Could not run Ec2-server on port 80
I could run the server on port 8000 but when i try to use 80 with python manage.py runserver myip:80 i get: You don't have permission to access that port. If i use sudo python manage.py runserver myip:80 i get: File "manage.py", line 14 ) from exc ^ SyntaxError: invalid syntax Using yum python manage.py runserver myip:80 i get Loaded plugins: priorities, update-motd, upgrade-helper No such command: python. Please use /usr/bin/yum --help If i write python in the console i get version 3.5.5 and my env is activated. EDIT: Using sudo python3 manage.py runserver myip:80 i get: Traceback (most recent call last): File "manage.py", line 8, in <module> from django.core.management import execute_from_command_line ImportError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 14, in <module> ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? -
slow order by "field" and limit
I have simple query that must get 1 record from table with about 14m records: EXPLAIN ANALYZE SELECT "projects_toolresult"."id", "projects_toolresult"."tool_id", "projects_toolresult"."status", "projects_toolresult"."updated_at", "projects_toolresult"."created_at" FROM "projects_toolresult" WHERE ("projects_toolresult"."status" = 1 AND "projects_toolresult"."tool_id" = 21) ORDER BY "projects_toolresult"."updated_at" DESC LIMIT 1; And it is weird that when I order query by updated_at field my query executes 60 sec. Limit (cost=0.43..510.94 rows=1 width=151) (actual time=56754.932..56754.932 rows=0 loops=1) -> Index Scan using projects_to_updated_266459_idx on projects_toolresult (cost=0.43..1800549.09 rows=3527 width=151) (actual time=56754.930..56754.930 rows=0 loops=1) Filter: ((status = 1) AND (tool_id = 21)) Rows Removed by Filter: 13709343 Planning time: 0.236 ms Execution time: 56754.968 ms (6 rows) No matter if it will be ASC or DESC But if I do ORDER BY RAND() or without order: Limit (cost=23496.10..23496.10 rows=1 width=151) (actual time=447.532..447.532 rows=0 loops=1) -> Sort (cost=23496.10..23505.20 rows=3642 width=151) (actual time=447.530..447.530 rows=0 loops=1) Sort Key: (random()) Sort Method: quicksort Memory: 25kB -> Index Scan using projects_toolresult_tool_id_34a3bb16 on projects_toolresult (cost=0.56..23477.89 rows=3642 width=151) (actual time=447.513..447.513 rows=0 loops=1) Index Cond: (tool_id = 21) Filter: (status = 1) Rows Removed by Filter: 6097 Planning time: 0.224 ms Execution time: 447.571 ms (10 rows) It working fast. I have index on updated_at and status fields(I also tried without too). I did … -
Django 2.1 PasswordResetView 404
I'm trying to integrate the User password reset functionality into my custom user model. When I try to access the URL I get a 404-error. The URL I try to access: http://localhost:8000/reset/MQ/4zw-f78ac4c97d45f366a243/ My urls.py: from django.urls import path from django.urls import reverse_lazy from django.contrib.auth.views import PasswordResetView from . import views app_name = 'accounts' urlpatterns = [ path('signup/', views.SignUpView.as_view(), name='signup'), path('login/', views.LoginView.as_view(), name='login'), path('logout/', views.LogOutView.as_view(), name='logout'), path('password-change/', views.PasswordChangeView.as_view(), name='password-change'), path('password-reset/', views.PasswordResetView.as_view(), name='password-reset'), path('password-reset-done/', views.PasswordResetDoneView.as_view(), name='password-reset-done'), path('reset/<uuid:uidb64>/<slug:token>/', views.PasswordResetConfirmView.as_view(), name='password_reset_confirm'), ] My views.py: from django.shortcuts import render from braces import views as bracesviews from django.views import generic from .forms import RegisterForm, LoginForm, PasswordResetForm, SetPasswordForm, PasswordChangeForm from django.contrib.auth import get_user_model from django.contrib.auth import views as auth_views from django.contrib.auth import authenticate, login, logout from django.utils.translation import ugettext, ugettext_lazy as _ from django.urls import reverse_lazy from django.contrib import auth # Create your views here. User = get_user_model() (...) class PasswordChangeView(auth_views.PasswordChangeView): form_class = PasswordChangeForm template_name = 'accounts/password-change.html' success_url = reverse_lazy('home') form_valid_message = _("Your password was changed!") def form_valid(self, form): form.save() return super().form_valid(form) class PasswordResetView(auth_views.PasswordResetView): form_class = PasswordResetForm template_name = 'accounts/password-reset.html' success_url = reverse_lazy('accounts:password-reset-done') subject_template_name = 'accounts/emails/password-reset-subject.txt' email_template_name = 'accounts/emails/password-reset-email.html' class PasswordResetDoneView(auth_views.PasswordResetDoneView): template_name = 'accounts/password-reset-done.html' class PasswordResetConfirmView(auth_views.PasswordResetConfirmView): template_name = 'accounts/password-reset-confirm.html' form_class = SetPasswordForm success_url = reverse_lazy('home') form_valid_message = … -
Adding tooltip data-toggle to a form in django
I'm trying to add a tooltip data-toggle to a form done with Django, and for each field I'd like to add some information about it with the tooltip data-toggle, but I don't know how to do this. Could anybody help me? -
Django - check if instance exists results in internal server error 500
I am trying to check if I have an entry in my data base using this code: def device_update(request): json_data = json.loads(request.body) email = json_data['email'] imei = json_data['imei'] sdk_version = json_data['sdk_version'] date = json_data['updateDate'] rule = json_data['ruleName'] group_name = json_data['group'] if Group.objects.filter(group=group_name).exists(): print("group does exists") else: print("group doesn't exists") return HttpResponse("Successful") However, when the code reaches the if statement to check if the group exists, it returns error 500. I tried to check with two groups one that exists and another one that doesn't, in both cases I got error 500. How can I fix this and why is this happening? Thanks in advance -
How do people make live server stream data on their websites like share market kind of things? How do I start?
Share market prices update so fast . I use data scrapping and put in ms excel self updating format . Now what should I do? How do I proceed next? -
LogoutView() received an invalid keyword 'name'. as_view only accepts arguments that are already attributes of the class?
Hi I am trying to name my url and I get the following error: LogoutView() received an invalid keyword 'name'. as_view only accepts arguments that are already attributes of the class. urlpatterns: url(r'^logout/$', auth_views.LogoutView.as_view(template_name='accounts/logout.html', name='logout')), working on a project and stuck atm. TIA -
Django 2.0.5 display different queryset result with the CBV listview
Hi: I am trying to build a staff directory where user can filter view by department. I have the department list displayed in a dropdown button but cannot figure out how to properly pass the user selection to the listview in the views.py Please see the code below. models.py class Department(models.Model): department = models.CharField(max_length = 20, unique = True) def __str__(self): return self.department class EmployeeList(models.Model): department = models.ForeignKey(Department, on_delete = models.SET_NULL, null = True, blank = True) views.py class EmployeeOutput(ListView): model = models.EmployeeList context_object_name = 'employee_list' template_name = 'employee_list.html' def get_context_data(self, **kwargs): context = super(EmployeeOutput, self).get_context_data(**kwargs) context['filter_list'] = models.Department.objects.values_list('department', flat = True) return context class FilterDepartment(ListView): model = models.EmployeeList context_object_name = 'employee_list' template_name = 'employee_list.html' def get_context_data(self, **kwargs): context = super(FilterDepartment, self).get_context_data(**kwargs) context['filter_list'] = models.Department.objects.values_list('department', flat = True) context['department_filter'] = models.EmployeeList.objects.filter(department_id = 3) return context employee_list.html <table class = 'table table-striped table-hover' id = 'my_table'> <thead> <tr> <th><button type="button" class = ' btn btn-info' onclick = 'sortTable(0)'>Name</button></th> <th><button type="button" class = ' btn btn-info' onclick = 'sortTableNumbers(1)'>Phone Ex</button></th> <th><button type="button" class = ' btn btn-info' onclick = 'sortTable(2)'>Email</button></th> <th> <div class="btn-group dropright"> <button class="btn btn-success dropdown-toggle" type="button" id="dropdownMenuButton" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> Department </button> <div class="dropdown-menu" aria-labelledby="dropdownMenuButton"> <a class="dropdown-item" onclick = … -
I want to create django popup form in my project
I have created fee management system in django. The problem is I am using simple form and for each form user have to navigate to separate page. I want to create popup form in django. I have search many websites but can't get solution enter image description here In above window when user click on payment button pop-up form will be open. and when user click on submit button changes will be shown in same page. Can anyone tell me how to solve this? or share code if you have work in same area. -
Where to put 'create_function' statements in Django
I'm working on a project with standard Django+SQLite bundle. And I've come to situation where Django querySet API and even django 'raw()' are not enough for me to retrieve appropriate information from the database. So I execute custom SQL directly to retrieve data. Also I need to define 'lower' function through 'create_function' interface cause SQLite can't perform case-insensitive sorting on unicode field (https://www.sqlite.org/faq.html#q18). My question is where should I put this 'create_function' statement? Is it normal to put it directly into a django view, so it would be executed every time the view is loaded, or I should put it somewere else, where it would be executed only once? from django.db import connection def lower(text): if text: return text.lower() else: return text def my_view(request): ... with connection.cursor() as cursor: if (connection.vendor == 'sqlite'): connection.connection.create_function('lower', 1, lower) cursor.execute('SELECT * FROM <my complicated select using lower>;') data = dictfetchall(cursor) ... -
How to access all fields in child class from base class in django?
Here is my models.py class Parent(models.Model): start_date = models.CharField(max_length=60) last_date = models.CharField(max_length=60) post_name = models.CharField(max_length=255) education = models.CharField(max_length=255) more_info = models.TextField() type = models.IntegerField() abstract = True def __str__(self): return "Upsc Jobs" class Child(Parent): def __str__(self): return "Ssc Jobs" Here how can i access all the fields from parent class in child class while migration . When i am doing this way with mysql databse. it is creating only one field for Child and that is " Parent_ptr_id " Thanks.. -
MSSQL django_pyodbc connectivity issues
I am trying to connect to MSSQL with help of django-pyodbc. I have installed all the required packages like FreeTDS, unixODBC and django-pyodbc. When I try to connect from backend using tsql and isql I am able to connect as below:- >tsql -S mssql -U ********* -P *********** locale is "en_US.UTF-8" locale charset is "UTF-8" using default charset "UTF-8" 1> isql -v mssql ********* *********** +---------------------------------------+ | Connected! | | | | sql-statement | | help [tablename] | | quit | | | +---------------------------------------+ SQL> But, when I am trying to connect from python it does not work. I am getting below error:- File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/site-packages/django/core/management/__init__.py", line 330, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 390, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/site-packages/django/core/management/base.py", line 441, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/site-packages/django/core/management/commands/migrate.py", line 93, in handle executor = MigrationExecutor(connection, self.migration_progress_callback) File "/usr/local/lib/python2.7/site-packages/django/db/migrations/executor.py", line 19, in __init__ self.loader = MigrationLoader(self.connection) File "/usr/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 47, in __init__ self.build_graph() File "/usr/local/lib/python2.7/site-packages/django/db/migrations/loader.py", line 180, in build_graph self.applied_migrations = recorder.applied_migrations() File "/usr/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 59, in applied_migrations self.ensure_schema() File "/usr/local/lib/python2.7/site-packages/django/db/migrations/recorder.py", line 49, in ensure_schema if self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()): File "/usr/local/lib/python2.7/site-packages/django/db/backends/base/base.py", line 162, in cursor cursor = self.make_debug_cursor(self._cursor()) File "/usr/local/lib/python2.7/site-packages/django_pyodbc/base.py", line 348, … -
Django: Restrict frontend delveoper access to backend code
We run a "classic" django website (rendering templates in the backend) and host the complete source code on github. We also use the "classic" folder structure: /source/ # For python related django code and packages /templates/ # Just the normal django templates /static/img/ # static images /static/sass/ # Sass files /static/css/ # Generated css files from sass (django-pipeline) For the development purpose we use vagrant and ssh into the machine to start the django development server. Changes are pushed to github. This is our current state and it works good for developer which are involved in the project. But we also have for example external designers which should not have access to the backend. Problem: Designer should only have access to the /static/ folder (locally and on git) So how can they run the Project without having access to the backend files? (Policy, installing and explaining vagrant is time consuming for non developers ...) I couldn't find a solution but I have the following idea: Create for the static folder a new repository Create a server with everything what is needed to run the server Mount the local /static/ folder from the developer on the server. So that the local … -
Django importing text file Data Into sqllit3
I have tabulated text files of my data and records are too much in number i cant upload it one by one in database is there any way to import that data into the table i created in model -
Update Server Group Unit Test Cases Python
def updateServerGroup(request): param = request.POST.get('id') record = ServerGroups.objects.get(id=param) form = ServerGroupUpdateForm(request.POST, instance=record) tempForm = form.save(commit=False) serverList = request.POST.getlist('serverList[]') tempForm.save() for server in serverList: if Servers.objects.filter(serverName=server): print(server) else: s = Servers(serverName=server) s.save(); s.serverGroup.add(tempForm) for server in Servers.objects.filter(serverGroup__id=param): if server.serverName not in serverList: Servers.objects.filter(serverGroup__id=param).filter(serverName=server.serverName).delete() html = "form saved successfully." return HttpResponse(record.updateDate) This is updateServerGroup function, for which I want to write unit test cases. Need more clarity on how to write and have a logic on writing the unit test cases -
How can I add a fields to a pandas dataframe by clicking an href link with Django
I have a database of assets with an asset number, model number, serial number, etc. On my website, I would like to click the 'Deploy' button next to an asset number and have it add that asset number (with all of the other fields associated) to a pandas dataframe. I'm new to Django, pandas and python so I am a little stuck on how to proceed. I have a basic skeleton made up using various tutorials. views.py from django.shortcuts import render #generates HTML fiels using a template and data #from django.http import HttpResponse from .models import Book, Author, BookInstance, Genre, Model, ModelInstance, Category, Ownership, Manufacturer, Location #imports model classes to access data in views from django.views import generic class ModelListView(generic.ListView): model = Model class ModelDetailView(generic.DetailView): model = Model class CategoryListView(generic.ListView): model = Category urls.py from django.urls import path from . import views urlpatterns = [ path('', views.index, name='index'), path('models/', views.ModelListView.as_view(), name='models'), path('model/<int:pk>', views.ModelDetailView.as_view(), name='model-detail'), path('category/', views.CategoryListView.as_view(), name='categories'), ] models.py from django.db import models from django.urls import reverse #Used to generate URLs by reversing the URL patterns from django.contrib.auth.models import User import uuid from datetime import date class Category(models.Model): category = models.CharField('Equipment Type', max_length = 50, help_text = "Enter general category … -
"'ReverseManyToOneDescriptor' object has no attribute 'all'"
I found the answer myself, but thought that the question might benefit others: i got the following error whenever i called: Schema.objects.all() or Schema.objects.filter(url=some_url) or similar.. Error: "'ReverseManyToOneDescriptor' object has no attribute 'all'" class Schema(models.Model): label = models.TextField() description = models.TextField() url = models.URLField(unique=True) def __str__(self): return self.label class Meta: app_label = 'metadata' class Object(models.Model): label = models.TextField() description = models.TextField() # related name should not be objects, because that will cause problems schema = models.ForeignKey( Schema, related_name='objects', on_delete=models.CASCADE) def __str__(self): return "%s.%s" % (self.schema.label, self.label) class Meta: app_label = 'metadata' -
ASGI options for django 1.9 and python 2.7
I am currently running django-channels on Daphne and looking for other options. Any and every suggestions are highly appreciated