Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Error: Reverse for '' with arguments '()' and keyword arguments '{}' not found. 0 pattern(s) tried: []
I checked other posts here in StackOverflow and noticed that most of the related posts were caused by namespace or incorrect URL. My issue is that, if I just render a plain HTML page, the page will load. Problem happens when I use template tag {% extends "education/dashboard/students/base.html" %}. The error didn't specify which part of the code lines is wrong. Any suggestions will be highly appreciated. -
Automatically delete 'old' data sets in Django - MYSQL
I have a sensor node that is streaming environmental data every 5 minutes (temperature, pH) along with its battery levels to a MYSQL instance (and a Django App). Now, I will store all logged temperature , pH data indefinitely on the db as they stream in, but would like to limit battery-level data storage to up to 3 months only. Reason being, its not an important metric for historical data analytics and there is hence no point on taking up disk space, especially if there are multiple nodes sending in data like this. Think of my models.py that deal with this battery level data as something like... class Node_Health(models.Model): # Battery levels, in percentage to two decimal placing timestamp = models.DateTimeField(db_index=True,auto_now=False, auto_now_add=False, null=True) # db index battery_lvl = models.CharField(max_length=4,null=True) Question is, How do I (best practice) automatically monitor & discard of 'old' battery level data once the battery level logs reach > 3 months in the Django-python framework ? i.e. store only the latest three months of battery levels in db. Do i use CRON or Celery with a python script that checks the db for any data in excess and wipes out these 'old data' ? (this is the … -
Confirm resubmission error on back button "Python with Django"
I built a web application where user can login and view work orders, property list and external contractors. However when I click back button on view property list page or view work orders page or view external contractors page it gives me an error saying confirm resubmission. Error screenshot def user_login(request): if request.method == 'POST': form = LoginForm(request.POST) if form.is_valid(): cd = form.cleaned_data user = authenticate(username=cd['username'], password=cd['password']) if user is not None: if user.is_active: login(request, user) if request.user.username == 'propertymanager': #return HttpResponse('Authenticated successfully') return render(request, 'account/dashboard.html', {'section': dashboard}) elif request.user.username == 'technician1': #return HttpResponse('Authenticated successfully') return render(request, 'account/technician_dashboard.html', {'section': dashboard}) elif request.user.username == 'technician2': return render(request, 'account/technician2_dashboard.html',{'section': technician2_dashboard}) else: return render(request, 'registration/incorrect_user.html', {'section':incorrect_user}) else: return HttpResponse('Disabled account') else: return render(request, 'registration/login.html', {'section': incorrect_login}) else: return render(request, 'registration/login.html', {'section': incorrect_login}) else: form = LoginForm() return render(request, 'account/login.html', {'form': form}) I tried replacing the last else with dashboard page else: return HttpResponse('Disabled account') else: return render(request, 'registration/login.html', {'section': incorrect_login}) else: return render(request, 'registration/login.html', {'section': incorrect_login}) else: return render(request, 'account/dashboard.html', {'section': dashboard}) But now my login button doesn't work. Need Help! -
Does anyone know the difference between “table-level” operations and “record-level” operations
From Django Documentation: Managers are accessible only via model classes, rather than from model instances, to enforce a separation between “table-level” operations and “record-level” operations. -
How can I set attributes for li tags in CheckboxSelectMultiple?
I used CheckboxSelectMultiple as a widget for MultipleChoiceField. I know it makes something like this: <ul> <li><input type="checkbox" name="..." ></li> ... </ul> when I set an attribute to CheckboxSelectMultiple, django adds it to ul tag. my question is, how can I set attributes to li? -
ordering a inlineformset_factory in django 1.6
Good morning, guys. I am trying to order an inlineformset_factory and I have a small problem. class Perfil(models.Model): nombre = models.CharField('Nombre', max_length=120) estado = models.CharField(max_length=1, choices=ESTADO_LISTA, default='A') class Meta: ordering = ['nombre'] def __unicode__(self): return self.nombre def get_update_url(self): return reverse('perfil_update', kwargs={'pk': self.pk}) class PerfilDetalle(models.Model): perfil = models.ForeignKey(Perfil, related_name='perfildet_perfil', on_delete=models.PROTECT) modulo = models.CharField(max_length=3, choices=MODULO_LISTA) def __unicode__(self): return u'{0}-{1}'.format(self.perfil, self.get_modulo_display()) def get_update_url(self): return reverse('perfil_update', kwargs={'pk': self.pk}) Views: def perfil_create_update(request, pk=None): if pk: perfil = Perfil.objects.get(pk=pk) title_meta = u'Perfil: Actualización' title = u'Perfil' nav = ( ('Panel Mando', '/'), ('Perfiles', reverse('perfil_list')), ('Actualización', '') ) else: perfil = Perfil() title_meta = u'Perfil: Registro' title = u'Perfil' nav = ( ('Panel Mando', '/'), ('Perfiles', reverse('perfil_list')), ('Registro', '') ) # formset PerfilDetalleFormSet = inlineformset_factory( Perfil, PerfilDetalle, extra=0, can_delete=True, fields=('modulo', 'id', 'perfil') ) if request.method == 'POST': next = request.GET.get('next') form = PerfilForm(request.POST, instance=perfil) perfilDetalleFormset = PerfilDetalleFormSet(request.POST, instance=perfil) if form.is_valid() and perfilDetalleFormset.is_valid(): perfil = form.save() perfilDetalleFormset.save() if next == 'new': return redirect(reverse_lazy('perfil_create')) if next == 'self': return redirect(perfil.get_update_url()) else: return redirect('perfil_list') else: form = PerfilForm(instance=perfil) # perfilDetalleFormset = PerfilDetalleFormSet(instance=perfil, queryset=perfil.perfildet_perfil.order_by("modulo")) perfilDetalleFormset = PerfilDetalleFormSet(instance=perfil) # parámetros comunes nav = ( ('Panel Mando', '/'), ('Perfiles', reverse('perfil_list')), ('Actualización', '') ) constants MODULO_LISTA = ( ('333', 'ADMINISTRADOR: Tareas Programadas'), ('02', 'ADMINISTRADOR: … -
Django send_mass_email without showing all recipients' Emails
Using send_mass_mail will result in all the emails being shown in the 'To' field. I came across this solution but it hides all user Emails. And it looks weird in the inbox because the 'To' field is empty. What I want is to use send_mass_mail showing only the receiving recipient's Email in the 'To' field. E.g. If I send Emails to jack@gmail.com and jane@gmail.com, jack should see jack@gmail.com and jane should see jane@gmail.com in the 'To' field. Is there a way to achieve this? Or do I have to use loop over each recipient with send_mail? -
Why does adding a related_name to my model break existing querysets that use set_all?
So I had to add a related_name to a simple model, and this seems to have broken some html on a couple pages. Here is the model with the related_name class TestModel(models.Model): example_a = models.ForeignKey(example_a) example_b = models.ForeignKey(example_b, related_name='examplesb') node = models.ForeignKey(Node, null=True) time = models.DateTimeField() I believe the culprit is set_all in the template. Is there a quick fix for this? Why is this happening? {% for i in demo.testmodel_set.all|dictsort:"time_start" %} -
SignatureDoesNotMatch - django ajax upload to S3 not working
I've been at this for almost a day now - I have a simple upload feature set up in my Django application to upload assets to an s3 bucket. My workflow is that I'm generating the policy and signature when rendering the upload form and appending it within the javascript so my Django code for rendering the upload form is as below: def sign(key, msg): return hmac.new(key, msg.encode("utf-8"), hashlib.sha256).digest() def getSignatureKey(key, dateStamp, regionName, serviceName): kDate = sign(("AWS4"+key).encode("utf-8"), dateStamp) kRegion = sign(kDate, regionName) kService = sign(kRegion, serviceName) kSigning = sign(kService, "aws4_request") return kSigning class Uploader(TemplateView): def get(self, request, *args, **kwargs): algorithm = "AWS4-HMAC-SHA256" service = "s3" t = datetime.datetime.utcnow() amz_date = t.strftime('%Y%m%dT%H%M%SZ') date_stamp = t.strftime('%Y%m%d') # Date w/o time, used in credential scope tomorrow = datetime.datetime.utcnow() + datetime.timedelta(days=1) shortDate = datetime.datetime.now().strftime("%Y%m%d") requestType = "aws4_request"; expires = "86400" successStatus = "201"; url = 'https://{bucket}.s3-{region}.amazonaws.com/'.format( bucket=AWS_UPLOAD_BUCKET, region=AWS_UPLOAD_REGION ) scope = [ AWS_UPLOAD_ACCESS_KEY_ID, shortDate, AWS_UPLOAD_REGION, service, requestType ] credentials = '/'.join(scope) dated = datetime.datetime.now().strftime('%Y%m%dT%H%M%SZ') policy_content = { 'expiration': tomorrow.isoformat(), 'bucket': AWS_UPLOAD_BUCKET, 'acl': 'private', 'upload_start_path': '', 'success_action_status': '201', 'credentials':credentials, 'algorithm':'AWS4-HMAC-SHA256', 'date': amz_date, #datetime.datetime.now().strftime("%Y%m%d"), 'expires': '86400' } policy_document = """ {"expiration": "%(expiration)s", "conditions": [ {"bucket": "%(bucket)s"}, {"acl": "%(acl)s"}, ["starts-with", "$Content-Type", ""], {"success_action_status": "%(success_action_status)s"}, {"x-amz-credential": "%(credentials)s"}, {"x-amz-algorithm": … -
Determine base64 uploaded file extension and mime type
I have a FileField Serializer for uploaded audio base64 upload, I noticed that the Base64 string does not start with data:****. How do I determine the Mime Type of the uploaded file? i_need_the_file_extension_mimetype() class AudioField(serializers.FileField): def to_internal_value(self, data): if isinstance(data, basestring): data = re.sub(r"^data\:.+base64\,(.+)$", r"\1", data) # Try to base64 decode the data url. try: decoded = base64.b64decode(data) except TypeError: raise serializers.ValidationError(_('Not a valid file')) file_name, file_ext, mime_type = self.i_need_the_file_extension_mimetype(decoded) data = ContentFile(decoded, name=file_name) return super(AudioField, self).to_internal_value(data) -
Django Models -- filtering on whether a tuple of fields is in a list of tuples
I have tried to simplify the example, but it is still a little convoluted. I suspect I may have to rewrite my models to better support this search. Say I have a Course model with associated days and start/end times. I also have a list of currently added Courses. I wish to return all Courses which don't conflict with my currently added Courses. The days are stored as a character field: "MoTuWeThFr" would represent a class taking place on every day of the week. The start and end time are each just a django date-time field. I am able to get a list of tuples of days and associated times that would conflict. For example, I could get the list [('Mo', 08:00, 10:00), ('We', 08:00, 10:00), ('Th', 12:00, 13:00)]. I need to return all Courses such that if its "days" field contains 'Mo', its start/end times don't overlap with (08:00, 10:00), and if it contains 'Th', its start/end times don't overlap with (12:00, 13:00), etc... I think could achieve filtering on just days or just times by using regular expressions. For example, if the "invalid" days are ['Mo', 'We', 'Th'], just write a regex expression that matches any string containing … -
Django Background Img CSS
My background image is not loading though my CSS file. It loads through the front end with: <img class="top" src={% static "/store/img/store.jpg" %}> inside of a div but not with: background: url('{{ STATIC_URL }}/store/img/store.jpg'); on the css file. My path is apps/store/static/store/img/store.jpg, so that's good. HTML: <div class="w3-display-container w3-content w3-wide" style="max-width:1600px;min-width:500px" id="home"> <div class="w3-display-bottomleft w3-padding-large w3-opacity"> <h1>SAN MIGUEL'S EXPORTA</h1> </div> </div> CSS: #home{ /* The image used */ background: url('{{ STATIC_URL }}/store/img/store.jpg') no-repeat; /* Full height */ height: 100%; /* Create the parallax scrolling effect */ background-attachment: fixed; background-position: center; background-size: cover; } -
how to import data from .csv file to django sqlite using import.py
i want to retrieve data from csv file but my hardware(RFID) output gives me two different entries of same employee for timein & timeout WorkNames.csv In this there are double entries i want only one row for one employee in models.py Employee class so please help in my METHOD1 by suggesting some code which can combine 2rows into one while transfering data into sqlite OR by helping in METHOD2 by suggesting some code to import data from output.csv METHOD 1: I used import.py to import data. Data is imported to sqlite but double entries import os import sys import csv from datetime import datetime project_dir='catalog' sys.path.append(project_dir) os.environ['DJANGO_SETTINGS_MODULE']='locallibrary.settings' import django django.setup() from catalog.models import employee1 data=csv.reader(open('locallibrary/WorkNames.csv'),delimiter=',') i=1 from datetime import datetime for row in data: if row[0]== '': break else: Employee1=employee1() Employee1.Date=row[0] Employee1.Name=row[1] Employee1.Number=row[2] if row[3] =="" or row[3]=='Time IN': Employee1.Time_IN='00:00:00 AM' else: Employee1.Time_IN=str(row[3]) if row[4] =="" or row[4]=='Time OUT': Employee1.Time_OUT='00:00:00 AM' else: Employee1.Time_OUT=str(row[4]) Employee1.save() **METHOD 2:but to get a timein timeout in row I generated a new file **output.csv the file is genrated properly but data is not importing from csv to sqlite import os import sys import csv from datetime import datetime project_dir='catalog' sys.path.append(project_dir) os.environ['DJANGO_SETTINGS_MODULE']='locallibrary.settings' import django django.setup() from … -
(Django) How to include template file from app into base.html in templates
I am building a site in Django CMS. In my templates directory for the project is base.html. I am writing an app "was_this_helpful" to add a dialog box on some pages for users to give feedback. I want to include a file from was_this_helpful/templates into base.html but it says the file does not exist. {% include 'was_this_helpful/dialog.html' %} My file structure look like this: - was_this_helpful - templates - was_this_helpful - dialog2.html - dialog.html - required app files I read somewhere that sometimes template files need to be another level deeper in templates to be found which is why I made the dialog2.html but still it's not working. I do not understand how to accomplish this. Based on what I've read it should work. Is it different because I'm not in another app, just the templates directory? -
TemplateDoesNotExist at / django
Got an error views.py: def index(request): user = request.user return render(request, 'main_app/index.html',{'user': user}) Tried this: 'DIRS': [os.path.join(BASE_DIR, 'templates')], But didn't help cmd: Internal Server Error: / Traceback (most recent call last): File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/exception.py", line 35, in inner response = get_response(request) File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py", line 128, in _get_response response = self.process_exception_by_middleware(e, request) File "/usr/local/lib/python3.4/dist-packages/django/core/handlers/base.py", line 126, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/ubuntu/workspace/main_app/views.py", line 10, in index return render(request, 'main_app/index.html',{'user': user}) File "/usr/local/lib/python3.4/dist-packages/django/shortcuts.py", line 36, in render content = loader.render_to_string(template_name, context, request, using=using) File "/usr/local/lib/python3.4/dist-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/usr/local/lib/python3.4/dist-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: main_app/index.html File structure: Django 2.0 Settings.py INSTALLED_APPS = [ # 'main_app.apps.MainAppConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'main_app' ] TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [os.path.join(BASE_DIR, 'templates')], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] -
Django nav bar doesn't show sometimes after refresh
http://vidaminds.com/test/ This is the web I am working on. And you can see a nav bar in the middle part. Or not after you refresh it. I think when you press command or ctrl and refresh the nav bar would show up or you can't control whether it would show or not. Even if it can't show the button is still there. You can still click it somewhere. I am really confused what happen. There is still a animation in the background to change the background. When the nav bar doesn't show, the background would not change as well. I write it in Django. This is part of the main.css file: @import url(font-awesome.min.css); @import url("https://fonts.googleapis.com/css?family=Source+Sans+Pro:300italic,600italic,300,600"); /* Dimension by HTML5 UP html5up.net | @ajlkn Free for personal and commercial use under the CCA 3.0 license (html5up.net/license) */ /* Reset */ html, body, div, span, applet, object, iframe, h1, h2, h3, h4, h5, h6, p, blockquote, pre, a, abbr, acronym, address, big, cite, code, del, dfn, em, img, ins, kbd, q, s, samp, small, strike, strong, sub, sup, tt, var, b, u, i, center, dl, dt, dd, ol, ul, li, fieldset, form, label, legend, table, caption, tbody, tfoot, thead, tr, th, td, … -
How to give "multiple" attribute to input file tag in jquery
Since I brought my HTML tags through Django form, I can't access the tags directly, so I wanna add some attributes through jQuery. Here's input tag <input id="id_photo" name="photo" type="file"> I wanna add multiple attribute to the input tag. So I did, $('#id_photo').attr('multiple'); But it doesn't work, what should I do? -
Django SearchRank performance with ranked annotations
I have a well-indexed postgres table with .5 million rows. Doing a direct ORM text search against its fields is lightning fast. However, I would like to get weighted and ranked search results (weighted relevancy). I am doing this: q_ = SearchQuery(val) qs = Location.objects.annotate( rank=SearchRank(vector, q_)).filter( rank__gte=0.1).order_by('-rank') (vector not shown) That works, and gives expected ranked results, but it's SLOW. The search time rises from fractional milliseconds to 5+ seconds when rank annotating and ordering is used. Again, I'm already fully indexed. Is there anything else that can be done to improve performance for weighted search results against large data sets in Django, shy of moving to ElasticSearch or similar? -
Security for publicly available api endpoint oauth2
We have few api end points which we use inside our apps (web & mobile) for the logged in user using token based authentication, but some of these end points are publicity available where users are not logged in (Guest users who don't have username or password). In this case how can I implement security to those end points which also need to be used for a logged in user too? -
Django rest framework: custom headers are different in client than unittests
I have a Django Rest API and then, separately, a client that consume this API. I pass a custom header using requests in the client: r = requests.get(url, params=params, headers={'license': '12345'}) Then in API, in my custom permission, I get the header like: app_license = request.META['HTTP_LICENSE'] I know django rewrites the custom headers for security reasons, so it works fine. My problem is when I write the unittests in Django rest API: response = self.client.get(self.url, params=params, headers={'license': '12345'}) Then it raise: KeyError: 'HTTP_LICENSE' But if I change the code like this, the test passes without problem but the consumer doesn't work: request.META['headers']['license'] I can check if there is 'headers' key or not but I don't want to change the code only to pass the unittest, it must be some way to write a unittest that matches reality, right? I tried to use: from django.test import TestCase And: from rest_framework.test import APITestCase Both with same result. There is any solution? Thank you! -
How to get humand readble month from django date field
I have defined month field in django models as: from django.utils.dates import MONTHS class Month(models.Model): month = models.IntegerField(choices=MONTHS.items(), blank=True, null=True) def __str__(self): return str(self.month) At the moment when I try to get output for the months, I'm getting integer for month like 1, 2, 3 ... 12. How can I get literal or human readable months like January, February etc. I can see its there because I can see them in admin tab. -
Is it possible to select a HTML tag in Django using python?
As it's clear from my question I'm a newbie. My question is; can I select a html tag with python in my own django project and then use that data? Should I use something like beautifulsoup or is there a library to manage this?Something like DOM management tool? -
django.db.utils.DataError: value too long for type character varying(2)
I've added the following to my User model: COUNTRIES = ( ('AD', _('Andorra')), ('AE', _('United Arab Emirates')), ('AF', _('Afghanistan')), ('AG', _('Antigua & Barbuda')), ('AI', _('Anguilla')), . . . ('YU', _('Yugoslavia')), ('ZA', _('South Africa')), ('ZM', _('Zambia')), ('ZR', _('Zaire')), ('ZW', _('Zimbabwe')), ('ZZ', _('Unknown or unspecified country')), ) class CountryField(models.CharField): def __init__(self, *args, **kwargs): kwargs.setdefault('max_length', 2) kwargs.setdefault('choices', COUNTRIES) super(CountryField, self).__init__(*args, **kwargs) def get_internal_type(self): return "CharField" class User(AbstractUser): ... country = CountryField() ... This is the migration created because of this change: class Migration(migrations.Migration): dependencies = [ ('users', '0006_auto_20180207_1902'), ] operations = [ migrations.AddField( model_name='user', name='country', field=pulsemanager.users.models.CountryField(choices=[('AD', 'Andorra'), ('AE', 'United Arab Emirates'), ('AF', 'Afghanistan'), ('AG', 'Antigua & Barbuda'), ('AI', 'Anguilla'), ('AL', 'Albania'), ('AM', 'Armenia'), ('AN', 'Netherlands Antilles'), ('AO', 'Angola'), ('AQ', 'Antarctica'), ('AR', 'Argentina'), ('AS', 'American Samoa'), ('AT', 'Austria'), ('AU', 'Australia'), ('AW', 'Aruba'), ('AZ', 'Azerbaijan'), ('BA', 'Bosnia and Herzegovina'), ('BB', 'Barbados'), ('BD', 'Bangladesh'), ('BE', 'Belgium'), ('BF', 'Burkina Faso'), ('BG', 'Bulgaria'), ('BH', 'Bahrain'), ('BI', 'Burundi'), ('BJ', 'Benin'), ('BM', 'Bermuda'), ('BN', 'Brunei Darussalam'), ('BO', 'Bolivia'), ('BR', 'Brazil'), ('BS', 'Bahama'), ('BT', 'Bhutan'), ('BV', 'Bouvet Island'), ('BW', 'Botswana'), ('BY', 'Belarus'), ('BZ', 'Belize'), ('CA', 'Canada'), ('CC', 'Cocos (Keeling) Islands'), ('CF', 'Central African Republic'), ('CG', 'Congo'), ('CH', 'Switzerland'), ('CI', 'Ivory Coast'), ('CK', 'Cook Iislands'), ('CL', 'Chile'), ('CM', 'Cameroon'), ('CN', 'China'), ('CO', … -
The current path, admin, didn't match any of these. django
I use django 2.0 my urls.py file: """django_direct URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/1.9/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: url(r'^$', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: url(r'^$', Home.as_view(), name='home') Including another URLconf 1. Add an import: from blog import urls as blog_urls 2. Import the include() function: from django.conf.urls import url, include 3. Add a URL to urlpatterns: url(r'^blog/', include(blog_urls)) """ from django.conf.urls import url,include from django.contrib import admin from main_app import views urlpatterns = [ url('^admin/', admin.site.urls), # url(r'^/', include('main_app.urls')), url('/', views.index), ] -
django static files not appearing with virtual environment
So I'm trying to push my website into production, but I have encountered a problem while in the virtual environment, where my static files are not being found (404 errors). In the settings.py file, I have STATIC_ROOT = os.path.join(BASE_DIR, 'static/'). In the file /etc/nginx/sites-available/django, I have modified the static files location, to look like this: location /static { alias /home/user/myproject/static; } In the directory /home/user/myproject, I have another directory called static, and inside are several directories holding the actual static files. i.e. /home/user/myproject/static/shopApp/shop_app.css or i.e. /home/user/myproject/static/officeApp/office_app.css What I am trying to see is if any of my configurations are set up badly. I am very new to django and web development, so I would appreciate any of your help!