Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why doesn't Django's select_for_update raise an exception with unsupported backends?
The Django docs for select_for_update say Using select_for_update() on backends which do not support SELECT ... FOR UPDATE (such as SQLite) will have no effect. SELECT ... FOR UPDATE will not be added to the query, and an error isn’t raised if select_for_update() is used in autocommit mode. This strikes me as an odd and potentially dangerous decision, especially since select_for_update is used to lock rows. If I write code that uses select_for_update, I would rely on it actually being honored! If the DB backend doesn't support it, I would expect Django to either fall back to a safe-but-less-efficient alternative or, if one doesn't exist, to throw an exception of some kind. In this case it seems like Django could suddenly and silently reintroduce race conditions by just ignoring select_for_update where it's not supported (such as SQLite). My intuition says Django wouldn't do that and there must be some type of fallback or reason why it's not needed (perhaps complete database locking?) but I can't seem to find anything concrete in the docs to back up that theory. This is making me very leery of using select_for_update even though it would solve some current problems nicely. -
How user can upload video in django
I am creating web app in which I want user to upload video file. Can somebody help me with sample code or if you have any links please share. Thank you in advance. -
How can I convert the data to that type?
How can I convert this list data : [ { "home_page_second_module__name": "云主机", "home_page_second_module__home_page_first_module__name": "产品", "id": 1, "name": "云主机子1" }, { "home_page_second_module__name": "云主机", "home_page_second_module__home_page_first_module__name": "产品", "id": 4, "name": "云主机子4" }, { "home_page_second_module__name": "云硬盘", "home_page_second_module__home_page_first_module__name": "产品", "id": 2, "name": "云硬盘子2" }, { "home_page_second_module__name": "云硬盘", "home_page_second_module__home_page_first_module__name": "产品", "id": 3, "name": "云硬盘子3" } ] to this: [ {"name":"产品", "data":[ {"name":"云主机", "data":[{"name":"云主机子1", "data":{"id":1}}, {"name":"云主机子2", "data":{"id":2}}]}, {"name":"云硬盘", "data":[{"name":"云硬盘子1", "data":{"id":3}}, {"name":"云硬盘子2", "data":{"id":4}}]} ] } ] There should has a arithmetic method to do this, but I tried, do not get that. I only think of this below little things: home_page_second_module__name_list = [] home_page_second_module__home_page_first_module__name_list = [] id_list = [] name_list = [] for home_page_second_module__name,home_page_second_module__home_page_first_module__name,id,name in ori_list: if not (home_page_second_module__name_list.__contains__(home_page_second_module__name)): home_page_second_module__name_list.append(home_page_second_module__name) if not (home_page_second_module__home_page_first_module__name_list.__contains__(home_page_second_module__home_page_first_module__name_list)): home_page_second_module__home_page_first_module__name_list.append(home_page_second_module__home_page_first_module__name) But now I think this is very difficult to do that, and I think mine is wrong way to do that. Is there a convenient way to realize it? -
Can flask be used to develop single page applications?
Can I use flask to develop a single page application? What are the pros and cons of using Flask as opposed to django? -
How to edit UserCreationForm password advice?
When I create a registration form that inherits from UserCreationForm, the text "Your password can't be too similar to your other personal information. Your password must contain at least 8 characters. Your password can't be a commonly used password. Your password can't be entirely numeric." always appears under the password input fields and takes up quite a bit of space. Is there a way I can remove this? -
Django migrations changing choices value
A field has been added to one of my MySQL table previously: # -*- coding: utf-8 -*- # Generated by Django 1.9.7 on 2017-09-14 00:49 from __future__ import unicode_literals from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ('my_app', '0102_previous_migrations'), ] operations = [ migrations.AddField( model_name='my_client', name='my_team', field=models.CharField(choices=[('Unassigned', 'Unassigned'), ('ACT', 'ACT'), ('Korea', 'Korea'), ('National', 'National')], default='Unassigned', max_length=255, verbose_name='My Team'), ), ] So users have a choices of the above selection in my UI and will be saved into the table my_client: Unassigned ACT Korea National The changes have been deployed and now a beginner like me would like to change, i.e. remove Korea and add 2 new choices: NSW and SA How would I go about this? Do I need another migration or I will just need to change those choices in the models? I use this in my model now like this: class Client(MyAppModel): TEAM_CHOICES = ( ('Unassigned', 'Unassigned'), ('ACT', 'ACT'), ('Korea', 'Korea'), ('National', 'National'), ) DEFAULT_TEAM = 'Unassigned' my_team = models.CharField(verbose_name='MyTeam', null=False, max_length=255, choices=TEAM_CHOICES, default=DEFAULT_TEAM) -
Angular 4 with Django - Development Environment
I am building an Angular4 application using Django rest_framework as a backend. I like having the browser automatically refresh to display my changes when working on my angular application. So I spin up both the Django server via python manage.py runserver and the angular dev server by running npm start. I have setup my environment/environment.prod.ts and environment/environment.dev.ts files to point to the proper API source as necessary. After sorting out CORS I am running into a CSRF token issue. I have configured Django to use angular's default CSRF cookie/response header names of XSRF-TOKEN/X-XSRF-TOKEN respectively. All this is working just fine. Where the issue lies is that Angular does not automatically read the X-XSRF cookie or return the header. Ok, that's fine, I can write an interceptor to do that for me. And that would be OK - except that I cannot access the response headers in the interceptor... import {DOCUMENT, ɵparseCookieValue as parseCookieValue} from '@angular/common'; import {Inject, Injectable, InjectionToken, PLATFORM_ID} from '@angular/core'; import {Observable} from 'rxjs/Observable'; import { HttpRequest, HttpHandler, HttpEvent, HttpResponse, HttpInterceptor, HttpXsrfTokenExtractor } from '@angular/common/http'; /** * `HttpInterceptor` which adds an XSRF token to eligible outgoing requests. */ @Injectable() export class DevHttpXsrfInterceptor implements HttpInterceptor { constructor( private tokenService: … -
django product price tracker: getting the amount and date of the all time maximum and minimum prices
I'm trying to build a django app where I can track product prices over time. The app fetches new prices routinely, graphs them and shows the recent history of price changes. I'm checking the price once a day and saving that price plus the date timestamp to my models. models.py Class Product(models.Model): title = models.CharField(max_length=255) Class Price(models.Model): product = models.ForeignKey(Product, on_delete=models.CASCADE) date_seen = models.DateTimeField(auto_now_add=True) price = models.IntegerField(blank=True, null=True) Along with the current price of a product I'd also like to show the max and min over all the price data I've collected. I want to get the value and also the date it was at that value. So far I can get the value but I can't get the corresponding date. I'm using this: def price_hla(self): return Product.objects.filter(price__product=self).aggregate(high_price=Max('price__price'), low_price=Min('price__price'), avg_price=Avg('price___price')) Any advice? Thanks! -
Adding placeholder to django-taggit field - TaggableManager()
I have this model with a TaggableManager() field: class MyModel(models.Model): knowledge_topics = TaggableManager( verbose_name="Áreas de conocimiento", help_text=_("Una lista de temas separada por comas.") ) I want add placeholder to knowledge_topics field, then my form is: class MyModelForm(forms.ModelForm): title = "Detalles del anfitrión de estudios" knowledge_topics = forms.CharField(label='Áreas de conocimiento', widget=forms.TextInput(attrs={ 'placeholder': 'Una lista de temas separada por comas'})) class Meta: model = MyModel fields = ('knowledge_topics',) But when I go to my form, the placeholder does not works of a suited way: -
will django uwsgi request continue after incoming request closes the connection
I have a web service. Incoming http request goes through an oauth server, then haproxy, then a django/uwsgi. My API is to make a http call another server to get data, write to db, then return data to the original caller. Assume the call to another http server takes 90 sec but the oauth server cut the connection after 60 sec. Will the api continues the effort and eventual finishes writing the data into db? or the api will end immediately after the incoming request closes the connection? Thanks. -
Filtering results of multiple models under one API Endpoint with django-rest-framework
I am using DRF to generate API for my django app. I am using the ViewSet class and exposing API endpoints for most of my models at their own path. I want to allow viewing of my Endpoint and TLSCertificate models at an /assets/ path. As they are both children of an Organisation entity, I want to allow the results to be filtered Organisation. So far I have: serializers.py class AssetSerializer(serializers.Serializer): endpoints = EndpointSerializer(many=True) certificates = TLSCertificateSerializer(many=True) views.py class AssetFilterSet(filters.FilterSet): organisation = filters.ModelChoiceFilter( name='organisation', queryset=Organisation.objects.all()) project = filters.ModelChoiceFilter( name='project', queryset=Project.objects.all()) class Meta: model = Endpoint fields = ['organisation', 'project'] # the object type to be passed into the AssetSerializer Asset = namedtuple('Asset', ('endpoints', 'certificates')) class AssetViewSet(CacheResponseAndETAGMixin, viewsets.ViewSet): """ A simple ViewSet for listing the Endpoints and Certificates in the Asset list. Adapted from https://stackoverflow.com/questions/44978045/serialize-multiple-models-and-send-all-in-one-json-response-django-rest-framewor """ # TODO filtering not functional yet filter_class = AssetFilterSet filter_fields = ('organisation', 'project',) queryset = Endpoint.objects.all() def list(self, request): assets = Asset( endpoints=Endpoint.objects.all(), certificates=TLSCertificate.objects.all(), ) serializer = AssetSerializer(assets, context={'request': request}) return Response(serializer.data) This works in returning the objects but does not allow for filtering to take place. I would appreciate any guidance in how to enable the filtering in this situation? -
How to target a Django form with jQuery
I'd like to target my django form with jQuery, but differently of a html select tag, I don't have a class to do that. Could someone help me? Ps: I'm a beginner on programming. <!-- Selection Box --> <div> <form action="" method="post">{% csrf_token %} {{selectfield}} <!-- my form --> <button type="submit">Save</button> </form> </div> <!-- End of Selection Box --> <!-- Jquery Select2 --> <script type="text/javascript"> $(document).ready(function(){ $('.target').select2({ placeholder: "Select here", maximumSelectionSize: 100}); }) </script> <!-- End of JQuery Select2 --> -
Pin only one post in Django-powered blog
I've managed to pin posts on the index page as I wanted to. Thing is, I would like to be able to pin only one post. What I have done is create two methods, one to pin, and another to unpin, the two being BooleanFields. What I would like to do is to, like in Twitter, when you pin one post, the other one before it loses its pinned status, and the just-pinned one takes its place. For now I can manage to pin several things at once. -
Django: Top navigation bar refreshes (flickers) when clicking on menu items
I have developed a Django app with a fixed top navbar, but it sometimes flickers / refreshes when clicking the menu items. Have I made a mistake in extending the templates or it is something else causing this? Here is the app deployed that you can see it: http://azeribocorp.pythonanywhere.com/index/ __base.html: {% load staticfiles %} <!DOCTYPE html> <html lang="en" class="no-js"> <head> {% block meta_tags %}{% endblock meta_tags%} <title> {% block title %}Azeribo Tracking{% endblock title %} </title> {% block stylesheets %} {% endblock stylesheets %} {% block js %} {% endblock js %} </head> <body> <header class="topnavbar" id="TNB" > {% include 'aztracker/_topnavbar.html' %} </header> <div id="main" role="main"> <div class="container"> {% block content %} {% endblock content %} </div> </div> {# /#main #} </body> </html> search_form.html: {% extends 'aztracker/__base.html' %} {% load staticfiles %} {% load static %} {% block stylesheets %} <link rel="stylesheet" type="text/css" href="{% static 'css/__main.css' %}"> <link rel="stylesheet" type="text/css" href="{% static 'css/search_form.css' %}"> {% endblock %} {% block content %} {% block main_col %} <section class="search_section"> <form method="POST" action="/search/"> {% csrf_token %} <input required type="search" placeholder="Country or Code" name="search_input_field" id="search_input"> <button id="search_btn" class="flat_button">Search</button> </form> </section> <!-- view all country codes link --> <div class="wrapper"> <a id="list_of_all_countries_link" href="/countries/"> List of … -
Store a Python exception in a Django model
What is the recommended way to store a Python exception – in a structured way that allows access to the different parts of that exception – in a Django model? It is common to design a Django model that records “an event” or “an attempt to do foo”; part of the information to be recorded is “… and the result was this error”. That then becomes a field on the model. An important aspect of recording the error in the database is to query it in various structured ways: What was the exception type? What was the specific message? What were the other arguments to the exception instance? What was the full traceback? So it isn't enough to have a free-form TextField to record a string representation of the exception. A structured field or set of fields is needed; perhaps even an entire separate model for storing exception instances. I'm aware of services that will let me stream logging or errors to them across the network; that is not what this question asks. I need the structured exception data in the project's own database, for reference directly from other models in the same database. Of course I could design such … -
a way to pass m2m field and action into a function's parameter? django
Let's say I have a model which has a m2m field named best. I know by adding things into the best field we can do something like model.best.add(blah) or remove model.best.remove(blah) if I have another m2m field named worst and I want to make a function which will then use the parameter to define if I should be using the best or worst field and if the action is add() or remove Is if possible? I already tried something silly such as: def change(field, action, obj): model.field.action(obj) of course the above will not work, is there a way to make this work so I do not need to do lots IF if I have LOTS m2m fields in one model? Thanks in advance for any advices -
DJango URL error 404
I am trying to get a website using Django to work off of old code and am getting this error when I click on my submit button. The URL file has just been updated how I think it needs to be however it may be wrong. Any help would be greatly appreciated. Page not found (404) Request Method: GET Request URL: http://192.168.2.214/accounts/create?chapter=2 Using the URLconf defined in tsa.urls, Django tried these URL patterns, in this order: ^help/$ [name='help_viewer'] ^help/(\w+)$ [name='help_viewer'] ^contact/$ [name='contact'] ^api/xml$ [name='xml'] ^calendar(?:.ics)?$ [name='calendar'] ^$ [name='index'] ^quick_login$ [name='quick_login'] ^update_indi$ [name='update_indi'] ^settings$ [name='settings'] ^event_list$ [name='event_list'] ^member_list/$ [name='member_list'] ^member_list/(\d+)/$ [name='member_list'] ^team_list/$ [name='team_list'] ^team_list/(\d+)/$ [name='team_list'] ^join_team$ [name='join_team'] ^teams/(\d+)/$ [name='view_team'] ^teams/(\d+)/update/$ [name='update_team'] ^edit_chapter$ [name='edit_chapter'] ^chapter_info$ [name='chapter_info'] ^member_fields/(\w+)?$ [name='member_fields'] ^attendance$ [name='attendance'] ^config/chapter_list$ [name='chapter_list'] ^config/events/(MS|HS)/$ [name='edit_events'] ^config/eventsets/$ [name='eventset_list'] ^config/eventsets/(\d+)/$ [name='edit_eventset'] ^accounts/login/$ [name='tsa.events.views.login_view'] ^accounts/logout/$ [name='tsa.events.views.logout_view'] ^accounts/create/$ [name='tsa.events.views.create_account'] ^accounts/request_chapter/$ [name='tsa.events.views.request_chapter'] ^accounts/reset/$ [name='tsa.events.views.reset_password'] The current path, accounts/create, didn't match any of these. You're seeing this error because you have DEBUG = True in your Django settings file. Change that to False, and Django will display a standard 404 page. -
executemany() takes exactly 3 arguments (2 given) -- mysql with Python
fields is => [u'sender', u'timestamp', u'number', u'mms', u'datetime', u'text', u'id'] dataList is => [(False, 1475565742761L, u'VM-449100', False, u'2016-10-04 12:52:22 GMT+05:30', u'Some text here', 1276)] cursor = connection.cursor() query = """INSERT INTO messages """+str(tuple(fields))+""" VALUES (%s, %s, %s, %s, %s, %s, %s) """,dataList cursor.executemany(query) On executing the above code i am getting error => executemany() takes exactly 3 arguments (2 given) -
Invalid Object Name - User Model Extension and/or matching query does not exist
My app structure is Security > Accounts I'm getting the following error, but why is it adding accounts_ prior to my table name? Below is the model, i'm still using the User model for my auth_user. [SQL Server]Invalid object name 'accounts_alleeactive'. (208) (SQLExecDirectW)") from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models from django.forms import ModelForm from django.db.models.signals import post_save from django.dispatch import receiver import django_filters class AllEeActive(models.Model): employee_ntname = models.OneToOneField(User, db_column='Employee_NTName',max_length=12) # Field name made lowercase. employee_last_name = models.CharField(db_column='Employee_Last_Name', max_length=50, blank=True, null=True) # Field name made lowercase. employee_first_name = models.CharField(db_column='Employee_First_Name', max_length=50, blank=True, null=True) # Field name made lowercase. b_level = models.CharField(db_column='B_Level', max_length=10, blank=True, null=True) # Field name made lowercase. group_name = models.CharField(db_column='Group_Name', max_length=100, blank=True, null=True) # Field name made lowercase. r_level = models.CharField(db_column='R_Level', max_length=10, blank=True, null=True) # Field name made lowercase. division_name = models.CharField(db_column='Division_Name', max_length=100, blank=True, null=True) # Field name made lowercase. d_level = models.CharField(db_column='D_Level', max_length=10, blank=True, null=True) # Field name made lowercase. market_name = models.CharField(db_column='Market_Name', max_length=100, blank=True, null=True) # Field name made lowercase. coid = models.CharField(db_column='COID', max_length=50, blank=True, null=True) # Field name made lowercase. unit_no = models.CharField(db_column='Unit_No', max_length=50, blank=True, null=True) # Field name made lowercase. dept_no = models.CharField(db_column='Dept_No', max_length=50, blank=True, null=True) # Field name made … -
How to use Django SelectMultiple to Send Email
I have a simple app that let's someone select a user, write a message, and then sends the message to the user while saving it to the database. I need to add the ability to select multiple users, type a single message, and then send that message to the selected users. It would also need to save that message to each users account. Here is my current code: forms.py from django.forms import ModelForm, Textarea, Select, SelectMultiple from django.contrib.auth.models import User from .models import Update class UpdateForm(ModelForm): class Meta: model = Update fields = ('user', 'update') widgets = { 'user': Select(attrs={'class': 'form-control'}), 'update': Textarea(attrs={'class': 'form-control', 'Placeholder': 'Please enter your update here.'}) } models.py from django.db import models from django.contrib.auth.models import User class Update(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) update = models.TextField() created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) def __str__(self): return self.update views.py @method_decorator(login_required, name='dispatch') class UpdateFormView(AjaxFormMixin, FormView): template_name = 'update/update_form.html' form_class = UpdateForm success_url = '/' def form_invalid(self, form): response = super(UpdateFormView, self).form_invalid(form) if self.request.is_ajax(): return JsonResponse(form.errors, status=400) else: return response def form_valid(self, form): response = super(UpdateFormView, self).form_valid(form) if self.request.is_ajax(): user = form.cleaned_data['user'] update = form.cleaned_data['update'] update = Update(user=user, update=update) print() update.save() name = user.first_name email = user.email send_complex_message(email, update, name) data … -
dynamic pagination with django
Okay so this is first time using pagination with Dajngo and I am trying to prevent it from reloading my view on each page turn. I'm handling the pagination in the view like this: page = request.GET.get('page', 1) print page paginator = Paginator(list(od.iteritems())[:24], 12) try: data = paginator.page(page) except PageNotAnInteger: data = paginator.page(1) except EmptyPage: data = paginator.page(paginator.num_pages) print data save_query_form = SaveQueryForm(request.POST or None) #if request.method == 'POST': if save_query_form.is_valid(): profile = save_query_form.save(commit=False) profile.user = request.user profile.save() context = { "title":"Search", 'data': data,#list(od.iteritems()), 'tools': od_tools.iteritems(), 'methods': od_methods.iteritems(), 'data4': od_data.iteritems(), 'search_phrase': " ".join(instanceValuesString), 'json_dump': js_data, 'form': save_query_form, } return render(request, 'results.html', context) and the pagination is handled in the html: {% if data.has_other_pages %} <div id='page-slide'> <ul class="pagination" start='$offset'> {% if data.has_previous %} <li><a href="?page={{ data.previous_page_number }}">&laquo;</a></li> {% else %} <li class="disabled"><span>&laquo;</span></li> {% endif %} {% for i in data.paginator.page_range %} {% if data.number == i %} <li class="active"><span>{{ i }} <span class="sr-only">(current)</span></span></li> {% else %} <li><a href="?page={{ i }}">{{ i }}</a></li> {% endif %} {% endfor %} {% if data.has_next %} <li><a href="?page={{ data.next_page_number }}">&raquo;</a></li> {% else %} <li class="disabled"><span>&raquo;</span></li> {% endif %} </ul> </div> {% endif %} The issue that I am having is that whenever I switch … -
About dictionary list
I want to fill a dictionary : recruitment_dict = {} for relation in Relation.objects.filter(on_team=Team.objects.get(owner=request.user)): if relation.recruitment is True: key = relation.on_game.guid value = [relation.on_plateform.guid, relation.recruitment] recruitment_dict[key] = value recruitment_dict returns this dictionary : {'A': ['b', True], 'B': ['b', True], 'C': ['b', True]} But some values are missing. Sometimes, I should have something like this : {'A': ['b', True], 'A': ['c', True], 'B': ['b', True], 'C': ['b', True]} I think the problem is because I use : recruitment_dict[key] = value And so, only the last object at the end of the boucle "for" is saved. But I don't know the right synthax to adopt. -
Django + Ajax . Can't find variable:ajaxPost
I downloaded a bit old project from repo(didn't updated it for few months) and it appeared ajax doesn't work somehow. In pip freeze I checked library I used djangoajax==2.4 In templates js code it looks like this: ajaxPost('/authfb/', {'username': fb_name , 'fb_id': fb_id, 'csrfmiddlewaretoken': getCookie('csrftoken')}, function(){ }); And issue in browser logs is that Can't find variable:ajaxPost I just don't know what that library was and maybe it's outdated? How to check? Or can be problem connected with something else? I am sure it worked before. All ajax, js, jQuery links and etc is correct -
How do I populate a hidden required field in django forms?
I looked at other similar questions on Stackoverflow, but those situations do not apply to me. I have a form with a Queue field that is a required field. This form is used in multiple places and in one such instance, I don't want the Queue field to be shown to the user. So, I simply did not render it on the template. But because this a required field, the form won't submit. How do I pre-populate this field while at the same time hiding it from the user? I cannot make changes to the model or the form's save methods because this form is also used at other places. forms.py class PublicTicketForm(CustomFieldMixin, forms.Form): queue = forms.ChoiceField( widget=forms.Select(attrs={'class': 'form-control'}), label=_('Queue'), required=True, choices=() ) views.py: def no_queue(request): if request.method == 'POST': form = PublicTicketForm(request.POST, request.FILES) form['queue'] = 9 # Tried to assign queue value to field, did not work if form.is_valid(): if text_is_spam(form.cleaned_data['body'], request): # This submission is spam. Let's not save it. return render(request, template_name='helpdesk/public_spam.html') else: form.save() else: form = PublicTicketForm(initial={'queue': 9}) # tried this one too, did not work either return render(request, 'helpdesk/no_queue.html', {'form': form}) The choices for this form were populated in the views, but because I'm not … -
Processing data from XML tags in python
I am trying to extract data from an XML document using python. The tool I'm currently trying with and seems like it is a stable choice is lxml. The issue I'm having is that the tutorials and questions I have came across all assume the format of the XML document is as follows: <note> <to>Tove</to> <from>Jani</from> <heading>Reminder</heading> <body>Don't forget me this weekend!</body> </note> With the values inside the XML tags. However - the document I am trying to extract from has values inside elements of the tags, like so: <note> <to id="16" name="Tove"/> <from id="341" name"Jani"/> <heading id="1" name="Reminder"/> <body id="2" name="Don't forget me this weekend!"/> </note> The way I have tried doing this in LXML is this: xml_file = lxml.etree.parse("test.xml") notes = xml_file.xpath("//note") for note in notes: note_id = note.find("id").text print note_id This just returns "None" I have now found that the .text is what gets data from inside the XML tags - However I simply can't find how to get the data from the elements shown above. Could anyone point me in the right direction?