Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to substitute template variable using additional context passed to the template
Django 1.11.2 I have: <div id="empty_keeper_and_form" style="display:none"> <p class='no_error'> {{ keeper_and_form_set.empty_form.as_p }} </p> </div> <div id="empty_keeper_or_form" style="display:none"> <p class='no_error'> {{ keeper_or_form_set.empty_form.as_p }} </p> </div> And I'd like to make an inclusion template to use like this: {% include "operation.html" with operation='and'%} And this is what I did: <div id="empty_keeper_{{ operation }}_form" style="display:none"> <p class='no_error'> {{ keeper_and_form_set.empty_form.as_p }} </p> </div> Well, the problem is that I failed to modify that keeper_and_form_set. Could you help me? -
Admin inline with no ForeignKey relation
Is it possible to manually specify the set of related object to show in an inline, where no foreign key relation exists? # Parent class Diary(models.Model): day = models.DateField() # Child class Sleep(models.Model): start_time = models.DateTimeField() end_time = models.DateTimeField() class SleepInline(admin.TabularInline): model=Sleep def get_queryset(self, request): # Return all Sleep objects where start_time matches Diary.day return Sleep.objects.filter(XXX) class DiaryAdmin(admin.ModelAdmin): inlines = (SleepInline, ) I want my Diary model admin to display an inline for Sleep models that have start_time equal to the same day as Diary.day. The problem is that the Sleep model does not have a ForeignKey to Diary (instead, the relation is implicit by the use of dates). Using the above, Django immediately complains that <class 'records.admin.SleepInline'>: (admin.E202) 'records.Sleep' has no ForeignKey to 'records.Diary'. How can I show the relevant Sleep instances as inlines on the Diary admin page? -
Download files from SFTP server into django server
I need to create an app in django that downloads files from an SFTP server. For this I have come across django-storages. There is no clear mention how to set up SFTP settings for django-storages in settings.py. django-storages:SFTP Any suggestions? -
Django Rest Framework/Rest Auth not authenticating user on mobile Chrome
I recently upgraded my Django to 1.11.2, my rest-framework to 3.6.3 and the rest-auth to 0.6 it worked fine until I checked out the mobile version via Chrome. The logged in user is always Anonymous, i don't know why. Don't understand what happend. Before (on Django 1.8 and rest on 3.3 and auth on 0.5) it worked fine everywhere, the settings remained unchanged: REST_SESSION_LOGIN = False REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( #'rest_framework_expiring_authtoken.authentication.ExpiringTokenAuthentication', 'rest_framework.authentication.BasicAuthentication', 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_THROTTLE_CLASSES': ( 'rest_framework.throttling.AnonRateThrottle', 'rest_framework.throttling.UserRateThrottle' ), 'DEFAULT_THROTTLE_RATES': { 'anon': '100/day', 'user': '1000/day' } } What is really weird is that django itself authenticates the user, just the ApiView doesn't, so I can not send information about the user to components in brwoser ... Any ideas why this happens? -
Django - processing model data before saving
I have a django model. I need to get username and password. But at that time I want to process them by vk() class to get uid, token, secret and save model with fields from vk() class only. How can I do it? from django.db import models from vk_class import vk class data(models.Model): # that's what I ask for username = models.CharField(max_length=50) password = models.CharField(max_length=50) # that's only what I want to save uid = vk(username=username, password=password).uid token = vk(username=username, password=password).token secret = vk(username=username, password=password).secret -
Salesforce Sandbox API Oauth2 Callback URL over localhost Django
Newbie working on a Salesforce project for a job interview. I'm trying to build a Django form that will submit a case ticket to the Salesforce backend. Using django-salesforce django-salesforcelibrary, and I'm at the point where I'm creating the a new connected app. How do I deal with the callback URL if I'm testing on localhost? The callback url needs to be an https secure connection. Can I just set the callback as http://localhost:8000? Having a hard time figuring it out and on a strict time limit so no time to learn the salesforce API. -
Wagtail Page Privacy 'Private, accessible to users in specific groups' as SAAS separation
Scenario: A User registers to my Wagtail site. This creates a Group, and a Page. This page wil be set Private 'Private, accessible to users in specific groups' The just created group will be set. The user invites people to the group, and shares pages as childpages of the just created root-page, so only group members can acces it. Would this scale? For like, hopefully, thousands of groups? Is this a way to separate content for a SAAS setup? -
Django FilteredSelectMultiple not rendering on page
I am currently using Django version 1.11.2 and would like to use the FilteredSelectMultiple widget outside of the admin page. This is my forms.py: class TBDAuthGroupManageForm(forms.Form): permissions = forms.ModelMultipleChoiceField(queryset=Permission.objects.all(), required=True, widget=FilteredSelectMultiple("Permissions", is_stacked=False)) class Media: css = {'all': ('/static/admin/css/widgets.css',), } js = ('/admin/jsi18n/',) def __init__(self, parents=None, *args, **kwargs): super(TBDAuthGroupManageForm, self).__init__(*args, **kwargs) This is my views.py: class TBDAuthGroupManageView(DetailView): model = TBDAuthGroup template_name = 'perms/tbdauthgroup_manage.html' def get_context_data(self, **kwargs): context = super(TBDAuthGroupManageView, self).get_context_data(**kwargs) context['form'] = TBDAuthGroupManageForm() return context And this is my template: {% extends "base.html" %} {% load static %} {% block css %} {{ form.media }} <script type="text/javascript" src="{% static 'js/jquery-3.1.1.min.js' %}"></script> <script type="text/javascript" src="/static/admin/js/jquery.min.js"></script> <script type="text/javascript" src="/static/admin/js/jquery.init.js"></script> {% endblock %} {% block content %} {{ form }} {% endblock %} However when I render it in the page, I only get this: and not this: I would love to know what I'm doing wrong and how I could fix this so my form looks like the admin form. -
request.user always returns AnonymousUser - Django
I have an app authy_me and wrote a custom URL url(r'^login/$', authy_views.log_me_in, name="login") the log_me_in view has the following: from django.contrib.auth.forms import AuthenticationForm from django.contrib.auth.views import login as auth_login def log_me_in(request): if request.user.is_staff and not has_2fa(request): logger.info('is staff but does not have 2FA, redirecting to Authy account creator') return redirect('admin/authy_me/authenticatormodel/') elif request.user.is_staff and has_2fa(request): logger.info("is staff and 2FA enabled redirecting to Authy verification") return redirect('2fa') elif not request.user.is_staff and not has_2fa(request): logger.info('is not staff and does not have 2FA') defaults = { 'authentication_form': AuthenticationForm, 'template_name': 'login.html', } return auth_login(request, **defaults) When I print request.user I get it as AnonymousUser but the thing is that it was working and I did not change anything! I am not sure what the problem is. Help!! -
Selectively deleting images uploaded to Azure blob (Django/Python project)
In a Django (Python) project, I'm using Azure blobs to store photos uploaded by users. The code simply goes something like this: from azure.storage.blob import BlobService blob_service = BlobService(account_name=accountName, account_key=accountKey) blob_service.put_blob( 'pictures', name, # including folder content_str, # image as stream x_ms_blob_type='BlockBlob', x_ms_blob_content_type=content_type, x_ms_blob_cache_control ='public, max-age=3600, s-maxage=86400' ) My question is: what's the equivalent method to delete an uploaded photo in my particular scenario? I'm writing a task to periodically clean up mydata models, and so want to get rid of images associated to them as well. -
Designing the best schema to a relation of Users with two parent/child tables
I am creating a school project app and I have a database design doubt. We must be aiming for high scalability. The app will have the following tables: Users, ReportFiles and Reports. A ReportFile can have multiple Reports or none, and a Report can be owned by one or none ReportFiles. A Report that has no ReportFiles could be later on grouped into a new or existing ReportFile. One ReportFile or Report will relate to multiple Users. The main screen will be showing a list of ReportFiles and Files that are not from a ReportFile. If a Report has a ReportFile it is not going to be shown, because its ReportFile already is. Common fields between ReportFiles and Reports are: name, date, creationDate, description, category. And all of those are shown in the list. The sort order will be by creation date, therefore the list will be a mixture of ReportFiles with Reports. My doubt is in how to design the database schema to populate this feed. I am considering two scenarios. 1) If a Report doesn't have a ReportFile, it will be assigned a 'ghost' ReportFile to it. There will be a boolean hasReportFile in Report or isReportFile in … -
Django - 'sqlclear' equivalent in Django > 1.9
In Django 1.10.6, I made a model, and ran python manage.py makemigrations and python manage.py migrate, it created a table in MySQL DB. Later I came to know that the table was not required. I searched and found an answer here. But that was for the versions before 1.9. In Django 1.9 sqlclear has been removed. Now my doubt is, how can I drop a table from the DB using Django, for versions greater than 1.9? Is there any sqlclear equivalent in versions greater than 1.9? Kindly help. -
Redirect custom AuthenticationForm once authenticated - Django
Is it possible to redirect a user once they pass through the confirm_login_allowed of AuthenticationForm. For example, I was trying to redirect the user in the forms by doing class LoginForm(AuthenticationForm): def confirm_login_allowed(self, user): if not user.is_active: raise forms.ValidationError('There was a problem with your login.', code='invalid_login') elif user.is_staff and not self.has_2fa(): logger.info('is staff but does not have 2FA, redirecting to Authy account creator') return redirect('admin/authy_me/authenticatormodel/') elif user.is_staff and self.has_2fa(): logger.info("is staff and 2FA enabled") elif not user.is_staff and not self.has_2fa(): logger.info('is not staff and does not have 2FA') or is confirm_login_allowed used only for validation error? if so is there any other way? -
Django migrate hang shell
I had a strange problem. When I migrate or makemigrations,command run well,but not exit shell. Like this: root@10-19-177-216:/data/mini# ./manage.py migrate Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions, user Running migrations: Applying contenttypes.0001_initial... OK Applying auth.0001_initial... OK Applying admin.0001_initial... OK Applying admin.0002_logentry_remove_auto_add... OK Applying contenttypes.0002_remove_content_type_name... OK Applying auth.0002_alter_permission_name_max_length... OK Applying auth.0003_alter_user_email_max_length... OK Applying auth.0004_alter_user_username_opts... OK Applying auth.0005_alter_user_last_login_null... OK Applying auth.0006_require_contenttypes_0002... OK Applying auth.0007_alter_validators_add_error_messages... OK Applying auth.0008_alter_user_username_max_length... OK Applying sessions.0001_initial... OK Applying user.0001_initial... OK ^CException ignored in: <module 'threading' from '/usr/lib/python3.4/threading.py'> Traceback (most recent call last): File "/usr/lib/python3.4/threading.py", line 1294, in _shutdown t.join() File "/usr/lib/python3.4/threading.py", line 1060, in join self._wait_for_tstate_lock() File "/usr/lib/python3.4/threading.py", line 1076, in _wait_for_tstate_lock elif lock.acquire(block, timeout): KeyboardInterrupt no error throw, what's happened ? -
Django -- Sort items in a list
I have a django model like the following: class Labour(models.Model): Aspect = models.CharField(max_length=100, null=False) Rate = models.DecimalField(decimal_places=2, max_digits=6) Order = models.IntegerField() In the template, I am using Sortable JS. What I am trying to do is, make my list drag-able, re-arrange the order if there're changes and store the same order in django model. However, I cannot figure out how to do this. -
Data in Postgresql dont save
Ubuntu 16.04, Postgres 9.5,django==1.10.7 Data in my django project dont save in database. Migrate are working, createsuperuser too, but data dont saving. In the local dev all works good, but in production no. In the postgresql-9.5-main.log was see this: 2017-06-16 18:26:42 MSK [1026-2] LOG: received fast shutdown request 2017-06-16 18:26:42 MSK [1026-3] LOG: aborting any active transactions 2017-06-16 18:26:42 MSK [1040-2] LOG: autovacuum launcher shutting down 2017-06-16 18:26:42 MSK [1037-1] LOG: shutting down 2017-06-16 18:26:42 MSK [1037-2] LOG: database system is shut down 2017-06-16 18:26:57 MSK [1056-1] LOG: database system was shut down at 2017-06-16 18:26:42 MSK 2017-06-16 18:26:57 MSK [1056-2] LOG: MultiXact member wraparound protections are now enabled 2017-06-16 18:26:57 MSK [1038-1] LOG: database system is ready to accept connections 2017-06-16 18:26:57 MSK [1061-1] LOG: autovacuum launcher started 2017-06-16 18:26:57 MSK [1273-1] [unknown]@[unknown] LOG: incomplete startup packet 2017-06-16 21:35:42 MSK [5836-1] user@user LOG: could not receive data from client: Connection reset by peer 2017-06-17 17:37:27 MSK [26684-1] user@user LOG: could not receive data from client: Connection reset by peer 2017-06-17 17:37:27 MSK [26678-1] user@user LOG: could not receive data from client: Connection reset by peer 2017-06-17 17:37:27 MSK [26676-1] user@user LOG: could not receive data from client: Connection reset … -
How can I log in to a Django backend from an iOS Swift App using Alamo-fire?
I want to login to my Django backend from my iOS swift app using Alamofire. I tried sending a POST request with the username and password as parameters, but got a 405 Method not allowed code. I tried changing the request method to GET and got a 404 not found code. I'm starting to think that I'm way off track and that there may be some kind of build in way to login from Alamofire that doesn't involve the request method at all. How can I log in to a Django backend from my iOS app? Here's my login button function: @IBAction func loginButton(_ sender: UIButton) { accountsClient.login(WithUsername: usernameField.text!, AndPassword: passwordField.text!) { response in if let error = response.result.error { print(error) } } } And here's my accountsClient.login method where I send the request: // Method to login to account func login(WithUsername username:String, AndPassword password:String, completionHandler: @escaping (DataResponse<Any>) -> Void){ // Add Headers self.sessionManager.session.configuration.httpAdditionalHeaders = [ "Cookie":"request_method=POST", ] // Add parameters let loginParameters: [String: String] = [ "username": username, "password": password ] // Send request to backend self.sessionManager.request("https://127.0.0.1:8000/accounts/login/", method: .post, parameters: loginParameters) .validate(statusCode: 200..<300) .validate(contentType: ["application/json"]) .responseJSON {response in completionHandler(response) } } -
How to update a single record for django-haystack?
I'm a haystack beginner, and I'm trying to figure out how to update a document. I have the following SearchIndex: class ProductIndex(indexes.SearchIndex, indexes.Indexable): text = indexes.CharField(document=True) # contains keywords associated with the product name= indexes.CharField(model_attr='name') def get_model(self): return Product def prepare_text(self, obj): return [tag.keyword for tag in obj.productkeywords_set.all()] I want to update the text field when a user adds a new product keyword. I have over 80k records, so it takes a very long time when I use python manage.py update_index. Is there a way to update just one document? -
How do creste a link from a database in Django?
If you have a blog model in Django that saves a slug, how do you create an href link from that slug field? -
Django models as optgroup choices
I am trying to get my installed models as opt group choices. I have to do it in my model, not form. so far I tried. def get_installed_model_choices(): returnval = [] for app in settings.SYSTEM_INSTALLED_APPS: app_config = apps.get_app_config(app) app_models = app_config.get_models() model_choices = [] for model in app_models: model_choices.append([model._meta.model_name, model._meta.verbose_name]) returnval.append([app_config.verbose_name, model_choices]) print returnval return returnval And in my model field. model = custom_model_fields.PanNoneBlankCharField(choices = get_installed_model_choices(),verbose_name=_('model'), max_length=20) I get this error. "Models for app '%s' haven't been imported yet." % self.label) Second approach: This is comething I saw on the internet, def __init__(self, *args, **kwargs): super(PanUserModelPermissions, self).__init__(*args, **kwargs) self._meta.get_field('model')._choices = \ lazy(get_installed_model_choices, list)() This didnt work either, had no affect I dont want choices to be static, is there anyway to achieve this? -
Google Adwords API + Python Certificate Verify Field
I have this code using the python google ads api. I return this error: oauth2_client = oauth2.GoogleRefreshTokenClient(client_id, client_secret, refresh_token) adwords_client = adwords.AdWordsClient(developer_token, oauth2_client, user_agent,client_customer_id=client_customer_id) customer_service = adwords_client.GetService('CustomerService',version='v201702') customers = customer_service.getCustomers() -
How to get full url of static default image in django model
I have a model that accepts an image which is not required. I'm trying to provide a link to a default image so that when a user later requests the model, I can send them the default image. I'm using DRF so I don't necessarily have access to reverse inside a view; based on this response I'm trying to achieve the functionality in the model itself. # models.py class Widget(models.Model): ... def image_url(self): ''' Returns the url of the image for the model instance. If no image is found, return the path to the default meal image. ''' if self.image and hasattr(self.image, 'url'): return self.image.url else: return settings.STATIC_URL + 'img/default/meal.png' And in my serializer I just add the field instead of the image: #serializers.py class WidgetSerializer(serializers.HyperlinkedModelSerializer): ... class Meta: model = Widget fields = ('image_url', ... ) However, this of course only gives me the relative path of the image, /static/img/default/meal.png instead of something like http://localhost:8010/static/img/default/meal.png. How can I get the base name of the url inside the model so I can respond with the full url? Is this even the right approach? Also, as a side note, I just visited http://localhost:8010/static/img/default/meal.png in my browser, and it says the image … -
Django batch process due to small memory?
I have a model that has a very large number of instances, and the memory cannot hold them. Now I need to load them and modify some attributes with some very complex function (so I cannot perform the modification on the database directly) I am wondering if there is any way I can batch process the queryset. For example, I can read them such as: Company.objects.all()[0:1000] Company.objects.all()[1000:2000] Company.objects.all()[3000:3000] ... until a queryset is found to be None. However, the above queryset will always read from beginning, which is not very efficient. Any idea on how to batch process the model more efficiently? -
Acces developement server - Django
I tried to run a friend's Django project on my Ubuntu Virtual Machine but I can't access the developement server. After a: python manage.py runserver 0:80 --settings=a.settings.dev_a Here the result : Performing system checks... System check identified no issues (0 silenced). June 19, 2017 - 21:56:31 Django version 1.11, using settings 'a.settings.dev_a' Starting Channels development server at http://0:80/ Channel layer default (asgi_redis.core.RedisChannelLayer) Quit the server with CONTROL-C. 2017-06-19 21:56:31,242 - INFO - worker - Listening on channels chat-messages, http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-06-19 21:56:31,247 - INFO - worker - Listening on channels chat-messages, http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-06-19 21:56:31,269 - INFO - worker - Listening on channels chat-messages, http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-06-19 21:56:31,289 - INFO - worker - Listening on channels chat-messages, http.request, websocket.connect, websocket.disconnect, websocket.receive 2017-06-19 21:56:31,297 - INFO - server - Using busy-loop synchronous mode on channel layer Using busy-loop synchronous mode on channel layer 2017-06-19 21:56:31,305 - INFO - server - Listening on endpoint tcp:port=80:interface=0 Listening on endpoint tcp:port=80:interface=0 Also here the dev_a setting file from a.settings.base import * import sys SETTING = 'dev' SITE = 'http://a.local' DEBUG = True INTERNAL_IPS = ['127.0.0.1'] WSGI_APPLICATION = 'a.wsgi.dev_jeb.application' MEDIA_ROOT = '/a/media/' MEDIA_URL = '/media/' PROJECT_DIRECTORY = '/a' # … -
Using the Django ORM, How can you create a unique hash for all possible combinations
I want to maintain a django model with a unique id for every combination of choices within the model. I would then like to be able to update the model with a new field and not have the previous unique id's change. The id's can be a hash or integer or anything. What's the best way to achieve this? class MyModel(models.Model): WINDOW_MIN = 5 WINDOW_MAX = 7 WINDOW_CHOICES = [(i,i) for i in range(WINDOW_MIN - 1, WINDOW_MAX - 1)] window = models.PositiveIntegerField('Window', editable=True, default=WINDOW_MIN, choices=WINDOW_CHOICES) is_live = models.BooleanField('Live', editable=True, default=False) unique_id = .... Given the above example there will be 3 * 2 == 6 unique id's. If I add another editable boolean field, I don't want to change the previous unique id's but I want the new unique id's to be generated for the new boolean field.