Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Regex matching long url
I have this long url and I want to match the string after ? and have it available in self.kwargs of Class Based View. new_timer/?UID=046F1572564080&runtime=1102&seconds=30stillrunning=1&numstoredtimes=3&storedtimes=13:2-23:32-48:43&checksum=71 I tried the following and it's not working. Urlpatterns = [ # bunch of awesome urls url(r'^new_timer/(?P<params>[^/]+)/$',NewTimerView.as_view(), name='new_timer'), ] What am I doing wrong? -
Save values in database with input type text django
I have a problem, create a template in which I have a table and after the assigned artifacts shows so many records in this with the name, code and the amount of which can enter or modify in a input text template: <form id="myform" method="POST"> <table id="example" class="table table-border table-striped table-hover"> <thead> <tr> <td>Especialidad</td> <td>Cod experto</td> <td>Nombre</td> <td>Cantidad</td> </tr> </thead> <tfoot> <tr> <td>Especialidad</td> <td>Cod experto</td> <td>Nombre</td> <td><input type="submit" class= "btn btn-primary" value="Guardar"></td> </tr> </tfoot> <tbody> {% if pedido %} {% for ped in pedido %} <tr> <td>{{ ped.especialidad.nombre }}</td> <td>{{ ped.articulo.cod_experto }}</td> <td>{{ ped.articulo.nombre }}</td> {% csrf_token %} <td><input type="text" name="cantidad" value="{{ ped.cantidad }}" ></td></td> </tr> {% endfor %} {% endif %} </tbody> </table> </form> At the time of entering a value in each input text, this only takes the last value example: 3 and this number is for all articles and does not save the corresponding value entered for each article. views.py: def ListEspeci(request, id_especialidad): pedido = Pedido.objects.filter(especialidad=especialidad) for cants in request.POST.get('cantidad'): ped = Pedido.objects.filter(especialidad=especialidad).update(cantidad=cants) return render(request, 'ingresa.html', {'pedido':pedido}) Please do not know what the mistake is, I humbly ask for your help! -
How to disable the cache for django-cms AppHooks?
I'm working on a page where i have an event-list page (future events) and an event-review page (past events, archive). On both pages i work with an django-cms AppHook because i also have detail views. The day after the event the event should be hidden on the event list and visible on the event review page. But the problem is that the event is still in the event-list-page. models.py # Managers class EventsManager(models.Manager): """EventsManager.""" def get_all(self): return super(EventsManager, self) \ .filter(is_visible=True) \ .order_by('-date') def get_all_future(self): return super(EventsManager, self) \ .filter(is_visible=True) \ .filter(date__gte=datetime.datetime.now()) \ .order_by('date') def get_all_past(self): return super(EventsManager, self) \ .filter(is_visible=True) \ .filter(date__lt=datetime.datetime.now()) \ .order_by('-date') views.py class EventListView(ListView): template_name = 'event_list.html' queryset = Events.objects.get_all_future() paginate_by = 10 @never_cache def dispatch(self, *args, **kwargs): return super(EventListView, self).dispatch(*args, **kwargs) class EventArchiveView(ListView): template_name = 'event_archive.html' queryset = Events.objects.get_all_past() paginate_by = 20 @never_cache def dispatch(self, *args, **kwargs): return super(EventArchiveView, self).dispatch(*args, **kwargs) def get_context_data(self, **kwargs): context = super(EventArchiveView, self).get_context_data(**kwargs) context['is_arcive'] = True return context I tried to use @never_cache but the event is still on the event-list page. I think it's a caching issue but i'm not really sure where to start searching. Any suggestions? -
Django Upgrade terminates with "Killed"
I am trying to upgrade to the latest Django 1.10 from 1.9.6 using: sudo pip install -U Django However, when i do I just get the following: The directory '/home/tingeyal/.cache/pip/http' or its parent directory is not owned by the current user and the cache has been disabled. Please check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. The directory '/home/tingeyal/.cache/pip' or its parent directory is not owned by the current user and caching wheels has been disabled. check the permissions and owner of that directory. If executing pip with sudo, you may want sudo's -H flag. Collecting Django Downloading Django-1.11.1-py2.py3-none-any.whl (6.9MB) 99% |████████████████████████████████| 6.9MB 40.2MB/s eta 0:00:01Killed Tried a quick google and looked through the django docs to no avail. Any thoughts? -
Enforce form field validation & display error without render?
I'm a django newbie so a verbose answer will be greatly appreciated. I'm enforcing a capacity limit on any newly created Bottle objects in my model, like so: class Bottle(models.Model): name = models.CharField(max_length=150, blank=False, default="") brand = models.ForeignKey(Brand, on_delete=models.CASCADE, related_name="bottles") vintage = models.IntegerField('vintage', choices=YEAR_CHOICES, default=datetime.datetime.now().year) capacity = models.IntegerField(default=750, validators=[MaxValueValidator(2000, message="Must be less than 2000") ,MinValueValidator(50, message="Must be more than 50")]) My BottleForm looks like so: class BottleForm(ModelForm): class Meta: model = Bottle fields = '__all__' My view (with form validation logic based on this answer): def index(request): args = {} user = request.user object = Bottle.objects.filter(brand__business__owner_id=user.id).all(). \ values('brand__name', 'name', 'capacity', 'vintage').annotate(Count('brand')).order_by('brand__count') args['object'] = object if request.method == "POST": form = BottleForm(request.POST) if form.is_valid(): bottle = form.save(commit=False) bottle.save() return redirect('index') else: form = BottleForm() args['form'] = form return render(request, template_name="index.pug", context=args) And my template (in pug format), like so: form(class="form-horizontal")(method="post" action=".") | {% csrf_token %} for field in da_form div(class="form-group") label(class="col-lg-3 col-md-3 col-sm-3 control-label") {{field.label_tag}} div(class="col-lg-9 col-md-9 col-sm-9") | {{ field|add_class:"form-control" }} input(class="btn btn-primary")(type="submit" value="submit") After a few hours of messing with my code and browsing SO, I managed to display the error by adding {{ form.errors }} to my template, but that only shows after the page has already been … -
Nginx/Gunicorn timeout when running query that takes 3+ minutes to complete on django
I'm running a query that takes maximum 3 minutes to complete with django, using connections['report'].cursor() When I make a request to the view that execute that query, Nginx give me a timeout (that is presented in the view as "502 Bad Gateway"). What approach should I choose to overcome this issue? Should I increase the timeout setting or how can I make this asynchronous? -
Programmatically create a user with social-auth-app-django
I'm using social-auth-app-django (formerly python-social-auth) so that users can log in with Google OAuth2. However, I don't want anyone with a Google account to be able to log in. I want to programmatically create a user, e.g. create_user(email=johnsmith@gmail.com), and then that User will exist even if John Smith has never tried to log in yet. Then, John Smith will be able to use his Google account to log in to that User account. Thank you! -
Django Collectstatic Files from a Single App
I am wondering if it is possible to limit the domain of the collectstatic command down to the files from 1-2 apps? I am aware of the exclusion using the -i flag, but I have way too many apps in the project now; manually specifying the exclusions is not an option. -
Django - Getting records from first table based on Second table' field value
I am developing a Django App, in which I have used PostgreSQL as a Database. The models in the Application are as follow. class topics(models.Model): topicid = models.IntegerField() topicname = models.CharField(max_length=512) topicdescription = models.CharField(max_length=512) class Video(models.Model): video_file_name = models.CharField(max_length=100) video_url = models.CharField(max_length=100, default='default.mp4') video_description = models.CharField(max_length=2000, default='Video Description') video_topic_id = models.IntegerField(default=1) Here, one topic will have 0 or many videos under it. The query condition is, I want the topic list uniquley, which will have atleast one video(more than zero). Means I have to ignore the topics in results which are not having any video under that topic. Currently I use a single get all function. all_topics = topics.objects.all(); -
Django: request.user.user_permissions is always None
I have created a user and assigned it to a group from django admin panel. I have given certain permissions to that group. However, when I catch the request in my view, it seems that the associated user has no permission at all. I'm using JWT web token based authentication system. Any ideas? -
django python manage.py runserver encounter "no module named xxx"
I am new to learn django and I met this error: no module named blog after typing python manage.py runserver. the 'blog' is the app that I configured in the settings.py file, I think this probably is because my project package isn't in sys.path. But I found documentation that says that manage.py will take care of that and will also confirm the DJANDO-SETTING-MODULE pointing to my settings.py file. So I couldn't understand why this error. Any help would be appreciated. Here is the error msg -
django template errno 13
I have a problem with django template. I made new template file in pycharm and in code i think all is good. But i have errno 13 permission denied. Other templates are working fine. Environment: Request Method: GET Request URL: http://127.0.0.1:8000/Doggo/2/results/ Django Version: 1.11 Python Version: 3.6.1 Installed Applications: ['Doggo.apps.DoggoConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback: File "C:\Python36-32\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request) File "C:\Python36-32\lib\site-packages\django\core\handlers\base.py" in _get_response 215. response = response.render() File "C:\Python36-32\lib\site-packages\django\template\response.py" in render 107. self.content = self.rendered_content File "C:\Python36-32\lib\site-packages\django\template\response.py" in rendered_content 82. template = self.resolve_template(self.template_name) File "C:\Python36-32\lib\site-packages\django\template\response.py" in resolve_template 64. return select_template(template, using=self.using) File "C:\Python36-32\lib\site-packages\django\template\loader.py" in select_template 48. return engine.get_template(template_name) File "C:\Python36-32\lib\site-packages\django\template\backends\django.py" in get_template 39. return Template(self.engine.get_template(template_name), self) File "C:\Python36-32\lib\site-packages\django\template\engine.py" in get_template 162. template, origin = self.find_template(template_name) File "C:\Python36-32\lib\site-packages\django\template\engine.py" in find_template 136. name, template_dirs=dirs, skip=skip, File "C:\Python36-32\lib\site-packages\django\template\loaders\base.py" in get_template 38. contents = self.get_contents(origin) File "C:\Python36-32\lib\site-packages\django\template\loaders\filesystem.py" in get_contents 28. with io.open(origin.name, encoding=self.engine.file_charset) as fp: Exception Type: PermissionError at /Doggo/2/results/ Exception Value: [Errno 13] Permission denied: 'C:\\Users\\noob1_000\\PycharmProjects\\eWybory\\Doggo\\templates' i think i have permission to this folder because other templates are working. I'm working on windows 10 -
Efficient data structure for storing dates/statuses in SQLite database?
I'm using Django 1.10, Python 2.7, and SQLite3 to build a web app that keeps track of the status of an object and when it was last changed. For example, every 24 hours, the user will import a list (such as the one below) of open ports for a host: 05/01/2017 ========== Host Open-Ports 123.45.67.89 22, 80, 443 ... ... A port (or multiple ports) may close one day: 05/02/2017 ========== Host Open-Ports 123.45.67.89 443 ... ... I want my Django app to display this data: IPv4 123.45.67.89 Ports 22 [Closed on 05/02/2017] 80 [Closed on 05/02/2017] 443 [Open] What would be the most efficient way of keeping track of the status of ports? Currently, I have a Host model with the following fields: IPv4 Address (GenericIPAddressField) Host Name (CharField) Location (CharField) What new field (and its type) should I add to accomplish this goal? This information will be stored in a SQLite3 database. How should my SQL table be setup? How should I compare the dates to know when a port is closed? Will I need two tables to store today's info and yesterday's? There could potentially be 100,000+ hosts, so I would need this method to be as … -
makemigrations not detecting new models
Django 1.11. I recently added the following module to myapp.models: from django.db import models from ordered_model.models import OrderedModel from .songs import Song class Service(models.Model): name = models.CharField(max_len=200, unique=True) date = models.DateField(blank=True) items = models.ManyToManyField(ServiceItem) class Meta: ordering = ('-date', 'name') class ServiceItem(OrderedModel): item = models.ForeignKey(Song) song_custom_order = models.CharField(max_len=50, blank=True) order_with_respect_to = 'service' class Meta(OrderedModel.Meta): pass I have other models in another module (in the same directory). When I run ./manage.py makemigrations, the script finds my changes in my other module, but not in this one. FWIW, this module is all new code with no previous migration history. Any ideas why these changes aren't getting picked up? -
Azure slow response time in Django web app
For a long time I've been managing an Azure web site in testing, staging and production environments. Initially, all of them were free and I noticed the server sometimes was very slow to respond to async requests. Some requests took 15-30 seconds to complete on the Azure web site. A local copy running on IIS worked with no problem and request times ranged from 75ms to 400ms. At first I thought the problem with the Azure websites was the 'Always on' feature but after upgrading the production server to a Standard 2 level the exact same problems still exist. Recently I ran a profile with Application Insights and the report for the slow requests shows something named ASYNC_UNKOWN and those 15-30 seconds are there, the actual request only takes a few ms. CPU and memory look fine from the insights live data when those delays happen. I don't know what else to do, I'm thinking about dropping Azure and go to some other hosting. I tried hosting the development site on pythonanywhere and it works just fine there. Can someone give me a clue about what could be causing this massive delays on Azure? -
Why Django lowercases only the domain part of email addresses in normalize_email?
I've noticed that somebody has managed to register twice in a website that is made with Django with one email, Foo@example.com and foo@example.com. I checked the code and found out that there's a class method in BaseUserManager named normalize_email that, according to the documentation, ... Normalizes the email address by lowercasing the domain part of it. I understand that the email address may be something like JaneDoe@example.com and if the part preceding @ is transformed too it would omit the distinction between the first and last name. Yet the problem described above rises. Why doesn't it non-case-sensitively check uniqueness of the email addresses later? Does it have a reasonable explanation or is it a bug that has to be reported and fixed? -
Static files like images doest not found on heroku while i update it
Currently i am working on django and angular 2. what i am performing is. i am uploading image in folder in django directory and saving that path in database. all works fine and it shows me image from that link. but whenever i update django project, old uploaded files/images doestn't exists more. Can anyone tell me why old images from folder no more exists. what should i do to store permanently on server. can anyone suggest me something. Here it is my settings.py """ Django settings for SNR project. Generated by 'django-admin startproject' using Django 1.11. For more information on this file, see https://docs.djangoproject.com/en/1.11/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.11/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.11/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '#u#9-1dttxl=y2-lfdxsh3udk+k51lyf9z5500@mva4w*(8sus' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'corsheaders', 'django.contrib.sessions', 'django.contrib.messages', 'rest_framework', 'mobile.apps.MobileConfig', 'laptop.apps.LaptopConfig', 'django.contrib.staticfiles', ] MIDDLEWARE_CLASSES = [ 'corsheaders.middleware.CorsMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_ALLOW_ALL=True … -
Django undirected unique-together
I want to model pair-wise relations between all members of a set. class Match(models.Model): foo_a = models.ForeignKey(Foo, related_name='foo_a') foo_b = models.ForeignKey(Foo, related_name='foo_b') relation_value = models.IntegerField(default=0) class Meta: unique_together = ('ingredient_a', 'ingredient_b') When I add a pair A-B, it successfully prevents me from adding A-B again, but does not prevent me from adding B-A. I tried following, but to no avail. unique_together = (('ingredient_a', 'ingredient_b'), ('ingredient_b', 'ingredient_a')) -
TypeError: descriptor 'get' requires a 'dict' object but received a 'str'
This should be simple question. I am using facebook social authentication from django-allauth. However, the latest installation of django-allauth(0.32.0) gives me an error message-"TypeError: descriptor 'get' requires a 'dict' object but received a 'str'". The specific location of the error is in the allauth/socialaccount/providers/facebook/provider.py file. I suppose the django-allauth package should work without tinkering/any changes. The relevant line of code in provider.py : GRAPH_API_VERSION = getattr(settings, 'SOCIALACCOUNT_PROVIDERS', {}).get( 'facebook', {}).get('VERSION','v2.4') GRAPH_API_URL = 'https://graph.facebook.com/' + GRAPH_API_VERSION I tried last .get to make it dictionary but no success. -.get({'VERSION':'v2.4'}) How do i change the descriptor from 'str' to 'dict', or whether i even need to make changes to the package? -
Django rawSQL in migration : error in your SQL syntax, but SQL is correct
I have a very tiny migration that looks like this for my django app (mysql backend) operations = [ migrations.CreateModel( name='Mileage', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('miles', models.DecimalField(max_digits=8, decimal_places=1)), ('start_location', models.CharField(max_length=255)), ('end_location', models.CharField(max_length=255)), ], ), migrations.CreateModel( name='Trip', fields=[ ('id', models.AutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID')), ('start_location', models.CharField(max_length=255)), ('end_location', models.CharField(max_length=255)), ('trip_date', models.DateTimeField(verbose_name='trip date')), ], ), migrations.RunSQL('mymileages.sql'), ] The mymileages.sql file looks like this: INSERT INTO `mileage_mileage` (`miles`, `start_location`, `end_location`) VALUES (3.7, 'Location 1', 'Location A'), (2.4, 'Location 2', 'Location B'), (4.3, 'Location 3', 'Location C'); I can run that SQL outside of the migration and it works fine and without issue. When I run the migration however, it gives me the error: Programming error: (1064, "You have an error in your SQL syntax; check the manual that corresponds to your MariaDB server version for the right syntax to use near 'mymileages.sql' at line 1") -
Fail to deploy to Azure a simple django webapp that works well on local machine
I have a simple Django webapp that works like a charm on my machine. However, when I tried to publish it to Azure Webapp using VS 2015 (by right click the project then click Publish button), it turns out a run time error: Then I tried to fix by add "< customErrors mode="Off"/>" to the web.config file. It turns out another error: Server Error in '/' Application. Couldn't find type for class Microsoft.WindowsAzure.Diagnostics.DiagnosticMonitorTraceListener, Microsoft.WindowsAzure.Diagnostics, Version=1.0.0.0, Culture=neutral, .. I tried the this and this tutorial but they do not help. I do not know whether these documents are out of date of not. Please save my day. -
Django, loop in model declaration
I just start my journey with Django and i have problem with Choice Field. I wanna wanna make Model in some ChessGame and i have to make Choice Field through ChessBoard. I have something like this: move = { ('a1', 'a1'), ('b1', 'b1'), etc. Is it possible more simple declaration of this code? Maybe some for loop? -
Mirroring click events between two drop boxes using jquery
I have a select dropdown that i needed to style, so i created a new dropdown using divs but the button used to click next is linked to select and option tags. I am trying to get the select dropbox to mimic the clicks of the div dropbox. so if i click on an option in the div, it will also click the select dropbox option that has the same value. this is what i have so far, i've tried doing several different things and am stuck! This is the new div-- inside of componentDidMount is what i am trying to do to create this mirroring effect. I tried using trigger but its hard to target a div with a value that is random every time. /* eslint-disable */ import React from 'react'; import $ from 'jquery'; class SelectInput extends React.Component { constructor(props) { super(props); this.handleSelectChange = this.handleSelectChange.bind(this); } componentDidMount(){ $('.sel').click(function(){ $('#arrow').css('transform', 'rotate(180deg)'); }); console.log('component mounted') let sel = $('.sel'), txt = $('.txt'), options = $('.form-select'); sel.click(function (e) { e.stopPropagation(); options.show(); }); $('body').click(function (e) { options.hide(); }); options.children('div').click(function (e) { e.stopPropagation(); txt.text($(this).text()); $(this).addClass('selected').trigger('classChange').siblings('div').removeClass('selected'); // console.log($(this).addClass('selected').siblings('div').removeClass('selected'), 'hello') options.hide(); $('#arrow').css('transform', 'rotate(360deg)'); }); let select = $('.option-div'); let selected = $('.option-div selected') let … -
Pytest Django import error -
I'm working on a short example to try Pytest in Django 1.8.18. The code in polls/test_question.py is as follows: import datetime from django.utils import timezone from .models import Question def test_was_published_recently_with_future_question(): time = timezone.now() + datetime.timedelta(days=30) future_question = Question(pub_date=time) assert future_question.was_published_recently() == False Upon running pytest in a shell session, I get the following: (django_pytest) ➜ mysite pytest ======================================================================================================= test session starts ======================================================================================================= platform darwin -- Python 2.7.13, pytest-3.0.7, py-1.4.33, pluggy-0.4.0 rootdir: /Users/am034402/Workspace/small_projects/mysite, inifile: plugins: django-3.1.2 collected 0 items / 1 errors ============================================================================================================= ERRORS ============================================================================================================== _____________________________________________________________________________________________ ERROR collecting polls/test_question.py _____________________________________________________________________________________________ ImportError while importing test module '/Users/am034402/Workspace/small_projects/mysite/polls/test_question.py'. Hint: make sure your test modules/packages have valid Python names. Traceback: polls/test_question.py:2: in <module> from django.utils import timezone E ImportError: No module named django.utils !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! Interrupted: 1 errors during collection !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! ===================================================================================================== 1 error in 0.11 seconds ===================================================================================================== If I start a python session in that shell using the same virtualenv, I am able to import django.utils without incident. I also based my test off of the same code (more or less) in the Django tutorial that uses unittest, which works fine. pytest.ini is as follows: [pytest] DJANGO_SETTINGS_MODULE = mysite.settings python_files = tests.py test_*.py *_tests.py pip freeze shows the following: (django_pytest) ➜ mysite pip … -
Django Form: Select from existing or create (related object)
I currently have a standard Bottle form: class BottleForm(ModelForm): class Meta: model = Bottle fields = '__all__' Which renders like this in my view: In my model declaration, each bottle has one brand, and so the form correctly lets the user choose a Brand from the available ones in my database. But it currently doesn't let them create new brand. My question is how can I have, in similar vein to what's available in the Django admin, a drop-down-menu that lets one choose from existing brands, or create a new one and associate it with the to-be-created Bottle object?