Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
I wanna connected 2 drill down button in large content&small content
I wanna connected 2 drill down button in large content&small content.But now 2 button is independency. My ideal output is like Left button is large content and right one is small content.If I select A in left button and a-1 & a-2 & a-3 is shown in small content.If I select B in left button and b-1 & b-2 is shown in small content.Now I wrote in views.py like from collections import OrderedDict from django.shortcuts import render import json from django.http import JsonResponse def index(request): with open('./data/data.json', 'r') as f: json_data = json.loads(f.read(), object_pairs_hook=OrderedDict) preprocessed = [] counter = 0 for key in ["type1", "type2", "type3", "type4"]: values = [(i + counter, value) for i, value in enumerate(json_data[key].values())] preprocessed.append((key, values)) counter = len(json_data[key]) return render(request, 'index.html', {'json_data': json_data,'preprocessed': preprocessed}) I wrote like index.html like <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option>{{ i }}</option> {% endfor %} </select> {% for key, values in preprocessed %} <select name="type" id=key> {% for counter, value in values %} <option value="{{ counter }}">{{ value }}</option> {% endfor %} </select> {% endfor %} Now 3 button is shown in browser, large content button & A's small content button & B's small … -
prevent SQL injection in django forms
I use this for validation: class MyValidationForm(forms.Form): title = forms.CharField() body = forms.Textarea() taxonomy = forms.IntegerField() and this is my class-based view: class blog_createpost(dashboardBaseViews): template_name = "dashboardtems/blog_createpost.html" model = {} def post(self, request, *args, **kwargs): form = MyValidationForm(request.POST) if not form.is_valid(): return HttpResponse("not valid") new_data = post(title=request.POST['title'], body=request.POST['body'], description=request.POST['description'], taxonomy=get_object_or_404(taxonomy, pk=request.POST['taxonomy']), writer=request.user) new_data.save() return HttpResponse("done") like you see i check my received request validation in this line: if not form.is_valid(): and its working on but when i add some SQL-command inside my form inputs. it does not preventing to insert the value inside database!.. means i have a field in database which contains some value like select * from user where 1=1!. doesn't it cause sql-injection danger from user inputs?... -
How can we view database in django of stored username and password of an default login page
How can we view database in django of stored username and password of an default login page. -
django form request.POST.get('field-name', '') always empty
Trying to get some values from a form but the parameters are always empty. here is the path from my urls.py: url((r'^partners-email$'), views.partners_email, name="Partners Email"), This is a simple form I have in the template: <form method="POST" action="/partners-email"> <input name="email" class="form-control" id="client-email"> <input type="submit" value="Submit" /> </form> and here is my function in views.py: def partners_email(request): from_email = request.POST.get('email', '') print('MY_TAG: ' + from_email) output is always: "MYTAG: " any ideas? Thank you very much in advance -
Django import-export.admin customize:for xlsx sheets, and change the diff strategy
I have a knotty problem. I used django-import-export to import xlsx data. I have integrated it to Django admin by ImportExportModelAdmin. below is admin.py: @admin.register(assets) class data_import(ImportExportModelAdmin): pass But when I import data several times, I found it just save the newest data(the last) to model, I want save all data every time I import, and just use some columns to decide if the data is duplicated.How can I solve this? -
I did not show big drill down button
I did not show large content drill down button. I load json file and the content of the file become drill down button's content.But now only small content drill down buttons are shown.json is like {'items': {'---': '---', ‘A’: ‘a’, ‘B’: ‘b’, ‘C: ‘c’, ‘D’: ‘d’}, 'type1': { "---":"---", "a1":"a1", "a2:"a2", "a3":"a3", "a4":"a4" }, 'type2': { "---":"---", "b1":"b1", "b2:"b2", "b3":"b3", "b4":"b4" }, 'type3': { "---":"---", "c1":"c1", "c2:"c2", }, 'type4': { "---":"---", "d1":"d1", "d2:"d2", "d3":"d3" }, } views.py is from collections import OrderedDict from django.shortcuts import render import json from django.http import JsonResponse def index(request): with open('./data/company_demand.json', 'r') as f: json_data = json.loads(f.read(), object_pairs_hook=OrderedDict) preprocessed = [] counter = 0 for key in ["type1", "type2", "type3", "type4"]: values = [(i + counter, value) for i, value in enumerate(json_data[key].values())] preprocessed.append((key, values)) counter = len(json_data[key]) return render(request, 'index.html', {'json_data': json_data}, {'preprocessed': preprocessed}) index.html is <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option>{{ i }}</option> {% endfor %} </select> {% for key, values in preprocessed %} <select name="type" id="{{ key }}"> {% for counter, value in values %} <option value="{{ counter }}">{{ value }}-{{counter}}</option> {% endfor %} </select> {% endfor %} But now this part <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> … -
ID and Class Name Delimiters in HTML
Django==1.11.5 Googl tells us not to use underscores: https://google.github.io/styleguide/htmlcssguide.html#ID_and_Class_Name_Delimiters Well, it is ok. But let's have a look at how to behave in the reality of Django. Let's open django/contrib/admin/templates/admin/index.html. We can see: <div id="content-main"> As if a hyphen is Ok for Django. But on the other hand if one organizes a Django form then opens its HTML, they will see something like this: id="id_keeper_not_absent" Well, this id was automatically created by this code: forms.py keeper_not_absent = forms.BooleanField(label='Keeper absent', required=False) Well, now we have underscores in HTML element ids. It is also Ok. But mixing doesn't seem Ok. Could you help me understand why Django itself uses such a mix and what should we ourselves use? -
How to set a path to virtual environment for sublime text 3 plugin to work correctly
I am trying to install a plugin called "Django manage commands" in sublime text 3. and after installation, I got the following message Remember to set the path to the directory where your virtual environments are installed in "python_virtualenv_paths" for the plugin to work correctly, as many directories as you need can be added. How can I do this? I found the same message in other plugins as well. Thanks for your time in advance '_' -
How to you join two models with a specific requirement
I have two models Model A class Affiliate(models.Model): instructor = models.OneToOneField(Profile) Model B class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) instructor = models.BooleanField(default=False, blank=False) My goal is in my django admin to show a list of Profiles where instructor = True, right now I am getting all of the instructors, how can I limit this list. class AffiliateAdmin(admin.ModelAdmin): fields = ['instructor'] This works but it gets the whole list of profiles. I only want the profiles that have instructor = True. I have tried limiting the profile on the affiliate model with no success. Any help is appreciated. -
Django issue with argon2 hasher in live production
So I have just setup my Digital Ocean droplet (server) and have been working to get this site to work, however I have been coming across error after error. I finally got the site to load the login page (which is what should happen), but when I login I get an error that Argon2 Pass Hasher couldn't load. I really have no idea what the problem is, as everything was working perfectly while in development. Here is the error: ValueError at /accounts/login/ Couldn't load 'Argon2PasswordHasher' algorithm library: No module named argon2 Here are my settings: """ Django settings for django_project project. Generated by 'django-admin startproject' using Django 1.8.7. For more information on this file, see https://docs.djangoproject.com/en/1.8/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.8/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) TEMPLATE_DIR = os.path.join(BASE_DIR, 'templates') MEDIA_DIR = os.path.join(BASE_DIR, 'media') # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.8/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'h&*(yq942_a^pa+ty&wh(bl9s4d#z^*_6cmeb#5&49jb^r$&!f' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', … -
Database Queries: Fast alternatives to Django's order_by()
I've been teaching myself Django and SQL, and one thing I've noticed is that when working with large tables (> 1,000,000 records), specifying an ordering is painfully slow. For example: Model.objects()[offset:limit] might take a few milliseconds, assuming offset and limit are a small enough range. However: Model.objects()[offset:limit].order_by('name') Could take 10 or 20 seconds, depending on the number of rows in the table. I understand why this is happening; all rows must be checked to ensure that the correct results are returned. I also understand that this is more an SQL problem and not a Django problem, it's just easier for me to explain it with Django code. So these are my questions: Since I see Django production websites display ordered data from extremely large tables, how do they achieve this without each query taking >10 seconds? After I solve the first question, how could I extend my Django application to allow ordering of multiple columns (name, date, value, etc)? My intuition says that the answer to the first question is to insert each record in the order I want it displayed so that no ordering is necessary when performing queries, but that seems difficult to maintain. Also, that means that … -
I wanna add number which is correspond to the number of this list's content
Now index.html is <html> <head> <script type="text/javascript" src="//code.jquery.com/jquery-1.11.0.min.js"></script> <script type="text/javascript" src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.8.2/chosen.jquery.min.js"></script> <script src="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.jquery.js"></script> <link rel="stylesheet" href="//cdnjs.cloudflare.com/ajax/libs/chosen/1.4.2/chosen.css"> </head> <body> <select id="mainDD" data-placeholder="Choose" class="chzn-select" style="width:600px;"> {% for i in json_data.items.values %} <option>{{ i }}</option> {% endfor %} </select> <select name="type" id="type1"> {% for j in json_data.type1.values %} <option>{{ j }}</option> {% endfor %} </select> <select name="type" id="type2"> {% for k in json_data.type2.values %} <option>{{ k }}</option> {% endfor %} </select> <select name="type" id="type3"> {% for l in json_data.type3.values %} <option>{{ l }}</option> {% endfor %} </select> <select name="type" id="type4"> {% for m in json_data.type4.values %} <option>{{ m }}</option> {% endfor %} </select> <script type="text/javascript"> $(document).ready(function () { $('#mainDD').on('change', function() { console.log($(this).val()); console.log($('#mainDD :selected').text()) ; var thisType = "type" + $(this).val(); for(i=1; i<5; i++) { var thisId = "type" + i; console.log(thisType + " " + thisId); if(thisType !== thisId) { $("#"+thisId).hide(); } else { $("#"+thisId).show(); } } }).trigger('change'); }); </script> </body> </html> I wanna add number to tag like .So my ideal output is <select name="type" id="type1"> <option value="1">a-1</option> <option value="2">a-2</option> <option value="3">a-3</option> <option value="4">a-4</option> </select> <select name="type" id="type2"> <option value="5">b-1</option> <option value="6">b-2</option> <option value="7">b-3</option> <option value="8">b-4</option> <option value="9">b-5</option> </select> <select name="type" id="type3"> <option value="10">c-1</option> <option value="11">c-2</option> </select> <select name="type" id="type4"> <option … -
Duplicate key issue when loading back.json file PostgreSQL
I have a PostgreSQL database that where I performed python manage.py dumpdata to backup the data into a json file. I created a new PostgreSQL database, performed a migrate, and everything worked like clockwork. When I tried to load the backup.json file with python manage.py loaddata backup.json it, gives me this error. Could not load contenttypes.ContentType(pk=15): duplicate key value violates unique constraint "django_content_type_app_label_76bd3d3b_uniq" DETAIL: Key (app_label, model)=(navigation, navigation) already exists. I checked phpPgAdmin, and there is a row for News. Is there a way to load the backup json file without including the content types, or better yet dump everything except for content types data ? -
Convert serialized object to json in Django
I'm coding unit tests for a serializer. I have got a serializer object from the serializer that I'm testing (This is actual serialized content). I have serialized the sample data using from django.core import serializers and got the json (This is the expected content which is in json). Could anyone please let me know how do I convert either (expected/actual) into class object/json, so that I can assert both? Below is the code I'm trying: obj = mixer.blend('register.Register', first_name='first_name') actual_serialized_content = RegisterSerializer(data=Register.objects.filter(first_name='first_name').values()) expected_serialized_content = serializers.serialize('json',Register.objects.filter(first_name='first_name')) I'm all new to Django and unit testing, if the above approach isn't right, please suggest. -
Global View-Context in Django App
Currently I've a class which I call in every single view for some global context variables which I use in my templates. It looks like this: class WikiContext(): def getWikiContext(self, view, request): context = { 'app': request.resolver_match.app_name, 'controller': view.__class__.__module__.split('.')[-1], 'action': view.__class__.__name__.lower(), 'categories': CategoryModel.objects.all() } return context I call it like this in every single view: context = WikiContext().getWikiContext(self, request) Is it possible to make it a little less code? I don't wanna repeat the call in every single view if possible. Thank you. -
django ManifestStaticFilesStorage 500 error
django 11.5 python 3.5.2 I would like to attach MD5 to the file, but there will be error 500 information, opened the debug, I can not see where the error appears. (English is not my native language; please excuse typing errors.) settings.py STATICFILES_STORAGE = 'django.contrib.staticfiles.storage.ManifestStaticFilesStorage' STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') templates <!-- Favicons --> {% load static %} <link rel="icon" type="image/x-icon" href="{% static "favicon/favicon.ico" %}"> <link rel="apple-touch-icon" href="{% static "favicon/apple-touch-icon-precomposed.png" %}"> <!-- Bootstrap --> <link href="{% static "css/bootstrap.min.css" %}" rel="stylesheet"> <link href="{% static "css/style.css" %}" rel="stylesheet"> python3 manage.py collectstatic You have requested to collect static files at the destination location as specified in your settings: /data/mysite/static This will overwrite existing files! Are you sure you want to do this? Type 'yes' to continue, or 'no' to cancel: yes Post-processed 'admin/css/login.css' as 'admin/css/login.a846c0e2ef65.css' Post-processed 'admin/css/base.css' as 'admin/css/base.31652d31b392.css' Post-processed 'admin/css/fonts.css' as 'admin/css/fonts.494e4ec545c9.css' Post-processed 'admin/css/changelists.css' as 'admin/css/changelists.f6dc691f8d62.css' Post-processed 'admin/css/rtl.css' as 'admin/css/rtl.4c867197b256.css' Post-processed 'admin/css/forms.css' as 'admin/css/forms.15ebfebbeb3d.css' Post-processed 'admin/css/dashboard.css' as 'admin/css/dashboard.7ac78187c567.css' Post-processed 'admin/css/widgets.css' as 'admin/css/widgets.5e372b41c483.css' Post-processed 'css/style.css' as 'css/style.476c9dc9ef58.css' Post-processed 'css/bootstrap.min.css' as 'css/bootstrap.min.5c7070ef655a.css' Post-processed 'admin/css/dashboard.css' as 'admin/css/dashboard.7ac78187c567.css' Post-processed 'admin/css/changelists.css' as 'admin/css/changelists.f6dc691f8d62.css' Post-processed 'admin/css/base.css' as 'admin/css/base.6b517d0d5813.css' Post-processed 'admin/css/fonts.css' as 'admin/css/fonts.494e4ec545c9.css' Post-processed 'admin/css/rtl.css' as 'admin/css/rtl.4c867197b256.css' Post-processed 'admin/css/forms.css' as 'admin/css/forms.2003a066ae02.css' Post-processed 'admin/css/widgets.css' as 'admin/css/widgets.5e372b41c483.css' Post-processed 'admin/css/login.css' … -
how to avoid increasing url in django
I am new to Django and learning it by developing small projects. Currently i am creating login app.I am facing below issue, i have written on form tag in one template: <form method="GET" action="login_page/"> {% csrf_token %} <button type ="submit"> Login</button> </form> after clicking submit button i goes to login/page url. And in the other template i have written below form tag, <form method="GET" action= "Welcome/"> {% csrf_token %} <button type ="submit"> Sign Up</button> </form> and my urls are: urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^login_page/', include('login.urls')) ] urlpatterns=[ #url(r'^$',TemplateView.as_view(template_name='base.html'),name='base'), url(r'^$',views.HomeView.as_view(),name='home'), url(r'^Welcome/$', views.WelcomeView.as_view(), name='Welcome'), #url(r'^Welcome/$',TemplateView.as_view(template_name='Welcome.html'),name='Welcome'), url(r'^logout/$',TemplateView.as_view(template_name='Logout.html'),name='Logout'), url(r'^home/$',views.HomeView.as_view(),name='home') ] but the issue is as i goes on and click submit buttons url keeps increasing, like http://localhost:8000/login_page/ localhost:8000/login_page/Welcome/ localhost:8000/login_page/Welcome/login_page and hence it gives error as it can not find 3rd url. how to correct it. ? can we go to views for action in form tag? -
django-filter - show only relevant filter values
I am using django-filters and can't figure out how to display only relevant to my queryset filter values. From code below I am displaying products by specific category but I receive all filter values that might not be applicable to that category. How do I display only relevant filter values? models.py Class Product(models.Model): name = models.CharField(max_length=512, unique=True, db_index=True) slug = models.SlugField(max_length=512, unique=True, db_index=True) categories = models.ManyToManyField(Category, related_name='products') description = models.TextField() status = models.BooleanField(default=True) manufacturer = models.CharField(max_length=64) common_attributes = JSONField(blank=True, null=True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateField(auto_now=True) Class ProductFilter(django_filters.FilterSet): manufacturer = django_filters.AllValuesMultipleFilter(name='manufacturer', widget=forms.CheckboxSelectMultiple) Class Meta: model = Product fields = ['manufacturer'] views.py def show_category(request, category_slug): category = get_object_or_404(Category, slug=category_slug) subcategories = Category.objects.filter(parent_id=category.id) products = ProductFilter(request.GET, queryset=Product.objects.filter(categories=category).annotate(starting_price=Min('variant__price'))) breadcrumbs = Category.get_parents(category.id) return render(request, 'catalog/category.html', {'category' : category, 'subcategories' : subcategories, 'breadcrumbs' : breadcrumbs, 'products' : products}) -
How do I separate user accounts in Django ?
I am using Django to create an app that allows recording of medical information however I am having problems with seperating the user accounts so currently all users see the same information entered. Anyone familiar with django knows how to set the proper permissions and roles and is willing to help a newby out? I want the user to only access to the account the user creates and the records that the user create. This is my github link If you are able to to help I would really appreciate it. -
Digital Ocean 502 Bad Gateway
I just setup my Digital Ocean droplet and and have been following a tutorial to get Django setup. However, upon restarting gunicorn my site now just has an error page: 502 Bad Gateway nginx/1.10.3 (Ubuntu) I am new to this stuff so I have no idea what the problem, please help! From my Nginx error logs I see this: 2017/09/25 22:23:51 [error] 2140#2140: *10 upstream prematurely closed connection while reading response header from upstream, client: 110.72.37.75, server: _, request: "GET / HTTP/1.0", upstream: "http://unix:/home/django/gunicorn.socket:/" 2017/09/25 22:24:02 [error] 2140#2140: *12 upstream prematurely closed connection while reading response header from upstream, client: 110.72.37.75, server: _, request: "GET / HTTP/1.0", upstream: "http://unix:/home/django/gunicorn.socket:/" 2017/09/25 22:24:13 [error] 2140#2140: *16 upstream prematurely closed connection while reading response header from upstream, client: 110.72.37.75, server: _, request: "HEAD /manager/html HTTP/1.0", upstream: "http://unix:/home/django/gunicorn.socket:/manager/html" 2017/09/25 23:38:16 [error] 2140#2140: *25 connect() to unix:/home/django/gunicorn.socket failed (111: Connection refused) while connecting to upstream, client: 68.81.142.218, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "104.236.213.167" 2017/09/25 23:38:17 [error] 2140#2140: *25 connect() to unix:/home/django/gunicorn.socket failed (111: Connection refused) while connecting to upstream, client: 68.81.142.218, server: _, request: "GET / HTTP/1.1", upstream: "http://unix:/home/django/gunicorn.socket:/", host: "104.236.213.167" -
Django login error: “attempt to write a readonly database” in IIS
I have a Django web app installed in IIS 10 and I applied some models into the db.sqlite3 but when I tried to log into the django/admin/login I encountered the error: OperationalError at /admin/login/attempt to write a readonly database. I have found solutions to this problem in sqlite3 error attempt to write a read only database, Django admin backend, attempt-to-write-a-readonly-database-django and all of them mention to change the permissions of the database folder. I changed the permissions of that folder by deselecting the option Read-only (Only applies to files in folder) but it seems that when I hit the Apply button it does not make any change because I check again the folder and it has the Read-only option activated. Questions: Is there any way to change this permission by any command terminal in powershell? Do I have to do any extra step in IIS to make the db.sqlite3 working? Any help is welcome! -
Django models: Inherit from variable abstract base class
I'm hoping to inherit to a child class from a variable abstract base class. So a child class would not have to inherit from a pre-defined base class and would instead be able to inherit from any one class of multiple base classes. Ideally, the models would be setup like so: class Orders(models.Model): order_number = models.IntegerField() # Orders metrics class Meta: abstract = True class Fees(models.Model): fee_number = models.IntegerField() # Fee metrics class Meta: abstract = True class Transactions(Inherit from either Orders or Fees): transaction_number = models.IntegerField() # Transaction metrics Transactions would be able to inherit from either orders or fees as they could both be a source of a transaction. Generic foreign keys could be implemented to allow for variable foreign key reference within the Orders model and Fees model but I am curious if there is a way to do this without using generic foreign keys. Is there a specific arrangement, mixin, decorator, property, or method that will allow for association of a child class with a variable abstract parent class? -
Django how to make a url that looks like 'a/main' or 'b/main' or 'c/main'?
I am trying to create a url that can either be a/main b/main c/main The url should look something like this: url(r'^(a|b|c)/main$', view.as_view()) Then I should be able to get which value it(a, b or c) is from the args to the view. -
Insert One to One field value in django
I have the following models. class PatientInfo(models.Model): lastname = models.CharField('Last Name', max_length=200) firstname = models.CharField('First Name',max_length=200) middlename = models.CharField('Middle Name',max_length=200) ... def get_absolute_url(self): return reverse('patient:medical-add', kwargs={'pk': self.pk}) class MedicalHistory(models.Model): patient = models.OneToOneField(PatientInfo, on_delete=models.CASCADE, primary_key=True,) ... and upon submitting PatientInfo form it will go to another form which supply the MedicalHistory Details. I can see my PatientInfo data as well as MedicalHistory data but not linked to each other. Below is my MedicalCreateView which process my MedicalHistory form. class MedicalCreateView(CreateView): template_name = 'patient/medical_create.html' model = MedicalHistory form_class = MedicalForm def post(self, request, pk): form = self.form_class(request.POST) if form.is_valid(): patiente = form.save(commit=False) physician_name = form.cleaned_data['physician_name'] # do not delete patient = PatientInfo.objects.all(id=self.kwargs['pk']) MedicalHistory.patient = self.kwargs['pk'] patiente.save() messages.success(request, "%s is added to patient list" % physician_name ) return redirect('index') else: print(form.errors) This is how I set MedicalHistory.patient field using the PatientInfo.pk MedicalHistory.patient = self.kwargs['pk'] -
Override Django User Model
I'm writing a Django app. I wanted to override the Django User Model for the following reasons: 1) I want to use LDAP for authentication. Therefore, Django authentication is not necessary for me. 2) I already have a user table and I want to reuse that table. I do not want Django to create a dup table for me. Also the table structure doesn't "fit" Django User model very well. Therefore, I'd like to override the Django User class. Does anyone have any good example good that I can learn from?