Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django models and join sql tables
i wanted to try using django instead of having to call my stored procedure on the DB. So i created a new model, taking informations from two differents models class TbMouvementinit(models.Model): id = models.AutoField(db_column='Id', primary_key=True) # Field name made lowercase. dateheurecreat = models.TextField(db_column='DateHeureCreat') # Field name made lowercase. dateheureclot = models.TextField(db_column='DateHeureClot', blank=True, null=True) # Field name made lowercase. id_pesee = models.BigIntegerField(db_column='Id_Pesee') # Field name made lowercase. id_proteine = models.BigIntegerField(db_column='Id_Proteine', blank=True, null=True) # Field name made lowercase. id_humidite = models.BigIntegerField(db_column='Id_Humidite', blank=True, null=True) # Field name made lowercase. id_espece = models.BigIntegerField(db_column='Id_Espece', blank=True, null=True) # Field name made lowercase. id_produit = models.BigIntegerField(db_column='Id_Produit', blank=True, null=True) # Field name made lowercase. id_codeechantillon = models.BigIntegerField(db_column='Id_CodeEchantillon', blank=True, null=True) # Field name made lowercase. id_traitement = models.BigIntegerField(db_column='Id_Traitement', blank=True, null=True) # Field name made lowercase. id_circuit = models.BigIntegerField(db_column='Id_Circuit', blank=True, null=True) # Field name made lowercase. code_source = models.CharField(db_column='Code_Source', max_length=20, blank=True, null=True) # Field name made lowercase. code_destination = models.CharField(db_column='Code_Destination', max_length=20, blank=True, null=True) # Field name made lowercase. nomos = models.CharField(db_column='NomOS', max_length=30, blank=True, null=True) # Field name made lowercase. codesite = models.CharField(db_column='CodeSite', max_length=9, blank=True, null=True) # Field name made lowercase. type_mouvement = models.CharField(db_column='Type_Mouvement', max_length=3, blank=True, null=True) # Field name made lowercase. sous_domaine = models.CharField(db_column='Sous_Domaine', max_length=1, blank=True, null=True) # Field name … -
No module named admin_view_permission, CircleCI?
When I run my Django project on CircleCI I get the following error: "ModuleNotFoundError: No module named 'admin_view_permission'" The project runs with no problems locally on my computer. I added the module admin_view_premissions, to settings, from this page: https://github.com/ctxis/django-admin-view-permission Then I ran "pip install django-admin-view-permission", and it worked fine. The migration also did not have any problems. Does anyone know why CircleCI is not able to find the module? Thank you for your time! -
Django messages are not shown if chrome data saver is enabled
Google data saver compresses data to reduce traffic usage. It is enabled by default in mobile (android) chrome and might be used in desktop chrome as plugin. Whe GDS is on django messages are NOT displayed. I created a sample application (Python 3.5, Django 1.10.8, uwsgi+nginx) to catch this bug. This app has one "submit" button on main page that triggers the view method: def welcome_view(request): if request.method == 'POST': messages.add_message(request, messages.INFO, "succeed") return HttpResponseRedirect('/') else: return render(request, 'index.html') Full app sources are here. Deployed application available at fqtest.ru Steps to reproduce: Deploy to some server (or use mine fqtest.ru). Don't forget to specify allowed hosts in settigs.py. Turn off chrome data saver plugin if you have it or use launch ingognito mode. Open main page and click Go bitton. Result: message shown as expected Turn on data saver plugin or install it (or open site from android chrome) Open main page and click Go bitton. Result: message NOT shown while it should be. Questions: What are reasons of this behavior? How can it be fixed/worked around? Hope for help. Thanks! -
How to query PointField - MongoEngine
I was trying to update PointField in my flask app with upsert_one. But it always inserts new document. I know the problem is with the query which I'm passing. Below is my model. class Location(db.Document): location_name = db.StringField(required=True) geoCoords = db.PointField() And the update query. Location.objects(geoCoords=loc["geoCoords"]).upsert_one(location_name=loc["location_name"], geoCoords=loc["geoCoords"]) #loc["geoCoords"] = [77.6309395,12.9539974] I also tried running get. But I'm getting the error message "Location matching query does not exist." for the below query. loc = Location.objects(geoCoords=[77.6309395,12.9539974]).get() I have following entries in my location collection. > db.location.find() { "_id" : ObjectId("59c5019727bae70ad3259e67"), "geoCoords" : { "type" : "Point", "coordinates" : [ 77.6309395, 12.9539974 ] }, "location_name" : "Bengaluru" } { "_id" : ObjectId("59c5022d27bae70ad3259ea2"), "geoCoords" : { "type" : "Point", "coordinates" : [ 77.6309395, 12.9539974 ] }, "location_name" : "Bengaluru" } > I couldn't find any related information on querying the PointFiled. -
After configure apache2 for django website it shows apache default page on browser
<VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly.\ ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /root/myproject/static Require all granted <Directory /root/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/root/myproject python-home=/root/myproject/myprojectenv WSGIProcessGroup myproject WSGIScriptAlias /myproject /root/myproject/myproject/wsgi.py</VirtualHost> Above is my 000-default.conf apache2 file. I have configured it for my django project named myproject and it is in root directory. And my virtualenv for this project is myprojectenv inside of myproject directory. -
How to analysis the result of django debug toolsbar?
From the debug result ,i can see my website Browser timing is really long. Basically i create 13000 item for the blog table. Seems like it takes not a long time to do sql query. The debug result My questions is how can i Identify bottlenecks from debug result. Why it loads so slowly ,takes near 20s .How can i reduce the domContentLoadedEvent and domloading Time. Thanks. -
Fom missing 1 required positional argument: 'request' in form
I am trying to get my form work using previous stackoverflow answers and google but nothing seems to work for me. I have a model Project and a project team and I would like the user to be able to choose from one of the teams that he created and link it to the project. I am using a custom user called MyUser that is my form in order to select a team: from django import forms from django.contrib.auth.models import User from registration.models import MyUser from .models import Project, Team from django.contrib.auth import get_user_model User = get_user_model() class EditSelectTeam(forms.Form): team_choice = forms.ModelChoiceField(widget=forms.RadioSelect, queryset=None) def __init__(self, User, request, *args, **kwargs): super(EditSelectTeam, self).__init__(*args, **kwargs) self.fields['team_choice'].queryset = Team.objects.all().filter(team_hr_admin = request.User) my views: def TeamSelect(request): if request.method == "POST": select_form = EditSelectTeam(request.user, request.POST) if select_form.is_valid(): print('sucess') else: print('Fail') else: select_form = EditSelectTeam(request) return render(request,'link_project.html', {'select_form':select_form }) If in my form I put request.User I get the error in my view that : TypeError: init() missing 1 required positional argument: 'request' Do not know what to do to make it work please helllpp ;) thx -
Showing error messages in template in DefaultUserCreationForm - django
I am having a problem in displaying an error message in the HTML page. I am using Django's default UserCreationForm for signup page. It has two password fields - one original and one for confirmation. When the user enters different passwords, I am getting at /signup/ whereas I want the error message to be displayed in the HTML page saying that the passwords didn't match. I have gone through the docs and I have added some related lines in my code, I don't know where I'm going wrong. Here is my views.py: def adduser(request): if request.method == 'POST': form = UserCreationForm(request.POST) print(request.POST) if(form.is_valid): try: user = employees.objects.get(emp_id=request.POST['username'] ) except employees.DoesNotExist: user = None print(user) if( user != None ): if request.POST['username'] in employees.objects.values_list('manager_id__emp_id',flat=True): g = Group.objects.get(name='Managers') newuser = form.save() newuser.groups.add(g) else: g = Group.objects.get(name='Employees') newuser = form.save() newuser.groups.add(g) return render(request,'login.html',{'form': form}) else: form = UserCreationForm() return render(request,'signup.html', {'form': form, 'msg': 'Enter valid employee id'}) else: form = UserCreationForm() return render(request,'signup.html', {'form': form}) and here is my signup.html: <body> <div class="container"> <div class="page-header"> <h1>Sign-up Here</h1> </div> {% block body %} <form method="post"> {% csrf_token %} <font color="orange" size="5px"><p> * Enter your Employee id, as username * </p></font> {{ form.as_p }} <font … -
python is asckin of existing argument in test
I try to test signals. I have signal item in app.signals.py from django.dispatch import Signal task_completed = Signal(providing_args=['balance']) Func is in user.views and it update balance according to task cost from django.contrib.messages import success from users.models import User from django.db.models import F from freelance.signals import task_completed def update_balance(cls, balance): User.objects.select_for_update().filter(user_type=User.CUSTOMER).update( balance=F('balance') - balance ) User.objects.select_for_update().filter(user_type=User.EXECUTER).update( balance=F('balance') + balance ) if success: task_completed.send_robust( sender=cls, balance=balance, ) func is called in task.models after task creation @receiver(post_save, sender=Task) def task_post_save(sender, instance, **kwargs): instance.assignee.update_balance(instance.money) And finally test that I want to make for all this things class TestCharge(TestCase): def test_should_send_signal_when_charge_succeeds(self): self.signal_was_called = False self.total = None def handler(sender, balance, **kwargs): self.signal_was_called = True self.total = balance task_completed.connect(handler) update_balance(100) self.assertTrue(self.signal_was_called) self.assertEqual(self.total, 100) task_completed.disconnect(handler) But it gives mistake like TypeError: update_balance() missing 1 required positional argument: 'balance' -
How to display instances from two different django models on the same template, inside the same table?
In a django app I've created different models and everything looks okay until I try using data from two different models inside the same table. To sum it up: in the homepage, I need to create a table that contains data from both the models, ordered by date. The two models I need to display are the following. models.py class Document(models.Model): number = models.CharField(max_length=10) description = models.CharField(max_length=50) assigned = models.BooleanField validity_date = models.DateField is_issued = models.BooleanField class Program(models.Model): name = models.CharField(max_length=25) description = models.CharField(max_length=100) validity_date = models.DateField Then, I tried to create a view that would allow me to work with different models. This is my view.py: class BaseView(generic.ListView): template_name = 'base/base_list.html' context_object_name = 'base_list' def get_queryset(self): queryset = Document.objects.order_by('due_date') return queryset def get_context_data(self, **kwargs): context = super(BaseView, self).get_context_data(**kwargs) context['Programs'] = Program.objects.all() context['Employees'] = Employee.objects.all() return context Now how can I create inside the template a table that shows both the models at once, ordering each entry by validity date (no matter if the entry belongs to Program or to Document)? Thank you in advance! -
ImportError: Module use of python34.dll conflicts with this version of Python
I have downloaded and installed Anaconda3-4.4.0 with Python 3.6. I already have Python 3.4 as the working version.Now after installing, when I try to launch Anaconda prompt I am getting the below error: No Module named 'conda' I have also added the path in the environment variables. Can anyone provide any suggestion on how to proceed further and solve this issue ? Thanks! -
Migrations applied but no migration folder
I have developed a Django 1.8 project a while ago. I deployed the project a few months back and everything was running perfectly. Today, I had to make a change in the database, but when I tried to run python manage.py makemigrations, I got the message "No changes detected". I then noticed that there was no migration folder in any of the apps of the project. What I don't understand is: I made the migrations (makemigrations then migrate) when I first deployed the project, and everything was ok. I didn't check that the migration folders were there though. I didn't made any change to the database since this first migration and didn't remove any folder. When I run python manage.py showmigrations, I get the following: admin [X] 0001_initial auth [X] 0001_initial [X] 0002_alter_permission_name_max_length [X] 0003_alter_user_email_max_length [X] 0004_alter_user_username_opts [X] 0005_alter_user_last_login_null [X] 0006_require_contenttypes_0002 contenttypes [X] 0001_initial [X] 0002_remove_content_type_name sessions [X] 0001_initial This is the full output. No sign of any of my apps. So my questions are the following: How is it possible that the migrations were made, the tables were created, etc. but no migration folder was created ? Where do I go from here ? I want to make the … -
Django delete cache with specific key_prefix
I'm using Django's per-view @cache_page decorator and have set a different key_prefix for each view. I've previously deleted the cache with: from django.core.cache import cache cache.clear() But what if I just want to delete the keys containing a specific key_prefix? I can obviously do it by just connecting to the database and delete with raw sql but I wonder if it can be done with 'pure' Django? I'm using Django 1.11 and Python 3.6 -
nginx location and Django auth
I'm trying to create a NGINX redirect based on an URL param in the querystring. Basically having: http://localhost/redirect/?url=https://www.google.it/search?dcr=0&source=hp&q=django&oq=django and location /redirect/ { proxy_cache STATIC; # cache status code 200 responses for 10 minutes proxy_cache_valid 200 1d; proxy_cache_revalidate on; proxy_cache_min_uses 3; # use the cache if there's a error on app server or it's updating from another request proxy_cache_use_stale error timeout updating http_500 http_502 http_503 http_504; # don't let two requests try to populate the cache at the same time proxy_cache_lock on; # Strip out query param "timestamp" if ($args ~ (.*)&timestamp=[^&]*(.*)) { set $args $1$2; } return 302 $arg_url$args; } It works and keeps the qs keys/values: dcr=0&source=hp&q=django&oq=django while removing the unwanted keys. I could do it at the Django level (https://github.com/mjumbewu/django-proxy/blob/master/proxy/views.py) but I suppose it's faster and less computationally expensive at the NGINX level. Is this a correct approach to proxy requests through NGINX? Now, only Django authenticated users (JWT/Cookie) can use the /redirect?url= end point, hence is it possible to implement a session/cookie check without opening a proxy to the entire world? Thanks, D -
Why does retrieving a single resource execute serializer.to_representation() multiple times in Django REST framework?
Lets say I have a model called Thingy, and there are 20 Thingies in my database. When I retrieve all Thingies, serializer.to_represenatation() is executed 20 times. This is good. However, when I retrieve just a single Thingy from /api/thingies/1, I observe that serializer.to_representation() is executed four (4!!!) times. Why does this happen, and how can I get away with just one call to to_representation()? -
Get specific attribute data from Json
I'm implemented a code to return Json value like this { "key1":"1", "key2":"2", ......} But I want to get only value of key1. so I first defined info to get Json. info = requests.get(url, headers=headers) And use info.text['key1'] to get value of key1. but i got error. could anyone suggest any solution? -
send email in django through gmail
I am trying to send a mail using django through gmail. Following is my settings.py code: EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = 'me@mycompany.com' EMAIL_HOST_PASSWORD = 'mypassword' EMAIL_USE_TLS = True view.py I am using method send_mail(): send_mail(subject, contact_message, emailfrom, emailto) When I execute the code & enter details in my contact form & hit submit. I get the below error: smtplib.SMTPNotSupportedError: STARTTLS extension not supported by server. Please suggest! -
How to pass the time to the DateTimeField?
In my models.py I have a GTTime model: class GTTime(models.Model): gt_time = models.DateTimeField(null=True) ctime = models.DateTimeField(auto_now_add=True) uptime = models.DateTimeField(auto_now=True) And in my views.py, how to add the time to in the gt_time? I tried use the time.time() to pass the timestamp, but there will report error: gt = models.GTTime(gt_time=time.time()) gt.save() Error: TypeError: expected string or buffer -
Can't display Query result in DataTable with Django
i recently made changes on my project to call stored procedure with django inside the python. I used to work with pyodbc and it was working fine, i was getting results from my stored procedure and was able to display them on the datatable. View: def index(request): cursor = connections['site'].cursor() try: cursor.execute("{CALL SP_webGET_RESUME_MVT_INIT_ACTIF}") mouvements = cursor.fetchall() finally: cursor.close() return render(request, 'index.html', locals()) Template : {% load static %} <!doctype html> <html> <head> <meta charset="utf-8"> <title>Untitled Page</title> <meta name="generator" content="WYSIWYG Web Builder 12 - http://www.wysiwygwebbuilder.com"> <link href="../static\css/Gestion_Mouvements.css" rel="stylesheet"> <link href="../static\css/index.css" rel="stylesheet"> <link href="{% static 'css/jquery-ui.min.css' %}" media="all" rel="stylesheet"> <link href="{% static 'css/jquery.dataTables.min.css' %}" media="all" rel="stylesheet"> <link href="{% static 'css/bootstrap.min.css" rel="stylesheet' %}" media="all"> <link href="{% static 'css//bootstrap-datetimepicker.min.css' %}" media="all" rel="stylesheet"> <script src="{% static 'js/jquery-1.12.4.min.js' %}"></script> <script src="{% static 'js/jquery.dataTables.min.js' %}"></script> <script src="{% static 'js/jquery-ui.min.js' %}"></script> <script> $(document).ready(function() { $('#indexTab').dataTable( { "bLengthChange": false, "lengthMenu": [ [-1], ["All"] ] } ); $('.editbtn').click(function(){ var $row = $(this).closest("tr"); // Find the row var $text = $row.find(".idMark").text(); // Find the text alert($text); }); $('.deletebtn').click(function(){ var $row = $(this).closest("tr"); // Find the row var $text = $row.find(".idMark").text(); // Find the text alert($text); }); }); </script> </head> <body> <div id="wb_Shape1" style="position:absolute;left:4px;top:5px;width:1300px;height:100px;z-index:0;"> <img src="../static\images/img0003.png" id="Shape1" alt="" style="width:1300px;height:100px;"></div> <div id="Html1" style="position:absolute;left:4px;top:107px;width:1300px;height:400px;z-index:1"> … -
Django Rest Swagger 2: Is there anyway so far to document parameters for POST requests of FUNCTION based views?
I am trying to integrate django-rest-swagger==2.1.1 with my existing project that uses djangorestframework==3.5.3. The project has some Class based views and some Function based views. After integrating swagger, It displays input boxes for POST requests of "Class Based views"(which have serializers obviously), but does not show for "function based views". The question has been asked several times, I have tried following solutions: Solution1 Solution2 and few others too, but did not work for my case. Is there any possible way to do that for 'function based views' or I ll have to convert them to class based views? -
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?