Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Rendering Matplotlib chart in HTML using mpld3
I'm trying to get a mpld3 chart into my webapp using Django and MPLD3/Matplotlib. As described here it should be straightforward getting the HTML code of the figure written in python. Views.py def figure(request): np.random.seed(9615) N = 100 df = pd.DataFrame((.1 * (np.random.random((N, 5)) - .5)).cumsum(0), columns=['a', 'b', 'c', 'd', 'e'], ) # plot line + confidence interval fig, ax = plt.subplots() ax.grid(True, alpha=0.3) for key, val in df.iteritems(): l, = ax.plot(val.index, val.values, label=key) ax.fill_between(val.index, val.values * .5, val.values * 1.5, color=l.get_color(), alpha=.4) ax.set_xlabel('x') ax.set_ylabel('y') ax.set_title('Interactive legend', size=20) html_fig = mpld3.fig_to_html(fig,template_type='general') plt.close(fig) return render(request, "dashboard.html", {'active_page' : 'dashboard.html', 'div_figure' : html_fig}) dashboard.html <div id="fig_container"> {{ div_figure }} </div> AFAIK, the python code gets translated into javascript and should be executed when views.py is rendering dashboard.html, right? As result, I get the HTML code displayed as text on my dashboard.hmtl. QUESTION: How do I get the chart displayed? Do I need to parse the HTML string which is returned by the method html_to_fig? -
Django system check stuck
I have following method def do(self): reservations = Reservation.objects.filter(is_synced=False) for reservation in reservations: serializer = ReservationPKSerializer(reservation) dictionary = {'url': 'url', 'hash': 'hash', 'json': serializer.data} encoded_data = json.dumps(dictionary) r = requests.post('http://gservice.ca29983.tmweb.ru/gdocs/do.php', headers={'Content-Type': 'application/json'}, data=encoded_data) if r.status_code == 200: reservation.is_synced = True reservation.save() When dev server starts it stuck on Performing system checks.... But if remove http://gservice.ca29983.tmweb.ru/gdocs/do.php and change it to any another url, problem doesn't happen, server starts good. It seems that something wrong with url. What may it be ? -
Password field in django admin not displaying value
I have a Crew Model. The table has a password field. I dont want to display password in plain text. So I have added forms where I have used widget=forms.PasswordInput(). But this doesnt show the password after saving the data. class Crew(models.Model): crew_id = models.AutoField(primary_key=True) crew_code = models.CharField(max_length=200, null=False, unique=True) crew_name = models.CharField(max_length=200, null=False) crew_password = models.CharField(max_length=200, null=False) Forms.py class UserForm(forms.ModelForm): crew_password = forms.CharField(widget=forms.PasswordInput()) class Meta: model = Crew fields = ('crew_name', 'crew_password', 'crew_code', 'crew_id') -
mysql malformed packet error after running makemigrations django
The issue that we are getting is : we have run manage.py makemigrations and manage.py migrate successfully, after which we start getting the below error: File "/usr/local/goibibo/python/lib/python3.5/site-packages/django/db/backends/mysql/base.py", line 110, in execute return self.cursor.execute(query, args) File "/usr/local/goibibo/python/lib/python3.5/site-packages/MySQLdb/cursors.py", line 250, in execute self.errorhandler(self, exc, value) File "/usr/local/goibibo/python/lib/python3.5/site-packages/MySQLdb/connections.py", line 50, in defaulterrorhandler raise errorvalue File "/usr/local/goibibo/python/lib/python3.5/site-packages/MySQLdb/cursors.py", line 247, in execute res = self._query(query) File "/usr/local/goibibo/python/lib/python3.5/site-packages/MySQLdb/cursors.py", line 411, in _query rowcount = self._do_query(q) File "/usr/local/goibibo/python/lib/python3.5/site-packages/MySQLdb/cursors.py", line 374, in _do_query db.query(q) File "/usr/local/goibibo/python/lib/python3.5/site-packages/MySQLdb/connections.py", line 292, in query _mysql.connection.query(self, query) django.db.utils.OperationalError: (2027, 'Malformed packet') This issue does not come every time we run makemigrations. It comes randomly, but once it comes it just sticks and we have no clue on why this is happening. Can somebody assist us in fixing this and explain why this might be happening. Packages Used in App: adium-theme-ubuntu==0.3.4 appdirs==1.4.3 asn1crypto==0.22.0 backports-abc==0.5 blinker==1.4 boto3==1.4.4 botocore==1.5.35 certifi==2017.4.17 cffi==1.10.0 chardet==2.3.0 click==6.7 ConcurrentLogHandler==0.9.1 configobj==5.0.6 decorator==4.0.11 Django==1.10.4 djangorestframework==3.5.3 docutils==0.13.1 Flask==0.11.1 futures==3.1.1 gevent==1.2a1 greenlet==0.4.10 gyp==0.1 idna==2.5 itsdangerous==0.24 Jinja2==2.8 jmespath==0.9.2 jsonpatch==1.10 jsonpath==0.75 jsonpath-rw==1.4.0 jsonpointer==1.10 MarkupSafe==1.0 newrelic==2.82.0.62 oauthlib==1.0.3 packaging==16.8 Pillow==3.1.2 ply==3.10 prettytable==0.7.2 pyasn1==0.1.9 pycparser==2.17 pycurl==7.43.0 PyJWT==1.3.0 PyMySQL==0.7.9 PyOpenGL==3.0.2 pyparsing==2.2.0 Pyrex==0.9.8.5 pyserial==3.0.1 PySocks==1.6.5 python-dateutil==2.6.0 PyYAML==3.11 requests==2.14.2 s3transfer==0.1.10 singledispatch==3.4.0.3 six==1.10.0 SQLAlchemy==1.1.4 ssh-import-id==5.5 tornado==4.4.2 unity-lens-photos==1.0 urllib3==1.19.1 virtualenv==15.1.0 Werkzeug==0.12.1 -
filter by is_active boolean field in django
I want to have an is_active field for all the models in my application and when ever I create an api, I want to filter only the active ones and send the response. Is there a generic way to do this? As of now I am keeping a boolean field is_active and every time I retrieve the objects, I am writing a filter. below is the code : My models.py class Crew(models.Model): crew_id = models.AutoField(primary_key=True) crew_code = models.CharField(max_length=200, null=False, unique=True) crew_name = models.CharField(max_length=200, null=False) crew_password = models.CharField(max_length=200, null=False) is_active = models.BooleanField(default=True) My views.py : @api_view(['GET']) def get_crews(request): c = Crew.objects.filter(is_active=True) serializer = CrewSerializer(c, many=True) return Response(serializer.data, status=status.HTTP_200_OK) -
How to empty all reply channel from group?
I don't know which reply channels are in the Channel Group but I want to empty the group. How to do that? -
How to handle ImageFiled in Django rest framework?
I am new to django rest framework and trying to handle image data. After adding an ImageFiled i can upload image to my model. But on accessing that image via browser, the browser returns a page not found error. My model from __future__ import unicode_literals from django.conf import settings from django.db import models from rest_framework import serializers from urlparse import urljoin class Item(models.Model): name = models.CharField(max_length=64, verbose_name='name') address = models.CharField(max_length=64, verbose_name='address') image = models.ImageField(max_length=None, null=True) def __str__(self): return self.name Model serializer class ItemSerializer(serializers.ModelSerializer): class Meta: model = Hotel fields = ('name','address','id','image') The field image returns a url and on hitting that url the browser returns a 404 error. So what is the proper way to implemet an api with image data? -
How do I `save()` a Profile model if it has a OneToOne relationship to my AbstractBaseUser model without running into UNIQUE constraint errors?
I have two separate models: 1. A MyUser model which inherits from AbstractBaseUser, and has a field of profile_page = models.OneToOneField(Profile, null=True) 2. A Profile model with a user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True, blank=True) relationship to the User model. I am attempting to allow users of the site to edit their own Profile information by providing them a ProfileForm ModelForm. In my user_profile/views.py I have this profile_edit FBV: def profile_edit(request): if request.method == 'POST': form = ProfileForm(request.POST) if form.is_valid(): form.instance.user = request.user form.instance.save() return redirect('/profile/edit') else: form = ProfileForm(instance=request.user) print(request.user) print('hello get req here') context = { 'form': form, } return render(request, 'profile_edit.html', context) When I attempt to update profile information in profile_edit.html, the POST data will go through the first time, but not get saved to the DB. On a second attempt, I receive a UNIQUE constraint failed: user_profile_profile.user_id error. form.instance.save() is pointed to as the direct cause of the exception. In my estimation the error has something to do with the fact that upon creation of a new user, an initial unique ID is created for the user. So when I try to save() the Profile object, I think it is attempting to save() a new User, thereby … -
Is it safe to grant "auth | User | Can change user" permissions without the "is staff" flag?
I need certain users to edit django.contrib.auth.models.User objects. My first thought was to grant them the auth | User | Can change user permission and flag them as is staff, so they can log into the Django Admin site. The problem is though, that they can use that to make themselves super admins. Since I want them to only be able to edit certain fields, I created a very limited view for that. What's left for me to do, is to actually grant permission on that view to that subset of users. The only solution I found was to still grant them the auth | User | Can change user permission (without making them staff). My question is this: If I use the @permission_required decorator on that view in cooperation with the auth | User | Can change user permission, is there any other way for the users to hack their way into granting themselves the super admin role (even assuming the user is a advanced Django programmer)? I am talking about things like e. g. API calls I am unaware of, or similar. I want to take possible mistakes in my code out of the scope here. -
Как сказать Django Использовать python 3 (Хостинг Timeweb)
Использует по дефолту 2.7.6. Стоит virtualenv. Из командной строки доступны две версии, и 2, и 3.4. При запуске проекта : Python Executable: /usr/bin/python Python Version: 2.7.6 Пробовал в шапки файлов ставить #!/usr/bin/python3 Не помогает. -
Redirect to /admin/auth/user/ since my Django app
I'm looking for add a new reverse url in order to redirect to /admin/auth/user/ in my Django Admin page. In my template, I already have : href="{% url "admin:index" %}" line which let to overcome to the admin page. I would like to go directly to the users manage page and groups manage page respectively admin/auth/user/ and admin/auth/group. My urls.py file looks like : urlpatterns = [ url(r'^$', TemplateView.as_view(template_name=os.path.join(settings.BASE_DIR, 'Accueil/templates/Choice.html')), name='choice'), url(r'^admin/', admin.site.urls), url(r'^Identity/', include('Identity.urls')), url(r'^Accueil/', include('Accueil.urls')), url(r'^Home/', include('log.urls')), url(r'^Informations/', include('Informations.urls')), url(r'^Configurations/', include('Configurations.urls')), url(r'^__debug__/', include(debug_toolbar.urls)), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) How I can write href="{% url "admin:index" %}" in order to add user and group ? Up to now, I don't find a way to do that. Thank you by advance -
How can i render html page of Django after the background celery task is competed
Problems: i am using rabbitmq server with celery 1)I need to run multiple tasks in the background. That i am able to do 2) When each task is completed, i need to render the html page, to run html page i need request object as arguement, which celery task cant access 3) By the time celery task is completed i am out of the function that is having the request object from future import unicode_literals, absolute_import from django.shortcuts import render from celDemo.celery import app import time from django.http.response import HttpResponseRedirect # Create your views here. dictionary = {} msg = "Hello!" def testing(request): print 'In 1st page:' return render(request,'index.html') def testcelery(request): print 'In testcelery' if request.method == 'POST': print 'On click event' value = str(request.POST['variable']) print request dictionary[value] = request print dictionary[value] try: make_wait.delay(value) return render(request,'index.html') except: return render(request,'nothing.html') @app.task def make_wait(value): print dictionary print msg print 'Started sleeping :)' actual2() print 'Slept :D' #request = dictionary[value] print value print 'before initiaing the request' return render('nothing.html') print 'after initiating the request' #return value def actual2(): result = actual() return result def actual(): time.sleep(25) return 'slept :D' -
Django: How to recieve XML via url and put it in databse
everybody. This my first question: I have project on Django and don't know how to reciece xml via url and put body of this xml in some of my model. How best to do this? -
Django Modeltranslation: Integrating with legacy database
We have a legacy database with fields like: widget_name, widget_name_es, widget_name_de The main language is English and this is stored in widget_name. The other columns contain the respective translations. We're now building a read-only Django application (not using Django admin). Is there a way to use Django Modeltranslation without having to add a widget_name_en column which is a duplicate of widget_name? -
How to list tuples of variant lengths into tables in Django?
I hope anyone can help me. I query different tables (with different numbers of columns) in my MySQL db to get a preview of the first 100 rows. I want to display the values in a table. In views.py I have the following piece of code: cursor.execute("SELECT column_name FROM information_schema.columns WHERE table_name = '%s';" %table) columns = cursor.fetchall() columns_list = [i[0] for i in columns] cursor.execute("SELECT * FROM %s LIMIT 100;" %table) preview = cursor.fetchall() The code in my html template looks like this: <table> <tr> {% if columns_list %} {% for column in columns_list %} <th>{{column}}</th> {% endfor %} {% endif %} </tr> <tr> {% if preview %} {% for row in preview %} <td>{{ row.0 }}</td> <td>{{ row.1 }}</td> <td>{{ row.2 }}</td> <td>{{ row.3 }}</td> </tr> {% endfor %} {% endif %} </table> But this works only if my table has 4 columns. Is there an easier way to split the tuples and allocate them than using lots of for loops and arrays? Thanks for your help! -
Why Django server with Docker is running without database in postgresql?
I wonder why my server is running and why doesn't see another database. To wit psql and \l: List of databases Name | Owner | Encoding | Collate | Ctype | Access privileges -------------+-------------+----------+-------------+-------------+----------------------- aso | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | template0 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres template1 | postgres | UTF8 | en_US.UTF-8 | en_US.UTF-8 | =c/postgres + | | | | | postgres=CTc/postgres owner | owner | UTF8 | en_US.UTF-8 | en_US.UTF-8 | (4 rows) My Django settings: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } As you can see there is no database named postgres but server is running properly (save data etc.). On the other hand when I use: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'aso', 'USER': 'postgres', 'HOST': 'db', 'PORT': 5432, } } I get django.db.utils.OperationalError: FATAL: database "pri" does not exist Can anyone explain me this? -
How to automate a django functions when a certain condition is met by a django model's field
My problem is, how do I make a Django function run automatically when a certain condition is met by a Django model field. Google decided not to be collaborative on this. Say for example, I have the following model: class Check(models.Model): name = models.CharField(max_length=100, blank=True) interval = models.DurationField(default=td(hours=1)) last_run = models.DateTimeField(null=True, blank=True) def run_function(self): return HttpResponse("....") I have a model named Check which has fields for name, the intervals which I expect a function to be run and the last time the function was run. I need to call the function each time after the specific interval. What is the simplest way to write a function that will be called or will call another function after the interval passes? I am currently learning Django and I got stuck on this. -
login and authenticate in custom adapter
I am using custom adapter to register a user by using django rest auth, in my custom adapter i am validating the user registered data i need to login the user automatically if he already exist and registering second time.. i have used authenticate and login function: new_user = authenticate(username=username, password=password) login(self,new_user) i am getting server error(500), and the exception is AttributeError: 'AccountAdapter' object has no attribute 'session' so if i put self.request - account adpater object has no attribute request, how can i login the user if he try to register for second time. -
'NoneType' object has no attribute 'name' -Attribute Error
def user_recommendation_list(request): # get request user reviewed wines user_reviews = Review.objects.filter(user_name=request.user.username).prefetch_related('wine') user_reviews_wine_ids = set(map(lambda x: x.wine.id, user_reviews)) # get request user cluster name (just the first one righ now) user_cluster_name =User.objects.get(username=request.user.username).cluster_set.first().name Why it this error message showing? -
File upload by ajax with php and javascript
I would like to make file uploader on a web page by php and javascript. However I could not run php and save a file on the server. So I would like you to help me. How can I save the uploaded file on my linux system? My system is Linux (Ubuntu MATE) - Apache - Django. The code is following. file_upload.html <body> <center> <h3>Firmware Update</h3> <form id="my_form"> {% csrf_token %} <input type="file" name="file_1"> <button type="button" onclick="file_upload()">upload</button> </form> </center> <script type="text/javascript" src={% static "js/file_upload.js" %}></script> </body> file_upload.js function file_upload() { var formdata = new FormData($('#my_form').get(0)); $.ajax({ url : "/upload.php", type : "POST", data : formdata, cache : false, contentType : false, processData : false, dataType : "html" }) .done(function(data, textStatus, jqXHR){ alert(data); }) .fail(function(jqXHR, textStatus, errorThrown){ alert("fail"); }); } upload.php <?php $file_tmp = $_FILES["file_1"]["tmp_name"]; console.log($file_tmp) $file_save = "./" . $_FILES["file_1"]["name"]; $result = @move_uploaded_file($file_tmp, $file_save); if ( $result === true ) { echo "UPLOAD OK"; } else { echo "UPLOAD NG"; } When I run these code, the response is only showing the formdata (content of php) and php is not run. I think I can save a file at $file_save on Linux, but I cannot do. Please tell me the … -
Django model unique_together on primary key and unique constraints
I have a model given below. class mc(models.Model): ap=models.CharField(max_length=50,primary_key=True) de=models.CharField(max_length=50) STATUS=models.CharField(max_length=12,default='Y') class Meta: unique_together=(("ap","de"),) db_table='mc' I have written ap='1', de='2' to table mc. +----+----+--------+ | ap | de | STATUS | +----+----+--------+ | 1 | 2 | Y | +----+----+--------+ Then i have tried to write ap='1' and de='3' but its just overwritten the previous one. Now the table contains +----+----+--------+ | ap | de | STATUS | +----+----+--------+ | 1 | 3 | Y | +----+----+--------+ Then i tried to write ap='2',de='3' and its work. Since i have given unique_together, the compination of ap and de is not working. But unique_together work if i haven't used 'primary_key' or 'unique' constraints on either of ap or de. Will you please help me.? How to use unique_together on primary keys? -
:not all arguments converted during string formatting
My database have table webap_orifile, there is aptype, data_added, user, oriF in webap_orifile, wo wantro select oriF from webap-orfile WHERE user='11'order_by('date_added') but I write in django is oriFile.objects.raw('(select oriF from webap_orifile where user = username_id order_by(''date_added''))',[username_id]) So what's wrong? Is Anyone can Help me? -
UnicodeEncodeError [Python3/Gunicorn/Nginx/Django]
I didn't have any problem when I set my environment with mod_wsgi and Apache2. I just had to add "export LANG='en_US.UTF-8' export LC_ALL='en_US.UTF-8'" in /etc/apache2/envars path to upload file with non-ASCII filename. This time, I set my env with Nginx and Gunicorn. But It occurs UnicodeEncoderError in every part where shows non-ASCII characters. 'ascii' codec can't encode characters in position 57-59: ordinal not in range(128) I don't understand why 'ascii' codec is used to encode in Python3 and Django environment. I searched and searched and searched. I checked and tried like below. PostgreSQL check : Encoding UTF8 Django default encoding : utf-8 Ubuntu locale check : en_US.UTF-8 (I also tried 'ko_KR.UTF-8', because it has an error with Korean) checked python 3 sys.getdefaultencoding, sys.stdout.encoding, sys.stdin.encoding : utf-8 adding charset utf-8; in /etc/nginx/sites-available/myproject checked if Gunicorn call python2 instead of python3 : installing gunicorn with pip3 virtualenv and checked '#!/home/username/venv/bin/python3' in gunicorn file. write import sys reload(sys) sys.setdefaultencoding('utf-8') in views.py : I understood it can apply to python2 and it is not recommended way. I was suspicous that Gunicorn call python2 instead of python3 because python2 is also installed in my Ubuntu. If I check python -c 'import sys; print(sys.getdefaultencoding());', I can … -
How to maintain the oauth session object between requests with django?
I am using the Requests-Oauthlib1 workflow to authenticate on a site with oauth 1 from django. I think I am not using the one obvious way to do it. The way I have implemented it: /oauth - Gets the request token and returns the oauth authorization url def oauth(request): oauth_service = Oauth_service() key, secret = oauth_service.obtain_request_token() message = oauth_service.get_authorization_url() return HttpResponse(message) /oauthcomplete - oauth success redirects here, but I am now creating a new instance of the Oath_Service which won't have the request token and secret def oauth_complete(request): oauth_service = Oauth_service() verifier = oauth_service.get_verifier(request.build_absolute_uri()) return HttpResponse("Verified with {}".format(verifier)) oauth_service.py class Oauth_service: ''' Class used to commuicate with an Oauth magento ''' BASE_URL = 'https://xxx' RETRIEVE_REQUEST_TOKEN_PATH = '/oauth/initiate' ADMIN_AUTHORIZATION_PATH = '/admin/oauth_authorize' RETRIEVE_ACCESS_TOKEN_PATH = '/oauth/token' OAUTH_CONSUMER_KEY = 'xxx' OAUTH_SECRET_KEY = 'xxx' OAUTH_SIGNATURE_METHOD = 'HMAC-SHA1' CALLBACK_URL = 'http://127.0.0.1:8000/models/oauth_complete' oauth = OAuth1Session( OAUTH_CONSUMER_KEY, client_secret=OAUTH_SECRET_KEY, callback_uri=CALLBACK_URL, ) resource_owner_key = '' resource_owner_secret = '' verifier = '' def obtain_request_token(self): ''' step 1 in oauth process ''' request_token_url = self.BASE_URL + self.RETRIEVE_REQUEST_TOKEN_PATH headers = { 'Accept': 'application/json' } fetch_response = self.oauth.fetch_request_token(request_token_url, verify=False, headers=headers) self.resource_owner_key = fetch_response.get('oauth_token') self.resource_owner_secret = fetch_response.get('oauth_token_secret') return self.resource_owner_key, self.resource_owner_secret def get_authorization_url(self): base_authorization_url = self.BASE_URL + self.ADMIN_AUTHORIZATION_PATH authorization_url = self.oauth.authorization_url(base_authorization_url) return 'Please go here and … -
MutlivalueDickeyerror django
<div class="ui container billtb"> <table class="ui celled striped fixed table"> <thead> <tr> <th>Patient Id</th> <th>Patient Name</th> <th>Medicines/Prescription</th> <th>Billing</th> </tr> </thead> <tbody> {% for n in medrec %} <tr> <td>{{ n.patient.pk }}</td> <td>{{ n.patient.name }}</td> <td> <div class="ui grid"> <form class="ui form" id="mform{{ n.id }}" action="/mbill/" method="post"> {% csrf_token %} <input value="{{ n.pk }}" type="hidden" name="pk"> {% for m in n.med_set.all %} <div class="row"> <div class="eight wide column">{{ m.medicine.name }}</div> <div class="eight wide column"> <div class="field"><input name="{{ m.stockpk }}" type="text"></div> <h5>{{ m.medicine.quantity }} left</h5> </div> </div> {% endfor %} </form> </div> </td> <td class="right aligned"> <button type="submit" class="ui button green" form="mform{{ n.id }}" >bill</button> </td> </tr> {% endfor %} </tbody> </table> </div> view def gbill(request): if request.POST: pk=request.POST['pk'] medrecord = MedicalRec.objects.get(pk=pk) medicines = Medicine.objects.filter(medicalrec=medrecord) for m in medicines: qty = request.POST[str(m.stockpk)] item = Stock.objects.get(m.medicine) item.quantity = item.quantity - int(qty) item.save() return redirect('/billing') models class Patient(models.Model): name = models.CharField(max_length=100) age = models.IntegerField() address = models.TextField() contact = models.CharField(max_length=15) def __str__(self): return self.name class Stock(models.Model): name = models.CharField(max_length=100) quantity = models.IntegerField() expiry = models.DateField() price = models.IntegerField() def __str__(self): return self.name class MedicalRec(models.Model): patient = models.ForeignKey(Patient) date = models.DateField() disease = models.TextField() treatment = models.TextField() billed = models.BooleanField() def __str__(self): return str(self.date) + …