Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
how to upload created xml file in django sqlite db
I have a script that when user sends his data to my app I make an xml file and upload it for further use. I think there are two ways to implement it: I can make a model that save xml file with its username and id to database I can make a folder for each user and upload the file and save the url in database to refer to xml file. which one is efficient? and can I upload xml file to database? are there any other comfortable way to do it? -
Django rest_framework: How to pass additional attribute to exception / error response?
I'm using Python 3.6 with Django 1.11.9 and rest_framework 3.6.2. I have a view (APIView) which can only be accessed by some users who successfully pass a given HasUnlimitedAccesPermission check. In case of failure to pass the latter, I raise a PermissionDenied with a detailed message of my choice about the error to pass on to front-end. So far so good, all of that is easily achievable by applying the HasUnlimitedAccessPermission to my view thanks to the "permission_classes" decorator (yeah, I'm using a function_based view, here). Now, what I would like to achieve is passing an additional attribute to my error response JSON (when the user fails to pass the permission test). This attribute would be an "error_id" attribute that would give the front-end developer the ability to adapt the error display depending on the "error_id" value. An example of the response JSON would be : { "error": "To enjoy this feature, go pick one of our pay offer!", "error_id": "no_unlimited_access" } Any idea on how to achieve this? -
Django 1.10 Templates - Print two python lists next to eachother in HTML Template
I am currently querying my test legacy database for all objects with value oee_hour which are not null using: lines_hourly = Lineoeex.objects.all.values('oee_hour') hourly_oee_list = list (Lineoeex.objects.all().values_list('oee_hour', flat=True).exclude(oee_hour=None)) #no null entries In the same row, my database also contains a date_hour column, also containing null values. I am querying for all objects with value date_hour using: time_hourly = Lineoeex.objects.all.values('date_hour') time_hourly_list = list (Lineoeex.objects.all().values_list('date_hour', flat=True).exclude(date_hour=None)) Both lists match, with 1 real value followed by 5 null values I am then passing on these variables on to my template. I am iterating over the hourly_oee_list in my HTML code and printing each value. How do I print the date_hour values from the time_hourly_list next to the hourly_oee? Code to print hourly_oee <ul class="list-group"> {% for hourlyoee in hourly_oee_list %} <li class="list-group-item> OEE: {{ hourlyoee }} </li> {% endfor %} </ul> This prints out all the oee_hour values in the hourly_oee_list. I want to print out the date_hour values inside time_hourly_list right next to the OEE values with the same stylings. Nesting the for loops does not give the desired effect. Any suggesionts on how this can be implemented? thanks -
Take a picture remotely
I have to developed a new project and I am little lost. The project consist in set a ip camera to take pictures accessing remotely. My first idea is build a Raspberry with a camera device, connect it to a WiFi network and open a port in the router, after, create a little interface for the client with Django to access remotely, through a python script, run a command line in the Raspberry that take the photo and download it in a server because the second part is analyze the picture with Vision Cloud Google Api. Any suggestion? Anybody has done something similar ? Is posible do that with existing IP camera in the market ? Thanks for the help -
Django with MySQL migration is not working
I have created a sample application by using Python V3.6 and Django 2.1 and I am using MySQL for the database. I have successfully integrated MySQL after a long struggle but now when I try to create a SuperUser for my application it is throwing an error (django_dev) C:\Users\******\Desktop\django_projects\shield>python manage.py mig rate Operations to perform: Apply all migrations: admin, auth, contenttypes, server_status, sessions Running migrations: Applying server_status.0001_initial... OK Traceback (most recent call last): File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\dja ngo\db\backends\utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\dja ngo\db\backends\mysql\base.py", line 71, in execute return self.cursor.execute(query, args) File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\MyS QLdb\cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\MyS QLdb\connections.py", line 50, in defaulterrorhandler raise errorvalue File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\MyS QLdb\cursors.py", line 247, in execute res = self._query(query) File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\MyS QLdb\cursors.py", line 411, in _query rowcount = self._do_query(q) File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\MyS QLdb\cursors.py", line 374, in _do_query db.query(q) File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\MyS QLdb\connections.py", line 277, in query _mysql.connection.query(self, query) _mysql_exceptions.ProgrammingError: (1146, "Table 'shield_dev.django_content_typ e' doesn't exist") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\dja ngo\core\management\__init__.py", line 381, in execute_from_command_line utility.execute() File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\dja ngo\core\management\__init__.py", line 375, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\ccduce\AppData\Local\Continuum\miniconda3\lib\site-packages\dja ngo\core\management\base.py", line 316, … -
Make running tests mandatory before runserver in django
Is there any way to make running tests compulsory before running the server in django? I have a project on which many people will be working on so i want to make the testing compulsory before running it and all tests must pass before it runs. So basically lock the runserver command until all the tests pass successfully. Please reply ASAP. -
Django changing CharField to ForeignKey cause OperationalError "Unknown column"
In my app, I have a field in my CalibrationForm model called cf_ani cf_ani = models.CharField(max_length=150) I wanted this field to become a dropdown where the user would select from choices contained in a model called Subjects. So, I changed the field from CharField to ForeignKey in models.py: cf_ani = models.ForeignKey( Subjects, on_delete=models.CASCADE, ) I run python manage.py makemigrations and the altered field is generated. I run python manage.py migrate and the following is returned: Running migrations: Applying CalibrationForm.0026_auto_20180821_0630...Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/django/db/backends/utils.py", line 85, in _execute return self.cursor.execute(sql, params) File "/usr/local/lib/python3.4/dist-packages/django/db/backends/mysql/base.py", line 71, in execute return self.cursor.execute(query, args) File "/usr/local/lib/python3.4/dist-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/usr/local/lib/python3.4/dist-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue File "/usr/local/lib/python3.4/dist-packages/MySQLdb/cursors.py", line 247, in execute res = self._query(query) File "/usr/local/lib/python3.4/dist-packages/MySQLdb/cursors.py", line 411, in _query rowcount = self._do_query(q) File "/usr/local/lib/python3.4/dist-packages/MySQLdb/cursors.py", line 374, in _do_query db.query(q) File "/usr/local/lib/python3.4/dist-packages/MySQLdb/connections.py", line 277, in query _mysql.connection.query(self, query) _mysql_exceptions.OperationalError: (1054, "Unknown column 'cf_ani' in 'CalibrationForm_calibrationform'") The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.4/dist-packages/django/core/management/__init__.py", line 371, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.4/dist-packages/django/core/management/__init__.py", line 365, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.4/dist-packages/django/core/management/base.py", line 288, in … -
Django error in request/response middleware- TypeError: __init__() takes 1 positional argument but 2 were given
I'm still pretty new to Django and cant seem to get anywhere with this error (I've read through similar posts here with no luck). Code in urls.py is pasted below: from django.conf.urls import include, url from django.contrib import admin # Add this import from django.contrib.auth import views from log.forms import LoginForm urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^', include(('dashboard.urls', "dashboard"), namespace='dashboard')), url(r'^login/$', views.LoginView, {'template_name': 'login.html', 'authentication_form': LoginForm}, name='login'), url(r'^logout/$', views.LogoutView, {'next_page': '/'}), ] Full trace is below: Internal Server Error: /login/ Traceback (most recent call last): File "C:\Python36-32\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Python36-32\lib\site-packages\django\core\handlers\base.py", line 127, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Python36-32\lib\site-packages\django\core\handlers\base.py", line 125, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) TypeError: __init__() takes 1 positional argument but 2 were given [21/Aug/2018 00:20:27] "GET /login/?next=/ HTTP/1.1" 500 64213 Any ideas on how to solve this? Or what could be causing this error? -
Django channels 2 : display live sensor, GPS informations
Django 2, Geodjango 2 and Channels 2 I want to display live informations on a webpage from sensors. In my case, i would like to display a point position from an usb serial GPS. I have a good understanding of GeoDjango. But it's not clear for me how to use the new Channels 2 to read sensor information and display it in live. Could you give me an example? Particularly the consumers.py -
Get module name as parameter in request
What is the best way to get my module name as a function in request function?. I tried the following but is not working at all (Page not found). Something is wrong in the url regex? : url(r'^<entity>=accounts/(?P<pk>[0-9a-z\-]+)/activate_entity/$', activate_entity) def activate_entity(request, entity, pk): entity_model = apps.get_model(app_label='entities', model_name=entity) entity_object = entity_model.objects.get(pk=pk) -
Django - how to notify the user that form was submitted successfully or not?
I created a small form where the user can enter his name and upload a text file. Now, after the user clicks on upload, I want to display a message on the screen like a toast or something that will say whether the upload was successful or not. I'm not quit sure how to do it, because after, submitting the form, the user just get redirected to another page. Side note: I use Django 1.7 (I know it's old, but this is the project I got to work on from someone else) Here is my html snippet where the user fills the fields: <form action="{{ request.build_absolute_uri }}upload/" method="POST" enctype="multipart/form-data"> <input id="Name" name="Name" type="text" placeholder="Name" style="width:100%"> <br> <input type="file" name="file"/> <br /> <input type="submit" value="Upload File" /> </form> Here is my views.py: def upload(request): if request.method == 'POST': name = request.POST.get('name') handle_uploaded_file(request.FILES['file'], str(request.FILES['file']), name) return HttpResponse("Successful") def handle_uploaded_file(file, filename, name): # if not os.path.exists('upload/'): # os.mkdir('upload/') fileContent = "" with open('upload/' + filename, 'wb+') as destination: for chunk in file.chunks(): fileContent += chunk # destination.write(chunk) currentDT = datetime.datetime.now() policy = Policy.create(name, currentDT, fileContent); policy.save() -
django allauth redirect issue debug
I am facing some problem while working with django-allauth. I am using google authentication with the help of django-allauth. I have set the redirect url in the google api console as directed in the official documentation.Also, I have set the LOGIN_REDIRECT_URL as stated in the documentation. Authorized redirect url in google api console: http://127.0.0.1:8000/accounts/google/login/callback/ Settings.py LOGIN_REDIRECT_URL = "user_dashboard" SOCIALACCOUNT_PROVIDERS = { 'google': { 'SCOPE': [ 'profile', 'email', ], 'AUTH_PARAMS': { 'access_type': 'online', 'hd': 'xxx.yyy' } } } urls.py url('^', include('django.contrib.auth.urls')), url(r"accounts/profile/logout", views.my_logout, name="logout"), url(r'^accounts/',include("allauth.urls")), url(r'^admin/', admin.site.urls), url(r'^admin/inventory_management_app/device/router_specifications/', views.pdf_download, name = "pdfdownload"), url(r'^admin/inventory_management_app/repair/repair_invoice/', views.repair_pdf_download, name = "pdfdownload"), url(r'accounts/profile/home',views.my_dashboard,name='user_dashboard'), url(r'accounts/profile/user_dashboard', views.my_dashboard, name = "user_dashboard"), I get a social network authentication failure. I overrode the authentication_error.html to find the cause but, still did not get any workable response. requesting your help at the earliest. -
MultiValueDictKeyError at deletemultipleclient at form_data
from urlparse import parse_qs form_data = parse_qs(request.POST['form_data'].encode('ASCII')) for client_id in form_data["clients"]: -
Is it possible to add a temlate to django CKEditor without editing it's templates-plugin files in site-packages?
There is a file in lib/python3.6/site-packages/ckeditor/static/ckeditor/ckeditor/plugins/templates/templates/default.js that i can edit to add more templates to my RichTextFields. But i would really like to track those changes with git and i don't want to add my environment to git. Is there a way to customize, add templates to django ckeditor's templates plugin? -
How to give users authorisation to access specific fields/objects of the Model Form at /admin in django?
models.py from django.db import models from django.contrib.auth.models import User CHOICES = (('1','Earned Leave'),('2','Casual Leave'),('3','Sick Leave'),('4','Paid Leave')) class Leave(models.Model): name = models.CharField(max_length = 50) user = models.ForeignKey(User, on_delete = models.CASCADE, null =True) employee_ID = models.CharField(max_length = 20) department = models.CharField(max_length = 50) designation = models.CharField(max_length = 50) type_of_leave = models.CharField(max_length = 15, choices = CHOICES, default = None) from_date = models.DateField(help_text = 'mm/dd/yy') to_date = models.DateField(help_text = 'mm/dd/yy') reporting_manager = models.CharField(max_length = 50, default = None, help_text = '0001_manager, 0002_manager') reason = models.CharField(max_length= 180) accepted = models.BooleanField(('approval status'), default= False) def __str__(self): return self.name I want the user to only access the 'type_leave_field' after submitting the form, when he is given 'is staff' status. forms.py from django import forms from lrequests import models class LeaveRequestForm(forms.ModelForm): class Meta: fields = ("name", "employee_ID", "department", "designation", "type_of_leave", "from_date", "to_date", "reporting_manager", "reason") model = models.Leave views.py from django.shortcuts import render from django.http import HttpResponse from .forms import LeaveRequestForm from .models import Leave def leaveRequest(request): form_class = LeaveRequestForm if request.method == "POST": form = LeaveRequestForm(request.POST) if form.is_valid(): leave = form.save(commit = False) leave.user = request.user form.save() return HttpResponse("Sucessfully submitted") else: form = LeaveRequestForm() return render(request, "request_form.html", {'form' : form_class}) I've tried using django-guardian and django-objectpermissions, but … -
Duplicate views or add parameters
I want to build a django application where the users are workers in a callcenter. When they talk to a client they have a specific task, but at some point they optionally might need to update the client's contact data. The point is that there already is a view for updating the contact data. So I am wondering whether I should reuse that view. I can think of roughly three options: Reuse the view and pass the return URL as parameter Create a new view that reuses parts of the existing view (e.g. template) Create a completely new view What would you recommend and why? -
How to handle Django dynamic in front end?
I have a Django form class which generates dynamic form fields to the front end. I want to perform operations such as enable, disable, hide, display etc.. by using java script.simply I want take control of the django dynamic form js. This is my django form class SetFeatureForm(forms.Form): def __init__(self, project=None, *args, **kwargs): super(SetFeatureForm, self).__init__(*args, **kwargs) if project: choices = [(column,column) for column in pd.read_csv(project.file.path).columns] self.fields['feature'] = forms.MultipleChoiceField(choices=choices, required=True, ) self.fields['feature'].widget.attrs['size']=len(choices) for _,choice in choices: self.fields[choice] = forms.ChoiceField( choices=DATA_TYPE.items()) Is there any way to do that? -
how to send data to dynamic jstree with alternative json format from django
I tried the following process but queryset was totaly changed it's format. $('#jstree').jstree({ 'core' : { 'data' :{{data}} # here main issue }, plugins : ["wholerow","unique","dnd","sort","state","contextmenu","contextmenubtn","themes"] }).on("ready.jstree", function (e, data) { data.instance.open_all(); }); qureyset i sent in response: data=Buildkb4.objects.values("id","text","parent") return render(request,"registration/basetest.html", {"data": data}) output: no table structure and no data on page source code i got following output for the query: data= &lt;QuerySet [{&#39;text&#39;: &#39;PKM&#39;, &#39;parent&#39;: 0, &#39;id&#39;: 1}, {&#39;text&#39;: &#39;develop&#39;, &#39;parent&#39;: 1, &#39;id&#39;: 2}, {&#39;text&#39;: &#39;social&#39;, &#39;parent&#39;: 1, &#39;id&#39;: 3}]&gt; -
Unwanted random value found in profile for custom user
I'm following https://docs.djangoproject.com/en/2.1/topics/auth/customizing/#a-full-example , to create user with email as username. I'm also create a one-to-one relationship, with a profile table. The profile table contains a API key column I looks at the user table and profile table. Both of them looks fine. If I have 3 records in user table, I will only have 3 records in profile table, as they are one-to-one relationship. However, when I look login into admin page. Things doesn't sound right. Each user is associated with 2 API keys. The first API key seem to be a random generated value, another API key is a valid API key from DB. Here's the current database. snapweb=# select * from accounts_myuser; id | password | last_login | email | is_active | is_admin ----+--------------------------------------------------------------------------------+-------------------------------+ 2 | pbkdf2_sha256$120000$w7OlH | | yccheok@yahoo.com | t | f 1 | pbkdf2_sha256$120000$tWA6Y | 2018-08-21 05:07:28.391689+00 | root@root.com | t | t 3 | pbkdf2_sha256$120000$TkKAE | | yancheng.cheok@gmail.com | t | f (3 rows) snapweb=# select * from accounts_profile; id | api_key | user_id ----+--------------------------------------+--------- 1 | d6ee9b31-6847-4b7d-8151-98b133f21c42 | 1 2 | c6f3718e-41ee-4759-984a-63c405b32fc4 | 2 3 | 10c64d48-416f-4fd7-b01d-4328d2536ea2 | 3 (3 rows) Now, the value shown in admin page is API KEY: 6cb1b77f-6ab0-464d-9176-d0ed20402b8c: … -
Django Allauth not Authenticating on email
I am using django allauth for providing social login using github and google. I have users already registered. I have to login the users based on their emails. Firstly I tried authenticating with google, and it redirected me to a link /accounts/social/signup/ It prompted me a form with username and email of user (the email column is already filled). If I give some username and click submit it creates a new user of that form. Instead of logging the current user. I am not understanding where the flaw is settings.py code -- SOCIALACCOUNT_QUERY_EMAIL = True ACCOUNT_AUTHENTICATION_METHOD='email' ACCOUNT_EMAIL_REQUIRED = True SOCIALACCOUNT_PROVIDERS = \ {'github': { 'SCOPE': [ 'email', ], 'google': {'SCOPE': ['https://www.googleapis.com/auth/userinfo.profile', 'email'], 'AUTH_PARAMS': {'access_type': 'online'} }, } I am trying to login users based on their emails. Am I wrong at any point ?? My Login template <a href="{% provider_login_url 'google' process='login' %}" class="connect google"> <a href="{% provider_login_url 'github' process='login' %}" class="connect github"> It is acctually performing operation of signup everytime instead of login. How actually to prevent it and login users based on email ? Thanks!! -
ImageField: save and display matplotlib image to template
I am attempting to render a page with a histogram based on data scraped from Twitter. In display_locations, I have successfully displayed the Twitter data in a dict based on frequency. Now, I wish to display the data on a histogram. The immediate ERROR I'm getting is: NameError: ImageFile not defined. However, I'm in general lost in terms of how to successfully save a matplotlib image to a Model. CODE Models.py class Hashtag(models.Model): """ Model representing a specific Hashtag serch by user """ search_text = models.CharField(max_length=140, primary_key=True) location = models.ManyToManyField(Location, blank=True) histogram = models.ImageField(upload_to=None, null=True) def __str__(self): """ String for representing the Model object (search_text) """ return self.search_text def display_locations(self): """ Function to create a dict by frequency of the locations associated with search_text """ country_list = list(self.location.values_list('country', flat=True).all()) for country in country_list: location_freq = {i:country_list.count(i) for i in set(country_list)} return location_freq @property def get_histogram(self): """ Function to create a histogram of locations associated with search_text """ location_freq = self.display_locations() plt.bar(list(location_freq.keys()), location_freq.values(), color='g') f = io.BytesIO() # redirect into the BytesIO object plt.savefig(f, format="png", facecolor=(0.95,0.95,0.95)) content_file = ImageFile(histogram) -
Is it possible to create a Django model w/ variable functions as an attribute (passed in either via __init__ or some method)?
I'm creating an app. that will generate math problems. They're specific problems where some parameters can be altered. Each problem will be different, and require a different method to solve (all of which will be programatically implemented). For example: models.py import random from django.db import models class Problem(models.Model): unformattedText = models.TextField() def __init__(self, unformattedText, genFunction, *args, **kwargs): super(Problem, self).__init__(*args, **kwargs) self.unformatedText = unformattedText self.genFunction = genFunction def genQAPair(): self.genFunction(self.unformattedText) views.py def genP1(text): num_1 = random.randrange(0, 100) num_2 = random.randrange(0, 100) text.format((num_1, num_2)) return {'question':text, 'answer':num_1 - num_2} def genP2(text, lim=4): num_1 = random.randrange(0, lim) text.format(num_1) return {'question':text, 'answer':num_1*40} p1 = Problem( unformattedText='Sally has {} apples. Frank takes {}. How many apples does Sally have?', genFunction=genP1 ) p1.save() p2 = Problem( unformattedText='John jumps {} feet into the air. How long does it take for him to age?', genFunction=genP2 ) p2.save() When I try this, the function isn't actually saved. Django just saves the integer 1. When I initiate an instance of the model, the function is there as intended, but apparently only 1 is saved to the database. Bonus question: I'm actually beginning to question whether or not I even need Django models for this. I'm using Django because it's super … -
Django - Best method for comparing real person names
Assuming I have A) Model: class Person(models.Model) first_names: models.CharField() last_names: models.CharField() B) Dataset: first_names: "John", last_names: "Smith" first_names: "John", last_names: "Bar Smith" first_names: "John Foo", last_names: "Smith" I woul like to see if a person first_names: "John", last_names: "Smith" or first_names: "John", last_names: "Bar Smith" exists in my Dataset in order to avoid duplicates. My first though was to use ElasticSearch for this. Are there any "cheaper" methods - perhaps django native - to do this? -
python change bash directory mac
Everyday When i open my mac. I open bash and execute the following commands : cd desktop cd reference cd django cd mel cd python3 manage.py runseerver I want to make the above process automated, where If i run one python script all the above should be executed in the shell. When I have tried so far : import os wd = os.getcwd() os.chdir("desktop") The above doesn't give me any error nor does it changes the directory -
Django curl request
Im trying to use curl to hit an endpoint in my Django application and havent been successful returning my data. curl 127.0.0.1:8000/myapp/?email=myname@gmail.com&part=123434 my server shows a 301 when the curl goes through, however; none of the print statements are ran in my view, and i am not able to get the querystring parameters using request.GET.get(). [21/Aug/2018 00:26:59] "GET /myapp/?email=myname@gmail.com HTTP/1.1" 301 0 view.py def index(request): if request.method == 'GET': print('hello world') email = request.GET.get('email') part = request.POST.get('part') print(email) print(part) df = generate_dataframe('apps/myapp/data.csv') df = get_dataframe_by_part(part, df) bool = check_all(email, df) response_data = {} response_data['DoesUserExist'] = bool return HttpResponse(json.dumps(response_data), content_type="application/json")