Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : size of floatfields
I have a model with fields : PLM = models.FloatField(_('LMP'),blank=True, null=False, default=1) Is it possible in the administration interface to display 'PLM' whose size would be reduced and not as in the present case to display twenty numbers..? -
'Options' object has no attribute 'get_all_field_names'
In my django-admin, I am trying to make a model non-editable. So, I am overriding a method get_readonly_fields of admin.ModelAdmin. Here is my Code @admin.register(SMSTemplate) class SMSTemplateAdmin(admin.ModelAdmin): list_display=['title', 'json', 'note'] formfield_overrides = { JSONField: {'widget': PrettyJSONWidget } } def has_delete_permission(self, request, obj=None): return False def get_readonly_fields(self, request, obj=None): return self.model._meta.get_all_field_names() But I am facing an error. I am pasting the error here. 'Options' object has no attribute 'get_all_field_names' Any Idea why ? -
Customize django filter model field
I have a following model class some_model(models.Model): some_date = models.DateTimeField() hours = models.IntegerField() Get a current date temp_date = datetime.datetime.now() Now I want filter on django field someting like this filter_date = some_date + add timedelta(hours) and then use filter_date in django filter some_model.objects.filter(filter_date__gte = temp_date) Above query possible in django? -
Dajngo social auth verify if username exist
In django social is there any way to automatically change the username if such a username already exist in the user model ? eg: Facebook username "bob" but bob already exists as a user currently the Facebook user will be saved without a username. -
Is there any way to make a static folder accessible to all apps in django project
I would like to ask if it is possible to make a static folder accessible to all your project apps in django? supposed that we have this structure: src ...\projectFolder ......\__init__.py ......\settings.py ......\urls.py ......\wsgi.py ...\app1 ......\app1 .........\static ...\app2 ......\app2 .........\static ...\app3 ......\app3 .........\static ...manage.py To avoid multiple static folder each app i would like to make this structure so static folder is shared in all the applications with the same level directory of projectFolder. src ...\static // this is static folder that must be shared with all the apps. ...\projectFolder ......\__init__.py ......\settings.py ......\urls.py ......\wsgi.py ...\app1 ...\app2 ...\app3 ...manage.py Is this possible? -
Django: test fail when using {% load staticfiles %} and {% load pipelines %}
I have used django-pipeline for managing static files. I start to introduce 3rd party bootstrap templates. I download whole this 3rd party bootstrap package and copy assets folder, where all css, js files are located, to my project directory. And I set STATICFILES_DIRS like this, STATICFILES_DIRS = ( os.path.join( PROJECT_ROOT_DIR, 'assets', ), ) And I import css, js file in my base.html like this, {% load staticfiles %} {% load pipeline %}<!DOCTYPE html> . . . <!-- 3rd party CSS --> <link href="{% static 'css/essentials.css' %}" rel="stylesheet" type="text/css" /> <link href="{% static 'css/layout.css' %}" rel="stylesheet" type="text/css" /> <link href="{% static 'css/header-1.css' %}" rel="stylesheet" type="text/css" /> <!-- my css --> {% stylesheet "application" %} . . . <!-- 3rd party JS --> <script type="text/javascript" src="{% static 'js/scripts.js' %}"></script> <!-- my js --> {% javascript "message" %} And temporally, I also import this 3rd-party's image like this, <img src="{% static 'images/a.png' %}"> All things works good and show 3rd party bootstrap views very well in browser. Image shows very well, and import css, js without any errors. I checked it through Chrome development tool. However, when I execute my whole tests, all test_views fail !! All errors are same with below, ERROR: β¦ -
How to configure multiple brokers in Django and Celery?
Requirement: Django making use of RabbitMQ(Internal) and SQS/Kafka Both tasks shares common DB/Django models. Django settings supports only one broker configuration as of Oct 2016 How to have shared tasks with different Queue configurations and broker settings ? Additionally: Also explains how to connect to SQS using Django and celery -
Django block and resend post_save() signal
Scenario Consider this django model: class Task(models.Model): title = models.TextField() ... I have many models like Task each of which is linked to each other. When a user creates a Task, (or any other model) these actions must take place: Create a log entry (custom model) with link to user, action, etc. Create notifications for users who are following tasks (based on the Log) If the user has created a Task under special conditions, make changes to another model. To properly handle this, I need to add a receiver on the Log app that would listen to post_save on Task model. Almost all user actions will be through an API built with DRF. Problem The post_save signal does not have any reference to the user's request. There are ways (hacks) to provide the request to the signal using a middleware, but are not elegant. Requirement All API actions (create, update, delete) should be able to catch and resend the post_save with some parameters from the request. How can this be done? PS:- Do ask for any clarifications. -
Modal pop django template
I have django template with table for which the data is populated dynamically (data is retrieved from database and sent through views). Code is shown below: {% for detail in modal_data %} {{ detail.0 }} {{ detail.1 }} {% endfor %} Now i want show a modal popup on onclick for any row. But the requirement is row specific. Suppose the table is like below abc 10 def 15 fgh 20 When the user clicks on abc row it should show data specific to abc sent from the view file and same for def and fgh. For abc, def, and "fgh" data is retrieved from database and sent through views file. I am not able to figure out the possibility of how to do it. Can modal and jquery be combined to pass the data from views? Need help ! -
Saving nearly 20 billion entries in django postgresql
I'm trying to save about 15-20 billion entries in django model and I'm using postgresql. I tried to use django bulk_create but my computer got stuck for nearly 45 minutes and then I shut the code now. My question is, how to do this in the right way? -
How to filter user requested datetime django?
I wanted to try something like this times = data.objects.datetimes('req_time', 'second',user=request.user) I need to filter user requested datetime from db -
python3 django1.8 mysql5.5 gives page not found (404) while sqlite works fine
Mysql: DATABASES = { 'default': { 'NAME': 'ch01', 'ENGINE': 'mysql.connector.django', 'HOST':'172.17.100.18', 'USER': 'test', 'PASSWORD': '123456', 'OPTIONS': { 'autocommit': True, }, } } sqlite: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } blog/urls.py: from django.conf.urls import url, include from . import views urlpatterns = [ #url(r'^$', views.post_list, name='post_list'), url(r'^$', views.PostListView.as_view(), name='post_list'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'), ] When I run server with second database settings project works fine, but when I run first settings file with mysql, django returns 404 error for all urls. -
Django forms: List of checkboxes populated from a model
I am new to Django. I am trying to render a list of checkboxes with the choices being populated from values in a model's field. Here is what I have so far: models #Model that feeds the list of checkboxes class Category_Level1(models.Model): category_level1_name = models.CharField(max_length = 50) forms class ProductCategoryLevel1Form(forms.Form): product_category_level1 = forms.MultipleChoiceField(label = "Product Category", choices = Category_Level1.objects.all(), widget = forms.CheckboxSelectMultiple) views def select_product(request): product_category_level1 = ProductCategoryLevel1Form() if request.method == 'POST': product_category_level1_form = ProductCategoryLevel1Form(request.POST) if product_category_level1_form.is_valid(): product_category_level1_list = product_category_level1_form.cleaned_data.get('product_category_level1', 'Unk') # Saving the selected categories to another table product_cat_obj = Product_Category_Level1(category_level1_name = product_category_level1_list) product_cat_obj.save() context = { 'product_category_level1' : product_category_level1 } return render(request, 'select_product/select.html', context) template <div class="row"> <label for="id_prod_category"></label> {% product_category_level1 %} </div> I get the following error: Invalid block tag on line 23: 'product_category_level1', expected 'endblock'. Did you forget to register or load this tag? What am I doing wrong? Appreciate any suggestions. -
Deploying django static files in production
My django application is working well on Ubuntu 14.04 / nginx 1.10 / django 1.10.2 / uwsgi 2.0.14, it can also load static files (js, css, images) as well, but css files is not apply to my website. The following is my configuration. application structure example.com/ βββ example.com βββ static (generated by collectstatic) β βββ css β βββ js β βββ images βββ templates βββ website βββ static (django collected from) uwsgi setting example.com.ini [uwsgi] ... socket=/var/www/example.com/uwsgi.sock chdir=/var/www/example.com chmod-socket=664 ... nginx.conf server { listen 80 default_server; server_name example.com; charset utf-8; access_log /var/log/nginx/access.log; error_page 404 /var/www/example.com/template/404.html; error_page 500 502 503 504 /var/www/example.com/template/500.html; location / { uwsgi_pass unix:///var/www/example.com/uwsgi.sock; include uwsgi_params; } location /static/ { alias /var/www/example.com/static/; } } setting.py INSTALLED_APPS = ( ... 'django.contrib.staticfiles', ... ) STATIC_ROOT = os.path.join(BASE_DIR, "static") STATIC_URL = '/static/' STATICFILES_DIRS = ( os.path.join(BASE_DIR, "website/static"), ) STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ... ] STATICFILES_STORAGE = 'whitenoise.django.GzipManifestStaticFilesStorage' After running ./manager collectstatic, I can access .css files by clicking the source path from web page in browser, and checking the access.log it also returns 200, no any error.log produced. "GET /static/admin/css/base.a846c0e2ef65.css HTTP/1.1" 200 Static files is already served by nginx I think, but it does not work in production (work in β¦ -
Can Node.js projects be done in Python?
This was built in Node.js: Link HTN My question is, is it possible for a piece of software that has a backend in Node.js to be transformed into Python? What I am asking is could I recreate this software using Python as a backend instead of Node.js? -
python3 manage.py migrate got an error
I just started a new project and change database engine DATABASES = { 'default': { 'ENGINE': 'mysql.connector.django', 'NAME': 'mysite', 'USER': 'root', 'PASSWORD': 'mypassword', 'HOST': '127.0.0.1', 'PORT': '3306', } } then after running python3 manage.py migrate i got an error: Operations to perform: Apply all migrations: admin, auth, contenttypes, sessions Running migrations: Applying contenttypes.0001_initial...Traceback (most recent call last): File "/usr/local/lib/python3.5/site-packages/mysql/connector/django/base.py", line 177, in _execute_wrapper return method(query, args) File "/usr/local/lib/python3.5/site-packages/mysql/connector/cursor.py", line 515, in execute self._handle_result(self._connection.cmd_query(stmt)) File "/usr/local/lib/python3.5/site-packages/mysql/connector/cursor.py", line 434, in _handle_result self._handle_noresultset(result) File "/usr/local/lib/python3.5/site-packages/mysql/connector/cursor.py", line 404, in _handle_noresultset self._warnings[0][1], self._warnings[0][2]) mysql.connector.errors.DatabaseError: 1265: Data truncated for column 'applied' at row 1 -
Django - Select shortest game of each type, and its details
So I have a game: class Game(models.Model): player = models.ForeignKey(settings.AUTH_USER_MODEL, models.PROTECT, db_index=True) start_time = models.DateTimeField(default=timezone.now) duration = models.DurationField(null=True, default=None) game_type = models.ForeignKey(GameType, models.PROTECT, db_index=True) ... class GameType(models.Model): show_name = models.BooleanField(default=True, db_index=True) show_photo = models.BooleanField(default=True, db_index=True) ... I want to show a leader-board. Which means I need for each GameType, to show the game-type details, the player that won (played the shortest (minimum duration) game), the actual duration, and maybe also the time the game started. How can this be done efficiently (preferably with a single query) in django? I thought about something like: GameType.objects.annotate(min_duration=Min("game_set__duration")) But then how do I get the full details of the game, like the player and the start_time (without issuing more queries of course)? Another option is: Game.objects.values("game_type").annotate(min_duration=Min("duration")) But again I'm missing all the details of both Game and GameType. Any ideas? Thank you! -
Django: Having problems saving value of datetime.date as null in database
My form looks like this: If the 'In Progress' box is checked I want the 'End Date' to be null in the MySQL db when I save the form. In my model I have this to allow a value of null to be saved (I think?): end_date = models.DateField(default=datetime.date, blank=True, null=True) I don't know if this is the best way to do it, but then in my views.py I have this line: if request.POST.get('end_year') == '- Year -': end_date = datetime.date(None, None, None) (I would also have similar checks for the Month and Day) But when I try to submit my form I get 'an integer is required' exception. As some additional information, when I manually try to change end_date to null in the db I get this error: Incorrect date value: 'null' for column 'end_date' at row 1 I'm not really sure what the best way to approach this is. Any ideas would be appreciated. Thank you. -
Display next form field after selecting but not submitting the previous one
I'm working with oTree which is an interactive economic game platform based on Django. I have several ChoiceField questions in a single template page. I would like the user to choose the questions one by one, but the next question is shown only after selecting the previous one. Also, the user can review all the questions before proceeding to the next page. {% block content %} <p>Question 1</p> {% formfield class1.q1 with label="select" %} <p>Question 2</p> {% formfield class1.q2 with label="select" %} {% next_button %} {% endblock %} I realize that this can be achieved by JS but I'm new to JS and struggling to find the solution. Thanks! -
Django - Many to Many Model Returning None
Long time listener, first time poster. Hoping to get some help with my models issue. I'm having trouble with my many to many relationship. When I submit a form, I want to have my user's info associated with the post that they create. I'm using a many to many because I will have an additional feature where other users can join in on that same trip. Currently my data for my Trip tables creates fine, but my user isn't being linked to the Trip id so I can't render out their name on the template. Below is my code. Appreciate any help! Cheers Here are my models.py: class User(models.Model): name = models.CharField(max_length=45) username = models.CharField(max_length=255) password = models.CharField(max_length=255) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = UserManager() class Trip(models.Model): destination = models.CharField(max_length=45) description = models.CharField(max_length=255) datefrom = models.CharField(max_length=255) dateend = models.CharField(max_length=255) user = models.ManyToManyField(User) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) Here is my views.py: def travels(request): user = User.objects.get(id=request.session['logged_user']) all_trips = Trip.objects.all().order_by('-id') user_trips = Trip.objects.filter(user=request.session['logged_user']) context = { "user_trips": user_trips, "all_trips": all_trips, "user": user, } return render(request, 'belt_exam/travels.html', context) def addtrip(request): user_id = request.session['logged_user'] createdtrip = Trip.objects.create(destination=request.POST['destination'], description=request.POST['description'], datefrom=request.POST['datefrom'], dateend=request.POST['dateend']) createdtrip.user.add(User.objects.get(id=user_id)) return redirect('/travels') Here's my template: {% for alltrip in β¦ -
How to restrict two columns not to have the same value using Django?
I have two integer columns, and want to restrict them not to have the same value within a row. For example, id | type1 | type2 | ------------------------ 1 | 1 | 2 | 2 | 1 | 3 | 3 | 3 | 3 The first and second rows are okay, but the third one should not exist. How to add this restriction in Django model? -
django-ldap-auth user profile in django > 1.7
I'm trying to implement django-ldap-auth in my project and everything seems to work just fine. The problem is, that package doesn't support user profile field population for Django versions newer than 1.7. From docs: Note Django 1.7 and later do not directly support user profiles. In these versions, LDAPBackend will ignore the profile-related settings. I've added this to my settings.py but nothing happens(as expected) but I still wanted to try: AUTH_LDAP_PROFILE_ATTR_MAP = {"description": "description"} My question is how can I enable AUTH_LDAP_PROFILE_ATTR_MAP in newer django versions? EDIT: I'm thinking of using custom user model but I'm not sure if that's the best way here.. -
Rate Limit API Calls to Shopify API with Django on Google App Engine
I am trying to use the Shopify API from my Django app hosted on Google App Engine. For my local single threaded scripts I am using a modified version of this to make sure that I don't go over Shopify's rate limit: # Setup local bucket to limit API Calls bucket = TokenBucket(40, .5) api_call_success = False while not api_call_success: if bucket.tokens < 1: sleep(.5) else: [... do an API call ...] bucket.consume(1) api_call_success = True This works for my local scripts, but it won't work for my Google App Engine hosted application where there may be multiple tenants, and multiple sessions occurring at once. I have been trying to research the best way to handle this rate limiting, and presently was going to try to constantly write each users/stores request response header to memcache so that I could always check the 'x-shopify-shop-api-call-limit' to see what the previous call limit (and time of the call) was. So I tried something like this: fill_rate = .5 capacity = 40 # get memcache key info last_call_time = memcache.get(memKey+"_last_call_time") last_call_value = memcache.get(memKey+"_last_call_value") # Calculate how many tokens should be available now = datetime.datetime.utcnow() delta = fill_rate * ((now - last_call_time).seconds) tokensAvailable = min(capacity, β¦ -
Django Javascript and Debugging
I am trying to add a JS datepicker using jquery in my template but I can't for the life of me get it working. My header.html (master template): [...] <script src="{% static 'js/jquery.js' %}"></script> <script src="{% static 'js/jquery-ui.js' %}"></script> <script> $( function() { $( "#datepicker" ).datepicker({ showOn: "button", buttonImage: "{% static 'images/calendar.gif' %}", buttonImageOnly: true, buttonText: "Select date" }); } ); </script> <title>{% block title %}{% endblock %}</title> </head> The template containing the script: [...] <div class="form-group"> <div class="col-sm-offset-2 col-sm-10"> <span class="text-danger small">{{ field.errors }}</span> </div> <label class="control-label col-sm-2"> {{ field.label_tag }} </label> <div class="col-sm-10"> <input type="text" id="datepicker"> </div> </div> [...] If I make a completely bare sheet and use the script, it works find. If I put all the code on the main header.html template, it doesn't work. If I completely wipe my header.html and replace all the code with the script source, it works. I don't see how my code could stop the script from working. What am I missing here? Also, what is a good way to troubleshoot when the development server is remote? -
django: proper way to send POST to view from potentially unlimited forms
In my django application I have a page where the user can theoretically add as many addresses as they want. I have a django address form that contains typical information (address, city, postal code) and the user can create as many of these django forms as they want, and the forms are all identical other than a unique id. My problem is that I need the user to be able to click a submit button which will submit all the forms to a view where I can process the addresses. Other answers to similar questions don't seem to work for me, currently my approach involves looping through the forms and calling jquery's submit() function on each one when the submit button is pressed, but that approach isn't working. Ideally I would end up with a POST request in my view with all of the address information from all of the forms so I can easily process it within the view. I'm not sure if there's a simple solution or if there's an entirely different approach that would work better, but any answers are welcome.