Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django - click the button and save create date in database
Database: database Model : class Donor(models.Model): firstName = models.CharField(max_length=50) lastName = models.CharField(max_length=50) bloodType = models.CharField(max_length=10) createdDate = models.DateTimeField(auto_now_add=True) lastAttendance = models.DateTimeField(auto_now_add=True) View: donor_id = None if request.method == "GET": donor_id = request.GET['id'] if donor_id: donor = Donor.objects.get(id=int(donor_id)) if donor: donor.createdDate = True donor.save() Error message: MultiValueDictKeyError at /donors/ "'id'" Problem: approach Click the attentd button, take user's id and save in the database current date. Any solutions appreciated!! -
Django ORM access optimization with Filter
I've implemented a method on my django app that will check if a user has a specific permission or it's part of a group that contains this specific permission. def user_has_perm(user, *permissions_to_check): permission_check = True permissions_not_found = [] user_groups = user.groups.all().prefetch_related('permissions') for permission in permissions_to_check: content_type, permission_codename = permission.split('.') if not user.has_perm(permission) and not user_groups.filter( permissions__content_type__model__icontains=content_type, permissions__codename__icontains=permission_codename).exists(): # Goes down from Groups to the single user permission permission_check = False permissions_not_found.append(permission) return permission_check, permissions_not_found Now, everythings works like a charm, but, Django-Debug-Toolbar it's complaining about the query, that it's duplicated many times as the groups to check. For me it's a bottleneck, because some users will have 50 groups associated, and really i don't know how to optimize this query... Any suggestions? Thanks -
Order json string in django model
I have a text column in my model, that save json into it. when I try to get this string and convert it to object i use: @property def text_json(self): if self._text_json: return ast.literal_eval(self._text_json) return {} The problem is that its return different order every time. What is the best solution? thanks -
Best development server?
I'm using the default django server to develop my projects. I have tried the ngrok's platform to test webhoks connections and I'm very surprised with its web interface, specially with the "replay" option. It would be great to use with a lot of tests that require to launch a request multiple times. Do you know something like this to run on my local server? (Something like a proxy between runserver and "localhost:port" with web gui, maybe) Which is the best django development server that you know? -
External js is not working in django
I'm trying to load external js file settings for static folder STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') Here I include js in template {% load static %} <link rel="stylesheet" href="{% static '/css/main.css' %}"> <link type="text/javascript" href="{% static '/js/main.js' %}"> And my project structure -project ---app ---static -----css -------main.css -----js -------main.js I dont know why, but css works and js is not loaded (I don't see main.js in the browser developer tool) -
Django1.10 cannot save korean characters(Mysql)
I got the error below in django when saving a field with Korean character in the admin panel. OperationalError at /admin/blog/post/add/ (1366, "Incorrect string value: '\\xEC\\xB9\\xB4\\xED\\x8E\\x98...' for column 'object_repr' at row 1") I'm sure the database(DB, tables, column) is ready for utf8mb4, because I can write/read these korean character in phpmyadmin and django shell. Also, I set DATABASE section in the settings.py with DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'name', 'USER' : 'root', 'PASSWORD' : 'password', 'HOST' : '', 'PORT' : '3306', 'OPTIONS': {'charset': 'utf8mb4'}, } } How can I solve this problem?? -
Django Admin does not display pre-existing objects
I created a class for exposing Django-Admin to multiple databases as explained in Django docs. My admin.py looks like this from django.contrib import admin # Register your models here. from .models import DestinationMap class MultiDBModelAdmin(admin.ModelAdmin): # A handy constant for the name of the alternate database. using = 'supplierui' def save_model(self, request, obj, form, change): # Tell Django to save objects to the 'other' database. obj.save(using=self.using) def delete_model(self, request, obj): # Tell Django to delete objects from the 'other' database obj.delete(using=self.using) def queryset(self, request): # Tell Django to look for objects on the 'other' database. return super(MultiDBModelAdmin, self).queryset(request).using(self.using) def formfield_for_foreignkey(self, db_field, request=None, **kwargs): # Tell Django to populate ForeignKey widgets using a query # on the 'other' database. return super(MultiDBModelAdmin, self).formfield_for_foreignkey(db_field, request=request, using=self.using, **kwargs) def formfield_for_manytomany(self, db_field, request=None, **kwargs): # Tell Django to populate ManyToMany widgets using a query # on the 'other' database. return super(MultiDBModelAdmin, self).formfield_for_manytomany(db_field, request=request, using=self.using, **kwargs) admin.site.register(DestinationMap, MultiDBModelAdmin) #admin.site.register(DestinationMap) The admin interface displays the model name, but has 0 objects. The table contains 275 objects, I have confirmed that using sql. I cannot find any solution to this as of now. Help would be appreciated. -
Getting context data of one view for another view
I have a FormView class PasswordFormView(FormView): I would like to use the context_data in PasswordFormView in another form view called AuthFormView class AuthFormView(FormView): context_data = PasswordFormView.get_context_data How would I do that? Thank you -
when parsing below line on a django framework ,The server page is empty.Inspect element says this error?
html +='<a href="' + urland + '">' + str(Dag.dag_id) + '</a><br>' django.db.models.query_utils.deferredattribute object="" at="" 0x040adbf0="" -
Jinja: Concatenate '#' + variable in HTML attribute?
In a Django project, I'm using Jinja + pug. To assist with the elements I'm talking about, I've added four forward slashes above them in the code below: each val in bottles tr th(scope="row")= index ... div.text-center //// button.btn.btn-default.btn-xs(type="button", data-toggle="modal", data-target='#{{ val.name }}') span.glyphicon.glyphicon-plus.text-primary button.btn.btn-default.btn-xs(type="button", data-toggle="modal", data-target=".remove-bottles") span.glyphicon.glyphicon-minus.text-primary //- Add Quantity Modal //// div.modal.fade(tabindex="-1" role="dialog")(id="{{val.name}}") ... So basically the first button will trigger the modal div, but I need to set data-target='#{{val.name}}'. Doing this results in a syntax error, while adding a space (like so data-target='# {{val.name}}'), adds a space between the pound sign (#) and {{val.name}}, which means that the IDs don't match. How can I concatenate # and {{val.name}} with a space between them? -
Django: Creating multiple class instances on a single webpage, with Foreign Key dependencies
I have the following code in my models.py: class Application(models.Model): team_name = models.CharField(max_length=100) ... class Participant(models.Model): name = models.CharField(max_length=100) grade = models.SmallIntegerField(choices=GRADE_CHOICES, blank=True, null=True) application = models.ForeignKey(Application, related_name="participants") ... i.e. There are multiple Participants, and each Participant will be on a single application. (It is defined that each Application will have exactly 8 Participants). The intended purpose of this code is that a user will be able to create a new application, on which he/she will name 8 Participants. When the Application is created, 8 new instances of Participants should also be created and linked such that each Participant has the newly created Application as its Foreign Key. I am currently struggling to create a form/view that will handle this creation process. I want the user to be a presented a single webpage that presents input forms that allow the user to create a new Application (name, etc.), along with 8 new Participants (each having a name, grade, etc.) My current forms.py has: class ApplicationForm(forms.ModelForm): """ A form that edits an application and all of its participants. """ nationality = forms.CharField(disabled=True, required=False) class Meta: model = Application fields = '__all__' But I realize that this does not display to the … -
Neat Formatted Test Cases Error Output for Python Django
I am running my nose test cases for my django app using python manage.py test However, when I get an output a particular test case error, the output is like this: > Error Message > exit__ six.reraise(dj_exc_type, dj_exc_value, traceback) File "/home/ubuntu/Envs/venv/local/lib/python2.7/site-packages/django/db/backends/util.py", > line 53, in execute return self.cursor.execute(sql, params) File > "/home/ubuntu/Envs/venv/local/lib/python2.7/site-packages/django/db/backends/sqlite3/base.py", > line 452, in execute return Database.Cursor.execute(self, query, > params) 'UNIQUE constraint failed: apixyz_.budsadsinesds_id, > api_user_id\n-------------------- >> begin captured logging << > --------------------\npy.warnings: WARNING: /home/ubuntu/Envs/venv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py:883: > RuntimeWarning: DateTimeField BusinessMetrics.from_date received > a naive datetime (2017-05-29 11:35:13.639105) while time zone support > is active.\n RuntimeWarning)\n\npy.warnings: WARNING: > /home/ubuntu/Envs/venv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py:883: > RuntimeWarning: DateTimeMetrics.from_date received a naive datetime > (2017-05-29 11:35:13.647704) while time zone support is active.\n > RuntimeWarning)\n\npy.warnings: WARNING: > /home/ubuntu/Envs/venv/local/lib/python2.7/site-packages/django/db/models/fields/__init__.py:883: > RuntimeWarning: DateTimeMetrics.from_date received a naive datetime > (2017-05-29 11:35:13.656736) while time zone support is active.\n (Pasted a sample here but it looks better only because I added the lines as quote and code block) And this is not really readable. Can I set some option so that traceback is more readable and \n changes to next line automatically? -
Filtering order in django
I'm interested to filter table by django orm in specific order. Basically, it's simple search by two fields - name and description. I want to sort the result first by the "name" field concurrencies, and then by the "description" field concurrencies. Here is the example of raw sql: WITH checkpoints AS (SELECT * FROM checkpoints_view WHERE ...) SELECT * FROM checkpoints WHERE name ILIKE '%KEYWORD%' UNION ALL SELECT * FROM checkpoints WHERE description ILIKE '%KEYWORD%' AND name NOT ILIKE '%KEYWORD%'; How can i generate sql like this in the django orm? Thanks to all P.S.: sorry for my english if i wasn't correct, i'm from not english-speaking country -
Django Celery Issue
I am using celery for an asynchronous task in my project. But when I try to run the worker, it gives me the following error: django.core.exceptions.ImproperlyConfigured: Requested setting LOGGING_CONFIG, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Not able to figure out how to resolve it. -
Django: attempt to write a readonly database
I've seen this question on here from before, but the answers really aren't cutting it. My application resides within /home/ubuntu/mywebsite All folders and files are 775 belonging to ubuntu : ubuntu My database is db.sqlite3 I keep getting warnings like this: attempt to write a readonly database A additional requirement is that my FTP needs to still work, using the ubuntu username. What is the ideal user : group permission scheme that I should have for this application? -
Set dynamic Value for Modal Action Form
I need to set dynamic value for Modal popup. This is my modal <!-- Modal --> <div class="modal fade" id="popUpModal" role="dialog"> <div class="modal-dialog"> <!-- Modal content--> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal">&times;</button> <h4 class="modal-title">"this is the value {{ cra }}"</h4> </div> <form class="modal-form" id="docsForm" action="{% url 'contact_delete' pk=contact.id %}" method="post" enctype="multipart/form-data"> <input type="file" name="upload" /> <input type="hidden" name="brandcode" value=this.id /> <input type="submit" /></form> <div class="modal-footer"> </div> </div> </div> </div> This is what I am trying <script> $('#popUpModal').on('show.bs.modal', function(e) { var $modal = $(this), esseyId = e.relatedTarget.id; $modal.find('.modal-form').html(esseyId); }) </script> based on the record I want value like contact/delete/1 contact/delete/2 .... -
Django uploading a file from a form fails to validate
I am trying to build a media library for my personal website. I can upload files in the django admin just fine through a FileField but I want to be able to do in my media library page instead. When I try to validate the form I get from the media library page form.is_valid() fails and returns Not Found: /media/ My MEDIA_URL is media/ # views.py class MediaView(UpdateView): form_class = FileForm model = File template_name = 'myapp/media.html' def get(self, request): if (request.user.is_superuser): form = self.form_class(None) files = File.objects.all() return render(request, self.template_name, {'form': form, 'files': files}) else: return HttpResponseForbidden() def post(self, request): if (not request.user.is_superuser): return HttpResponseForbidden() form = self.form_class(request.POST) if (form.is_valid()): name = form.cleaned_data['name'] file = form.cleaned_data['file'] media = form.save(commit=False) if (not name): media.name = name media.file = file media = form.save() return redirect('/media') else: return HttpResponseNotFound() # models.py class File(models.Model): name = models.CharField(max_length=256, null=True, blank=True) file = models.FileField() date_uploaded = models.DateTimeField(default=datetime.now) def __str__(self): if (not self.name): return str(self.file) else: return self.name -
Django: How can I update my database using an AJAX request?
In my web app., I have users who have a coin balance in addition to a timer. When the timer finishes counting down, I would like for their coin balance to increase. Within Django, I access the user's coin balance using: {{ request.user.profile.coins }}, and my JS timer looks like this: function startClock () { timeInterval = setInterval(function () { var t = getTimeLeft(deadline); minutesSpan.innerHTML = ("0" + t.minutes).slice(-2); secondsSpan.innerHTML = ("0" + t.seconds).slice(-2); if (t.total <= 0) { clearInterval(timeInterval); if (i === 7) { $(".reset, .start-pomodoro").addClass('hidden'); $(".start-break2").removeClass('hidden'); } else if ((i % 2) === 1) { $(".reset, .start-pomodoro").addClass('hidden'); $(".start-break1").removeClass('hidden'); } else { $(".start-pomodoro").removeClass('hidden'); } } }, 1000); How can I make it so that before the if statement executes, the user's coin balance increases? -
Reverse Look up Django foreign key?
I have three models universities, users and master user types .Models are defined below. university model:- from __future__ import unicode_literals from django.db import models # WE ARE AT MODELS/UNIVERSITIES class Universities(models.Model): id = models.IntegerField(db_column="id", max_length=11, help_text="") name = models.CharField(db_column="name", max_length=255, help_text="") abbreviation = models.CharField(db_column="abbreviation", max_length=255, help_text="") address = models.CharField(db_column="address", max_length=255, help_text="") status = models.BooleanField(db_column="status", default=False, help_text="") createdAt = models.DateTimeField(db_column='createdAt', auto_now=True, help_text="") modifiedAt = models.DateTimeField(db_column='modifiedAt', auto_now=True, help_text="") updatedBy = models.IntegerField(db_column="updatedBy",default=None,help_text="Logged in user updated by ......") class Meta: managed = False get_latest_by = 'createdAt' db_table = 'universities' user model: from __future__ import unicode_literals from django.db import models from django.contrib.auth.models import User from cms.models.masterUserTypes import MasterUserTypes from cms.models.universities import Universities from cms.models.departments import MasterDepartments # WE ARE AT MODELS/APPUSERS requestChoice = ( ('male', 'male'), ('female', 'female'), ) class Users(models.Model): id = models.IntegerField(db_column="id", max_length=11, help_text="") userTypeId = models.ForeignKey(MasterUserTypes, db_column="userTypeId") universityId = models.ForeignKey(Universities, db_column="universityId") departmentId = models.ForeignKey(MasterDepartments , db_column="departmentId",help_text="") name = models.CharField(db_column="name",max_length=255,help_text="") username = models.CharField(db_column="username",unique=True, max_length=255,help_text="") email = models.CharField(db_column="email",unique=True, max_length=255,help_text="") password = models.CharField(db_column="password",max_length=255,help_text="") bio = models.TextField(db_column="bio",max_length=500,help_text="") gender = models.CharField(db_column="gender",max_length=6, choices=requestChoice,help_text="") mobileNo = models.CharField(db_column='mobileNo', max_length=16,help_text="") dob = models.DateField(db_column="dob",help_text="") major = models.CharField(db_column="major",max_length=255,help_text="") class Meta: managed = False db_table = 'users' and user type model:- from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models # … -
Django ImageField showing absolute Linux path in template
I have the following model class Product(SiteBaseFields): name = models.CharField(max_length=500) description = models.CharField(max_length=500) price = models.DecimalField(max_digits=10, decimal_places=2, null=True, blank=True, default=0.00) unit = models.CharField(max_length=500, null=True, blank=True, default=0.00) image = models.ImageField(upload_to=settings.MEDIA_ROOT, null=True, blank=True) def __unicode__(self): return self.name The product record in the database are d762ugo5f5706v=> select id, image from dj_commerce_product d762ugo5f5706v-> ; id | image ----+------------------------------------------------------------------------------------------------------ 17 | /var/www/dj_node_project/media/iphone_4TTsU22.jpg 19 | /var/www/dj_node_project/media/samsung_phone_5VlDULp.png 18 | /var/www/dj_node_project/media/201409-w-americas-best-coffee-cities-new-orleans-cafe-du-_CTcGKwx.jpg (3 rows) When I do <img src="{{MEDIA_URL}}{{product.image.url}}" /> in the template, I get back <img src="/var/www/dj_node_project/media/iphone_4TTsU22.jpg">, and the URL to the image is totally wrong. I can't not find out the cause. -
Django query execute behaviour
I have wrtie down this in django a = Model.objects.all() Is this query execute immediately or not? When this query fetch request from db -
AWS Cognito as Django authentication back-end for web site (reprise)
My reading of Cognito is that it can be used in place of a local Django admin database to authenticate users of a website. However I am not finding any soup-to-nuts examples of a basic "Hello, World" app with a login screen that goes through Cognito. I would very much appreciate it if someone could post an article that shows, step-by-step, how to create a Hello World Django app and a Cognito user pool, and then how to replace the default authentication in Django with a call to AWS Cognito. In particular I need to know how to gather the information from the Cognito admin site that is needed to set up a call to Cognito API to authenticate a user. There are two cases to consider: App user login to App, and Admin login to django Admin URL of site. I assume that I would want to use Cognito for both cases, otherwise I am leaving a potential hole where the Admin URL is using a weaker login technology. Current answers on AWS forums and StackExchange either say (1) It is a waste of time to use Cognito for authenticating a website, it is only for access to AWS … -
How to get all objects, excluding ones that have records with same related field id value
Model Model1 has ForeignKey field (my_field) to Model2. I want to retrieve all Model1 without records that already have at least 1 record with same my_field value. -
Django DRF Token Authentication
I'm having issues with DRF's token based authentication. Following is my landing page code (after login): @api_view(['GET','POST'],) def landing(request): this_tenant=request.user.tenant end=date_first.date.today() start=end-date_first.timedelta(days=30) sales_daily=sales_day_wise(start, end, this_tenant) invoice_value=sales_raised_value(start, end, this_tenant) payment_value=sales_collected_value(start, end, this_tenant) return render(request,'landing.html', {'sales_daily':json.dumps(sales_daily, cls=DjangoJSONEncoder),\ 'invoice_value':json.dumps(invoice_value, cls=DjangoJSONEncoder), \ 'payment_value':json.dumps(payment_value, cls=DjangoJSONEncoder)}) I'm using Django's built-in login view to authenticate and log in a user. Following is my DRF settings: REST_FRAMEWORK = { 'DEFAULT_RENDERER_CLASSES': ( 'rest_framework.renderers.JSONRenderer', ), 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.TokenAuthentication', # 'rest_framework.authentication.SessionAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), } Issue is, when I'm logging in and going to the landing page via browser, DRF is not working and I'm getting the following error: {"detail":"Authentication credentials were not provided."} The reason is the custom DRF header (AUTHENTICATION = TOEKN XXXXXXXXXX) is not present in the request. However, if I use Postman and put in the custom header (AUTHENTICATION = TOKEN XXXXXXXXXXXX), then it works. How do I solve it? Would this mean I would need a custom header for every view? And on using DRF Token, does it open up CSRF vulnerability (this question: Django DRF - How to do CSRF validation with token authentication )? Thanks a lot!! -
Low-latency communication between web browsers: Django
I'm designing a Django 1.11-powered webapp which features a presentation (PowerPoint-like) mode which can be rendered on an arbitrary number of devices, and controlled by an arbitrary number of devices, which may or may not be the same devices that are displaying the presentation. When the slide is changed, all display browsers need to notice and respond to the change in under 300 ms (100 ms or less is preferred). Slide show content may also be edited on the fly and needs to be pushed out to each display device. My first idea, which I rejected almost immediately, was to have each display browser constantly poll the server for changes. Of course, this is a whole lot of polling. Then I read about WebSockets, and they seemed like the way to go. I'm brand new to this technology, so I'm having to start from zero. After searching for Django libraries for WebSockets, I hit upon Channels and Celery. Initial reading leaves me doubtful about how suited either library is for my purposes, as they seem to be intended for a system where messages are queued for the next available worker. In my use case, I'm not using workers (other than …