Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User email from GitHub in django social login
I followed this article to get social login in my django application. It is working well, but for github users I can't get user email, even when I add SOCIAL_AUTH_GITHUB_SCOPE = ['email'] What should I change in the article example to get user email? -
Django Rest DRF - Post method using generic class based views (CreateAPIView) when there is a foreign key relation
I currently have the following structure in my DRF api. models.py class Location(models.Model): name = models.CharField(max_length=64, unique=True) district = models.CharField(max_length=64, blank=True) division = models.CharField(max_length=64, blank=True) latitude = models.DecimalField(max_digits=9, decimal_places=3, blank=True) longitude = models.DecimalField(max_digits=9, decimal_places=3, blank=True) class Event(models.Model): title = models.CharField(max_length=64) location = models.ForeignKey(Location, on_delete=models.CASCADE, blank=False, null=False) type = models.CharField(max_length=64, blank=True) max_quota = models.IntegerField(blank=True) min_cost = models.IntegerField(blank=True) duration_start = models.CharField(max_length=64, blank=True) duration_end = models.CharField(max_length=64, blank=True) serializers.py class LocationSerializer(serializers.ModelSerializer): class Meta: model = Location fields = [ 'name', 'district', 'division', 'latitude', 'longitude', ] class ExperienceCreateSerializer(serializers.ModelSerializer): location = LocationSerializer(many=False) #location_id = serializers.PrimaryKeyRelatedField(read_only=True) class Meta: model = Experience fields = [ 'title', 'type', 'max_quota', 'min_cost', 'duration_start', 'duration_end', 'location', ] views.py class ExperienceCreate(generics.CreateAPIView): queryset = Experience.objects.all() serializer_class = ExperienceCreateSerializer Now, I have tried a lot of things and the only solution that made sense was to override the create() method. But, nothing whatsoever has worked. I don't understand exactly where I am going wrong. -
Django-admin won't allow me to modify user permissions and groups
When editing user model through admin interface, here's what I see: And here's what I expect to see: The second one allows me to modify the user permissions, the first one does not. The User model I use on the first screenshot inherits from AbstractUser and is registered in the following way: from django.contrib import admin import accounts.models admin.site.register(accounts.models.User) In my settings: DEBUG = True AUTH_USER_MODEL = 'accounts.User' What can be the problem? How do I get from the first screenshot to the second? -
Django Crispy forms : Save data in the form of key value pair
the requirement is to create a form as displayed in image and save the labels as key and user input as value. As I am new to Django, can anyone guide me on this. Here's some code :- Model: class Setting(models.Model): id = models.AutoField(primary_key=True) project = models.ForeignKey(Project) type = models.CharField(max_length=4, default=SYS) k = models.CharField(max_length=DEFAULT_DESC_FIELD_LEN, blank=False, null=False) v = models.TextField(blank=True, null=True) help = models.TextField(blank=True, null=True) history = HistoricalRecords(table_name='Setting_Hist') and created a settings_const.py: CODES_REVIEW_NEW = 'CODES_REVIEW_NEW' CODE_SELECTION_REVIEW_NEW = 'CODE_SELECTION_REVIEW_NEW' CODE_SELECTION_REVIEW_VERIFY = 'CODE_SELECTION_REVIEW_VERIFY' DEFAULT_CODE_REVIEW_NEW = 'DEFAULT_CODE_REVIEW_NEW' CODE_MARK_VERIFIED = 'CODE_MARK_VERIFIED' CODES_HIGHLIGHTED = 'CODES_HIGHLIGHTED' Any kind of help will be appreciated. Thanks in advance!! -
Cron job in google cloud is showing status failed
I am currently working in Google clouds and i have deployed my python application in Google app engine. now i want to schedule tasks in it. i have read it. Google clouds is doing this through cron jobs. i have written a very basic cron and trying to run it. but every time it failing. can anyone please tell me what is going wrong. here is my app.yaml handlers: - url: /laptop/ script: file.py login: admin and my cron.yaml file is cron: - description: daily summary job url: /laptop target: beta schedule: every 24 hours my file which i want to run is in myproject/laptop/file.py and my file.py is only printing my name (just for testing purpose) print "Amad"; print "testing" can anybody tell me, how can i run this file on Google app engine. when i run this cron on task queues it gives me error like this. please refer me some tutorial where i can successfully run it. i have waste a lot of my time on it. Any help or suggestions are highly appreciated. -
What is the need for super() in overriding TestCase.setUpClass() [duplicate]
This question already has an answer here: What does 'super' do in Python? 5 answers I am overriding setUpClass() of TestCase as per django documentation. class Health_showhome(TestCase): @classmethod ##setUpClass must be called with instance of Health_showhome() def setUpClass(cls): super(Health_showhome, cls).setUpClass() db = MySQLdb.connect(host="localhost",user="root",passwd="mcvishu007") cls.cursor = db.cursor() query = 'CREATE DATABASE IF NOT EXISTS testxxx;' cls.cursor.execute(query) query = 'USE testxxx;' cls.cursor.execute(query) @classmethod def tearDownClass(cls): query = 'DROP DATABASE testxxx;' print "teardown" cls.cursor.execute(query) cls.cursor.close() The method creates database without super() function. So i am confused with the use of super() function.super(Health_showhome, cls).setUpClass() is actually as TestCase.setUpClass(), isn't it? What is the use of super() function ? How they works? -
Django manipulate model fields programatically
I want to use the following base model to allow our team to add a unique_reference field to various models where required, using custom attributes (namely prefix, length and the field_name of the field). is there a clean and agreeable way to achieve what I am looking for with Django? class UniqueFieldModel(models.Model): class Meta: abstract = True def __init__(self, *args, **kwargs): self.prefix = getattr(self.Meta, 'unique_reference_prefix') self.unique_ref_length = getattr(self.Meta, 'unique_reference_field_name', settings.UNIQUE_REFERENCE_MAX_LENGTH) unique_ref_field_name = getattr(self.Meta, 'unique_reference_field_name') unique_reference_field = models.CharField( max_length=self.unique_ref_length, blank=False, null=False ) setattr(self, unique_ref_field_name, unique_reference_field) super(UniqueFieldModel, self).__init__(*args, **kwargs) def save(self, *args, **kwargs): if not self.unique_reference: prefix = getattr(self.Meta, 'unique_reference_prefix') self.unique_reference = \ self.gen_unique_value( prefix, lambda x: get_random_string(x), lambda x: self.objects.filter(unique_reference=x).count(), self.unique_ref_length ).upper() I would say that one possible way would be to normalise the name of the unique_reference field over all models. But it is suboptimal, as it will require a lot of refactoring, and will be semantically incorrect in some cases. -
Running python script from django view with parameters
I want to call a python script with paramters from django view. The python script is stored in a subfolder (see attached picture). Basically I have an input form and want to call crawl.py with the input data from that form. The form data should be stored in variable "production_number" in crawl.py. view.py def newOrders(request): if request.method == 'POST': form = CustomerForm(request.POST) if form.is_valid(): formdata = form.cleaned_data['product_ID'] # call crawl.py with paramter formdata return HttpResponseRedirect('/customer/newOrders') crawl.py import db import sys import requests import json from datetime import datetime def query(resource): r = requests.get('http://11.111.11.11:8080/webapp/api/v1/' + resource, headers={'AuthenticationToken': '11111-11111-1111-1111-11111'} ) return r costumer_id = 1 production_number = formdata d = query('productionOrder/?productionOrderNumber-eq={}'.format(production_number)).json() session = db.Session() costumer = session.query(db.Costumer).get(costumer_id) if 'result' in d and len(d['result']) > 0: r = d['result'][0] order = db.Order() try: order.article_id = r['articleId'] order.amount = r['targetQuantity'] order.create_date = datetime.fromtimestamp(r['createdDate'] / 1000) order.start_date = datetime.fromtimestamp(r['targetStartDate'] / 1000) order.end_date = datetime.fromtimestamp(r['targetEndDate'] / 1000) except NameError as e: sys.exit('Error {}'.format(e.what())) article_number = r['articleNumber'] d = query('article/?articleNumber-eq={}'.format(article_number)).json() if 'result' in d and len(d['result']) > 0: r = d['result'][0] article_image_id = r['articleImages'][0]['id'] order.price_offer = r['articlePrices'][0]['price'] r = query('article/id/{}/downloadArticleImage?articleImageId={}'.format(order.article_id, article_image_id)) order.article_image = r.content else: print('No result for article with number', article_number) costumer.orders.append(order) session.add(costumer) session.commit() else: print('No … -
Attempting to write readonly database Django + Gunicorn + nginx + sqlite3
The problem may sound trivial at first. My server runs on nginx and gunicorn. Django 1.11.4, db: sqlite3. The problem is raised when I try to enter as an admin to my fresh new project with almost no data. Right after I log in the OperationalError is raised and says 'attempt to write a readonly database". I have surfed the internet and the solutions below don't work in my case: chmod to 777 the DB (raises "can't open file" issue. FullPath doesn't work as well) chown to a+w The whole project runs on "supervisor" and, unfortunately, I coulnd't find the solution to this problem My supervisor file [program:majorpack] command=/usr/local/bin/gunicorn project.wsgi:application -c /var/www/django/project/project/project/gunicorn.conf.py directory=/var/www/django/project/project user=nobody autorestart=true redirect_stderr=true Gunicorn.conf.py bind = '127.0.0.1:8000' workers = 3 user = "nobody" nginx default file server { listen 80; server_name 111.222.333.44; #либо ip, либо доменное имя access_log /var/log/nginx/example.log; location /static/ { root /opt/myenv/myproject/; expires 30d; } location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $server_name; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } And the ls -lp log drwxr-xr-x 7 root root 4096 Aug 23 09:49 ./ drwxrwxr-x 3 django django 4096 Aug 23 00:17 ../ drwxr-xr-x 5 www-data www-data 4096 Aug 23 09:35 client/ -rw-r-xr-x 1 … -
Django Dropbox storage
i am trying to use django-storages with dropbox. I did everything like in docs: set DEFAULT_FILE_STORAGE = 'storages.backends.dropbox.DropBoxStorage', DROPBOX_OAUTH2_TOKEN = 'MY_ACCESS_TOKEN' DROPBOX_ROOT_PATH = 'media' But when I'm trying to upload images on heroku, i got an error in logs: TypeError: expected request_binary as binary type, got class'django.core.files.uploadedfile.InMemoryUploadedFile' -
make div side by side in django simple template?
i am learning django and i want to know how to put div that is in for loop side by side i know how without for loop but here i just have on div that the for loop will do it more than one time: ` {% for albums in all_albums %} <div id="album" class="some-class" style="background-image: url({{ albums.album_logo }})"> {% if albums.is_favorite %} <img src="http://icons.iconarchive.com/icons/oxygen-icons.org/oxygen/16/Actions-rating-icon.png" > {% endif %} </div> <a href="{% url 'detail' albums.id%}"><h3>{{ albums.title }}</h3></a> <p>{{ albums.song_set.count }} songs inside</p><br> {% endfor %}` -
How to get right url
I write a django page . example: i has a menu as below: <ul class="menu"> <li class="nav-current" role="presentation"><a href="">index</a></li> <li role="presentation"><a href="/cpuinfo/">cpu info</a></li> <li role="presentation"><a href="#">about</a></li> </ul> example: when i in home page cpuinfo url like : /cpuinfo but when i in other page like /post/ i click cpu info url jump to /post/cpuinfo , how can i set it on post page also can jump to /cpuinfo ? -
Setup django/python with Jenkins
I currently configure Jenkins for my python/django application (i'm using python 3.5) During the setup I open a Virtualenv and I activate it. virtualenv -q wecover_platform . ./wecover_platform/bin/activate Then i install all my requirements from my file requirement.txt pip install -r $WORKSPACE/requirements.txt I can't pass this step i always have a permission denied issue. Installing collected packages: asn1crypto, pycparser, cffi, idna, cryptography, pyOpenSSL, olefile, pillow, reportlab, selenium, django-jenkins Exception: Traceback (most recent call last): File "/usr/local/lib/python3.5/dist-packages/pip/basecommand.py", line 215, in main status = self.run(options, args) File "/usr/local/lib/python3.5/dist-packages/pip/commands/install.py", line 342, in run prefix=options.prefix_path, File "/usr/local/lib/python3.5/dist-packages/pip/req/req_set.py", line 784, in install **kwargs File "/usr/local/lib/python3.5/dist-packages/pip/req/req_install.py", line 851, in install self.move_wheel_files(self.source_dir, root=root, prefix=prefix) File "/usr/local/lib/python3.5/dist-packages/pip/req/req_install.py", line 1064, in move_wheel_files isolated=self.isolated, File "/usr/local/lib/python3.5/dist-packages/pip/wheel.py", line 345, in move_wheel_files clobber(source, lib_dir, True) File "/usr/local/lib/python3.5/dist-packages/pip/wheel.py", line 316, in clobber ensure_dir(destdir) File "/usr/local/lib/python3.5/dist-packages/pip/utils/__init__.py", line 83, in ensure_dir os.makedirs(path) File "/usr/lib/python3.5/os.py", line 241, in makedirs mkdir(name, mode) PermissionError: [Errno 13] Permission denied: '/usr/local/lib/python3.5/dist-packages/asn1crypto' Build step 'Execute shell' marked build as failure Finished: FAILURE If somebody could help me I would really appreciate it! -
MS SQL server datetime field shows UTC timestamp
I am new to MS SQL and I am running a Django application on a windows server I have set the TIME_ZONE to my local time zone in the settings.py and in the django admin the time is shown according to the local time zone but in the SQL db the time stamp seems to show the date time format in UTC. I tried searching how to change the timezone of SQL Server but I don't find any answer on that regard any help would be appreciated -
The format for date objects may not contain time-related format specifiers (found 'H')
Learning Django and can't solve this problem... Confused by the error message : In template /Users/hangsu/Desktop/learning_log/learning_logs/templates/learning_logs/base.html, error at line 0 googled the bug and got no similar problems. Please let me know if you know possible solution, thx! -
How to customize Mapzen search control using my own html/css?
How can I customize an L.Mapzen.geocoder to take my own HTML/CSS styled search box that is positioned at the center (just like the one in Mapzen Demo)? <div id="form-wrapper"> <form class="form-horizontal"> <div class="col-lg-offset-3 col-lg-6"> <div class="input-group"> <input type="text" class="form-control input-sm"> <span class="input-group-btn"> <button class="btn btn-default btn-sm" type="submit"><span class="glyphicon glyphicon-search"></span></button> </span> </input> </div> </div> </form> </div> I wanted to let it stay at the center as the map adjusts to the location as its background. Its basic use is to let the users check if the location they chose is correct and after another button click their input will be redirected to another python django view. -
Django MySQL database design
I'm trying to optimize the MySQL DB on a Django app that provides search results for items for users to buy. It has been recommended to me that one option was to vertically split my Items table into multiple tables. After some thought, I've realized I'm using the table for three separate purposes: Query rows for results relevant to some search term. Display paginated results that are relevant to the search term. Direct a user to any external pages they click. So as far as I can tell, my best option is to split the table according to these needs (Is this a correct assumption?). At the moment my model looks like this: class Items(models.Model): categories = models.CharField(max_length=64) title = models.CharField(max_length=128) description = models.CharField(max_length=1024) thumb = models.CharField(max_length=255, unique=True) vendor = models.CharField(max_length=16) url = models.CharField(max_length=255, unique=True) After a horizontal split, the tables would look something like this: # Query all fields in this table for the search term class ItemSearch(models.Model): categories = models.CharField(max_length=64) title = models.CharField(max_length=128) description = models.CharField(max_length=1024) # Once a set of relevant results has been compiled, query this table to get all information needed to display it on the page. class ItemDisplay(models.Model): title = models.CharField(max_length=128) thumb = models.CharField(max_length=255, … -
Django merge 2 querysets in staggered/alternating fashion without duplicates?
Follow up question to this one: Django merge 2 querysets in staggered/alternating fashion? I'm wondering is there an efficient way to avoid duplicates in the result? i.e. the generators will only return items we have not seen before. -
Prevent DateRangeField overlap in Django model?
Now that Django supports the DateRangeField, is there a 'Pythonic' way to prevent records from having overlapping date ranges? Hypothetical use case One hypothetical use case would be a booking system, where you don't want people to book the same resource at the same time. Hypothetical example code class Booking(models.model): # The resource to be reserved resource = models.ForeignKey('Resource') # When to reserve the resource date_range = models.DateRangeField() class Meta: unique_together = ('resource', 'date_range',) -
How to create custom relation table for ForeignKey or OnetoOne field?
What I want to do is create a model than can be used to store data about a relation between two elements. With ManytoMany fields, I can use the parameter "through" and specify a model which stores two elements foreign keys as below. def MyModel(models.Model): relation = models.ManyToManyField('AnotherModel', through='RelationModel') def RelationModel(models.Model): model1 = models.ForeignKey('MyModel') model2 = models.ForeignKey('AnotherModel') slug = models.CharField() What would be the equivalent for a OnetoOne relation or a ForeignKey relation ? I've read the docs about custom managers and some posts on SO so in the end I'm quite confused and I dont know what is the solution. Thanks in advance for any help. -
Django pluggable app to maintain master database models
I want to have a django pluggable app which contains all the models for my master database (Postgres). It should handle all the communication with the database (connect, read, write.. etc) Any project which uses this app should be able to use the underlying models and hence access the database. How do I achieve this? -
Detecting Client Aborting XHR on Django Server
I have a server which dispatches some long running jobs when a client spawns a request. Since these jobs are long running and particularly resource heavy, I want a way to kill the processes related to the client's request on the server side when the client aborts their XHR. Another important thing to note is that all these long computations are done within this one user request (eventually I'd like to move to a polling system involving Celery, but that's for the future). I'm using JQuery's AJAX extension, and I have a button on my frontend which aborts the AJAX request when clicked. This button just calls xhrJQ.abort(). As far as I can tell, the only potentially observable xhrJQ.abort() does is close the socket the client is listening on, though I'm not certain this is even true. I'm using Django, so I can get the address and port the client is requesting from through the HTTPRequest object Django passes. But I'm not sure 1) whether my assumption about xhrJQ.abort closing the socket is true 2) if it is true how to detect a client's closing a socket. I've looked around quite a bit and haven't been able to find a … -
I can not use the django's session in my project
When I login, I want to store the username in the session. But when I set session in my views.py, but get the below error: Internal Server Error: /cookie/login1/ Traceback (most recent call last): File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/utils/deprecation.py", line 142, in __call__ response = self.process_response(request, response) File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/contrib/sessions/middleware.py", line 58, in process_response request.session.save() File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/contrib/sessions/backends/db.py", line 81, in save return self.create() File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/contrib/sessions/backends/db.py", line 50, in create self._session_key = self._get_new_session_key() File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/contrib/sessions/backends/base.py", line 164, in _get_new_session_key if not self.exists(session_key): File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/contrib/sessions/backends/db.py", line 46, in exists return self.model.objects.filter(session_key=session_key).exists() File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/db/models/query.py", line 670, in exists return self.query.has_results(using=self.db) File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/db/models/sql/query.py", line 517, in has_results return compiler.has_results() File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/db/models/sql/compiler.py", line 845, in has_results return bool(self.execute_sql(SINGLE)) File "/Library/Python/2.7/site-packages/Django-1.11.2-py2.7.egg/django/db/models/sql/compiler.py", line 886, in execute_sql raise original_exception OperationalError: no such table: django_session I tested my code, did not find the reason. In the urls.py: urlpatterns = [ ... url(r'^login1/$', views.login1), url(r'^index1/$', views.index1), ] In the views.py, I have two method, if login1 success, I will redirect to index1.html: def login1(request): if request.method == 'GET': return render(request, 'cookie/login1.html') elif request.method == 'POST': username = request.POST.get('username') pwd = request.POST.get('pwd') print ('username:'+username, 'pwd:'+pwd) if username == 'root' and pwd == '123': request.session['username'] = username … -
Rest Framework Django - Disable field to accept null values
Rest Framework Django - Disable field to accept null values How can I configure for the serialized Model to accept blank fields? Warning {Operacao: ["This field can not be blank."]} Model class SEF(models.Model): operacao = models.CharField(max_length=10, null=True) documento = models.CharField(max_length=50, null=True) user = models.ForeignKey(User) Serializer class SEFCreateSerializer(serializers.ModelSerializer): class Meta: model = SEF fields = ('operacao', 'documento', 'user') View sef_create = SEFCreateSerializer(data=data, many=True) if sef_create.is_valid(): sef_create.save() salvo = HTTP_200_OK else: salvo = sef_create.errors -
Display file delete option before posting the attachments
I can post multiple attachment files well, used below form field to select multiple files at once. my_attachments = forms.FileField( widget=forms.ClearableFileInput(attrs={'multiple': True}), required=False ) But there is no option to remove some files selected before posting the form. How can we display selected files along with a delete link? On clicking the link, it should remove the file from posting?