Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django sharing resources
Scenery: A web app which allows a registered user to create a ToDoList and then to assign each item of List to other users. Problem: Assign an element of ToDoList to users. How I can do it? -
Django child template not inheriting from base.html
I have a problem in inheriting template from base.html for my about page (about.html). Meanwhile, I am able to extend base.html to home.html. I suspect it is an issue of syntax somewhere either in base.html or about.html, but could not possibly find it. It might also be base.html is only inherited by home.html. Can you please help? My base. html: <!DOCTYPE html> {% load staticfiles %} <html lang="en"> <head> <title> {% block title %}{% endblock %} </title> <h1> {% block h1 %}{% endblock %} </h1> </head> <body> {% block content %} {% endblock %} {% block two %} {% endblock %} </body> <!DOCTYPE html> My about.html: {% extends "base.html" %} {% load staticfiles %} <html lang="en"> <head> {% block title %}About{% endblock %} {% block h1 %}Hi,About!{% endblock %} </head> <body> </body> </html> -
django serving static file with nginx
I couldn't seem to get routing to work properly. I've also included the collectstatic when i run. In my settings.py i have the follow code STATIC_URL = '/static/' STATIC_ROOT = "/code/static" in my nginx config file worker_processes 1; events { worker_connections 1024; } http { server { listen 80; server_name example.org; access_log /dev/stdout; error_log /dev/stdout info; location ^~/static/ { autoindex on; root /code; } location / { proxy_pass http://web:8000; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } } -
How to group by date from timestamp field with Django ORM?
I have this MySQL specific query SELECT SUM(trip_amount) as tp , DATE(FROM_UNIXTIME(request_time)) as timestamp FROM trip_master WHERE trip_master.date > 1493836200 AND trip_master.date < 1493922600 AND trip_master.id = 6 GROUP BY timestamp Implemented this query in Django, Trip.objects.filter(id=userid,date__gt = start,date__lt = end).annotate(trip_amount = Sum('trip_amount')).extra({'timestamp':'DATE(FROM_UNIXTIME(request_time))'}) As defined i have to convert time stamp to date to have grouping from dates.Has reached at the almost level but not getting group by dates. Any help is much appreciated -
Django using request.user with Button action
Description: I have a table that displays information submitted by a user which needs to be actioned by a manager so i have a button at the end of each row saying "authorise" and a blank comment called "authorised_by", once the button is pressed the manger is redirected to a form to overlook the information and given the option to authorise said info. Question: How do i then pass back the managers name to display in the column "authorised_by" ListView/Table Code: model = Change template_name = 'users/change_requests/exemption_authorise.html' context_object_name = 'change' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) self.queryset = self.get_filters(self.model.objects.all()) context['requested_by'] = self.request.user if self.model.authorised_by == True: context['authorised_by'] = self.request.user else: context['authorised_by'] = "" context['auth'] = int(bool(int(self.request.GET.get("auth")))) if "auth" in self.request.GET.keys() else None context['count_of_records'] = self.queryset.count() return context FormView Code: model = Change template_name = 'users/change_requests/auth_request.html' form_class = AuthForm pk_url_kwarg = 'authorise_id' def check_authorised(self): if not getattr(self, 'authorise', None): self.authorise = Change.objects.get(pk=self.kwargs.get('authorise_id')) if self.authorise.authorised_by: messages.error("Sorry, this has already been authorised by {}".format(self.authorise.authorised_by.get_full_name())) return True return False def get(self, request, *args, **kwargs): if self.check_authorised(): return redirect('users:change_request') return super().get(request, *args, **kwargs) def post(self, request, *args, **kwargs): if self.check_authorised(): return redirect('users:change_request') return super().post(request, *args, **kwargs) def get_initial(self): initial = super().get_initial() self.authorise = Change.objects.get(pk=self.kwargs.get('authorise_id')) initial.update({'request': … -
django rest framework csrf token missing or incorrect
hello i'm using django rest-auth and i have this problem in /password/change/ it allways return csrf token missing or incorrect problem : my settings are : INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'rest_framework', 'rest_framework.authtoken', 'rest_auth', 'rest_auth.registration', 'allauth', 'allauth.account', 'allauth.socialaccount', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework.authentication.SessionAuthentication', 'rest_framework.authentication.TokenAuthentication', ) } versions : django-rest-auth==0.9.1 djangorestframework==3.6.2 -
xlsxwriter consuming too much memory and process gets killed
I'm using xlsxwriter python package to export data from a PostgreSQL database to excel in a django project. I've implemented a Django command to do this, but the problem is that there are more than 4 millions of records of data and writting the file consumes all my RAM, and the process gets killed. Log: [export_user_data_to_excel]> Generating excel file with: 3913616 Instagram publications 1250156 Instagram hashtags 513124 Twitter publications 127912 Twitter hashtags Killed I've tried with a parameter called 'constant_memory' but it doesn't seem to make a difference. Here is the method that writes the excel file: def write_to_excel_perf(filename, instagram_publications, instagram_tags, twitter_publications, twitter_tags, instance): """ Export the current queryset to an excel file in xlsx format. Optimized for low memory consumption and better performance http://xlsxwriter.readthedocs.io/working_with_memory.html#memory-perf """ logger.info("[write_to_excel_perf]> Openning Workbook..") book = xlsxwriter.Workbook(filename, {'constant_memory': True}) if 'instagram' in instance: logger.info("[write_to_excel_perf]> Writting Instagram publications..") sheet = book.add_worksheet('Instagram Media') # Adding media page titles = ["Type", "City", "Date", "Instagram Id", "Instagram URL", "caption", "likes", "author", "location id", "location name", "lat", "lng"] i = 0 for title in titles: sheet.write(0, i, title) i += 1 row_index = 1 # We improve the performance making sure that we query by related data using select_related # … -
ValueError - The annotation 'status' conflicts with a field on the model django
I'm trying to perform a bit of complicated query in my rest api view so I can order my contacts in the right order, now as e4c5 suggested in my previous question I could do this Case annotation and build my custom annotation with CASE/WHEN and then use that in annotation in the order by, but now I'm getting ValueError at /api/sales/lead_contact/ The annotation 'status' conflicts with a field on the model so this is the custom annotation I'm trying to build so I can properly order contacts, one note is that I'm preforming this in rest view: class LeadContactViewSet(viewsets.ModelViewSet): def get_queryset(self): filter_date = self.request.query_params.get('filter_date', None) case_sql = LeadContact.objects.annotate( status=Case( When(status=LeadContactConstants.STATUS_CLIENT, then=Value('1')), When(status=LeadContactConstants.STATUS_QUALIFIED, then=Value('2')), When(status=LeadContactConstants.STATUS_CONTACTED, then=Value('3')), When(status=LeadContactConstants.STATUS_PRISTINE, then=Value('4')), default=Value('1'), output_field=CharField(), ) ).values_list('status') if filter_date is not None: queryset = queryset.filter(next_action_date=filter_date).extra(select={'status': case_sql}, order_by=['status']) return queryset Model fields: status = models.CharField(max_length=10, choices=LeadContactConstants.STATUSES, default=LeadContactConstants.STATUS_PRISTINE) and the choices for this field: class LeadContactConstants(object): STATUS_PRISTINE = "PRISTINE" STATUS_CONTACTED = "CONTACTED" STATUS_QUALIFIED = "QUALIFIED" STATUS_CLIENT = "CLIENT" STATUSES = ((STATUS_PRISTINE, "Virgin"), (STATUS_CONTACTED, "Contacted"), (STATUS_QUALIFIED, "Qualified"), (STATUS_CLIENT, "Client")) Serializer class: class LeadContactSerializer(serializers.ModelSerializer): account_handler = AccountHandlerSerializer() next_action_date = serializers.DateTimeField(format=settings.CUSTOM_DATE_FORMAT_NO_TIME) absolute_url = serializers.URLField(source='get_absolute_url') class Meta: model = LeadContact fields = ( 'pk', 'organization_name', 'sub_organization_name', 'serial_number', 'account_handler', 'status_text', 'first_name', 'last_name', … -
Issue with Django URL Mapping/DetailView
I am new to Django and have been making a sample project. I have been trying to use Generic Detailview. It seems that url redirection works fine but DetailView can't get primarykey fro the url. Here is my app's urls.py code: urlpatterns = [ url(r'(?P<pk>\d+)/$',views.detailView.as_view(),name="detail"),] View file for the DetailView: from django.shortcuts import render from django.views import generic from .models import Story class detailView(generic.DetailView): model = Story template_name = 'personal/storydetail.html' def get_context_data(self, **kwargs): pk = kwargs.get('pk') # this is the primary key from your URL print("PK:",pk) Template Code: {% block content %} {{ Story.writer }} <h6> on {{ Story.story_title }}</h6> <div class = "container"> {{ Story.collection }} </div> {% endblock %} When I check primary key value on view it shows it 'NONE'. I can't find issue with the code. My pased url looks like : http://127.0.0.1:8000/personal/2/ where personal is the name of app and 2 should be taken as id. -
POST or not? render_to_response() or render()?
I am very new user of Django. I would like to send an email (for fax) in clicking on a button. So I have created the method send_fax in the view CustomerRequestUpdateView. I am a bit confusing here. Does this method have to use a POST request? How could I render 'send_fax' to my template? I would like that method could be implemented in the class directly. class CustomerRequestUpdateView(RequestUpdateView): template_name = 'loanwolf/customers/request.html' url_namespace = 'customers' def send_fax(self): subject = 'The contract of %s' % self.customer.email_user contact_message = 'This is just a test for later on during this project' from_email = settings.EMAIL_HOST_USER to_email = [from_email, ] send_mail( subject, contact_message, from_email, to_email, fail_silently=False, ) return #render(request, template_name, context) render_to_pdf() I thought I could use render_to_response() or just render(), but my method use self, not request. Could anyone be able to help me here? Thanks! -
How to store value in NullBooleanField from Django form
I am trying to insert data into a NullBooleanField() from a Django form, however, only 'True' is ever added. I have printed the cleaned data from 3 different fields from the form and it looks as follows: True False None (Which is what I would expect it to look like - as I selected 3 different options) This is what the form fields look like: MY_CHOICES = [(True, 'Yes'), (False, 'No'), (None, 'N/A')] field_1 = forms.ChoiceField( required=True, choices=MY_CHOICES, widget=forms.RadioSelect(renderer=HorizontalRadioRenderer), label="Field 1" ) And this is what the fields in the model looks like: field_1 = models.NullBooleanField() I don't understand why the data always inserts as 'True' when I check in Django admin. In Django admin, the choices are as follows: "Yes, No, Unknown" So I have tried changing the form choices to read as follows: MY_CHOICES = [('Yes', 'Yes'), ('No', 'No'), ('Unknown', 'N/A')] But yet again, this does not work. Can anyone suggest what might be the issue here? -
Testing with Django: how to display all characters when using assertEqual with json object?
I'm testing django-rest-framework. When I POST some content in json format and want to test if it was posted correctly I try to get the object posted with resp_get = self.client.get(self.url) and test with assertEqual (json format): self.assertEqual( json.loads(resp_get.content.decode('utf8')), [ { 'id': researcher.id, 'first_name': researcher.first_name, 'surname': researcher.surname, 'email': researcher.email, 'studies': [], 'nes_id': researcher.nes_id, 'owner': researcher.owner.username } ] ) As comparing results false, I get an AssertionError with following message AssertionError: {'id': 1, 'first_name': 'João Maria', 'su[102 chars]ab1'} != [{'id': 1, 'first_name': 'João Maria', 's[104 chars]b1'}] I'd like to know if is someway possible to get entire json object compared in both sides, as AssertionError returns the object compacted: su[102 chars]ab1, and s[104 chars]b1. -
Django Rest Framework Json Web Token Refresh
i just started using Json Web Token ( https://github.com/GetBlimp/django-rest-framework-jwt ) and i have a question regarding refreshing the token. While reading the official documentation on Refresh Tokens, i found this bit here Each time the user loads the page, you can check if there is an existing non-expired token and if it's close to being expired, refresh it to extend their session. The thing is, i want my API to support both Web and Mobile, for my Web part i am using jQuery to ask for the refresh tokens. The thing is how can i do this part and if it's close to being expired, refresh it to extend their session without passing my Django secret key to the template so that i can decode the token in my local storage and figure out when it is going to expire before making an unnecessary request?? If i should not decode the token, then for every page load i would have to make an additional request to ask if my current token has not expired yet? That seems a bit overkill to me and it is whats causing me to be confused about it. What is the correct approach here?? Thanks -
Django: String not extracted from custom translation template tag
I made a template tag to translate a string in multiple languages but those strings are not detected by makemessages. How does one mark strings for translation in template tags? How does xgettext identify translation strings in template tags? Here's the code (simplified): # Helper def multitrans(string): translated_strings = [] current_language = translation.get_language() for lang in settings.LANGUAGES: translation.activate(lang[0]) translated_strings.append(ugettext(string)) translation.activate(current_language) return mark_safe("<br>".join(translated_strings)) # Template tag @register.simple_tag(name="multitrans") def multitrans_tag(string): return multitrans(string) # Template block tag from django.templatetags.i18n import BlockTranslateNode class BlockMultiTranslateNode(BlockTranslateNode): def render(self, context, nested=False): translated_strings = [] current_language = translation.get_language() for lang in settings.LANGUAGES: translation.activate(lang[0]) translated_strings.append( super(BlockMultiTranslateNode, self).render(context, nested=nested) ) translation.activate(current_language) return mark_safe("<br>".join(translated_strings)) @register.tag("blockmultitrans") def do_block_multi_translate(parser, token): … # Same as Django blocktrans. return BlockMultiTranslateNode(…) # Custom management command `my_makemessages` from django.core.management.commands import makemessages class Command(makemessages.Command): xgettext_options = makemessages.Command.xgettext_options + [ '--keyword=multitrans', ] With these files, my_makemessages extracts everything except those from multitrans tags: # test.py ugettext("ugettext string") multitrans("multitrans string") # test.html {% trans "trans tag string" %} {% multitrans "multitrans tag string" %} {% blockmultitrans %}blockmultitrans tag string{% endblockmultitrans %} -
Django Rest Framework JWT : How to change the token expiration time when logged in
I'm using Django REST framework JWT Auth for session creation and permissions, the only problem is: when I log in and after the token expires I can't continue doing the operation I want, unless I log in again. And I didn't fully understand the documentations provided for the additional settings. So can any one explain a method for dynamically creating (and refreshing) my token (following best practices) so that I can keep doing operations when I'm logged in. P.S: I'm using angular 2 for my front end, and I'm inserting the token in the Http requests headers. Thanks. -
Django-MSSQL error when creating a user from the admin panel
I am a bit stuck, my app is nearly finished and I have a problem, I can't create a user with the admin panel. I am using django 1.9 and MSSQL and when I go to my admin panel (with a superuser I created in the shell), I have my groups and my users, I can enter them both, but when I want to add a user it gives me this error : (-2147352567, 'Une exception s\x92est produite.', (0, u'Microsoft OLE DB Provider for SQL Server', u"Impossible d'ex\xe9cuter SAVE TRANSACTION quand aucune transaction n'est active.", None, 0, -2147467259), None) Command: SAVE TRANSACTION [s6736_x1] Parameters: [] The translation is : (-2147352567, 'An exception has happend.', (0, u'Microsoft OLE DB Provider for SQL Server', u"Impossible to execute SAVE TRANSACTION when no transaction is active.", None, 0, -2147467259), None) Command: SAVE TRANSACTION [s6736_x1] Parameters: [] When I try to add a group I have no problem, I can access the group creation form. If anyone has an idea I would be thanksful. -
Python - filtering in Django
I'm new in python/django and i have a problem, i'm trying to use checkbox filtering in my html table and i don't really know how to do it. This is what i have now I want to add these models.py class Tags(models.Model): tag_frequency = models.CharField(max_length=250) views.py @login_required(login_url='/login/') def index(request): title = 'Tags' all_tags = Tags.objects.all() return render(request, 'tag/index.html' ,{'all_tags':all_tags, 'title':title}) How do i use filter with these, i tried something like this but doesn't work: LF = 125 - 134.2 KHz HF = 13.56 MHz UHF = 860 - 960 MHz LF = Tags.objects.filter(tag_frequency__gt=125, tag_frequency__lt=134.2) -
ordering using SQL's CASE WHEN/THEN syntax django
I'm trying to order contacts in table and I'm facing some problems, I found a nice solution in this SO question, maybe it's an over kill for this, but I'm trying to do this over restapi so I'm only affecting my rest view with this, ok so this is my solution for this ordering: filter_date = self.request.query_params.get('filter_date', None) case_sql = '(case when status="Client" ' \ 'then 1 when status="Contacted" ' \ 'then 2 when status="Qualified" ' \ 'then 3 when status="Virgin" then 4 end)' if filter_date is not None: queryset = queryset.filter(next_action_date=filter_date).extra(select={'status': case_sql}, order_by=['status']) I'm doing this because I don't want to change my db field, like I said I only want to affect my rest view, so the question is, am I doing this filter wrong all this all setup is wrong by default? Model fields: status = models.CharField(max_length=10, choices=LeadContactConstants.STATUSES, default=LeadContactConstants.STATUS_PRISTINE) and the choices for this field: class LeadContactConstants(object): STATUS_PRISTINE = "PRISTINE" STATUS_CONTACTED = "CONTACTED" STATUS_QUALIFIED = "QUALIFIED" STATUS_CLIENT = "CLIENT" STATUSES = ((STATUS_PRISTINE, "Virgin"), (STATUS_CONTACTED, "Contacted"), (STATUS_QUALIFIED, "Qualified"), (STATUS_CLIENT, "Client")) -
django update_or_create, see what got updated
My app uses update_or_create() to update a bunch of records. In some cases, updates are really few within a ton of records, and it would be nice to know what got updated within those records. Is it possible to know what got updated (i.e fields whose values got changed)? If not, does any one has ideas of workarounds to achieve that? This will be invoked from the shell, so ideally it would be nice to be prompted for confirmation just before a value is being changed within update_or_create(), but if not that, knowing what got changed will also help. -
how to authenticate using google
Django==1.8.6., python-social-auth==0.2.12 I tried to authenticate using google, got an error: Request URL: http://127.0.0.1:8000/social-auth/login/google/ Raised by: social.apps.django_app.views.auth Backend not found My main. urls: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^user/', include('user.urls')), url('social-auth/', include('social.apps.django_app.urls', namespace='social')), ] Settings: INSTALLED_APPS = ( 'user', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'social.apps.django_app.default', ) AUTHENTICATION_BACKENDS =( 'social.backends.google.GoogleOAuth2', ) SOCIAL_AUTH_GOOGLE_OAUTH2_KEY='here is my google key SOCIAL_AUTH_GOOGLE_OAUTH2_SECRET ='here is my google secret' ) -
request_kerberos doesn't work
Are you able to tell me why I cannot use the request_kerberos module ? this is my code: from django.http import HttpResponseNotFound ,HttpResponseRedirect import requests from requests_kerberos import HTTPKerberosAuth, OPTIONAL I have already installed this module ,but when I'm opening the webpage I see that: No module named winkerberos I've checked the code and the problem is here ,kerberos.py file, first 4 lines: try: import kerberos except ImportError: import winkerberos as kerberos winkerberos is for Windows OS and I'm using the CentOS So, why my system cannot import that module ? -
Django Rest Framework, different endpoint URL for one APIVIEW
I am using Django Rest Framework for my API project. Now i have one APIVIEW with post and get method. How can i add different endpoint only for a particular get or post. class UserView(APIVIEW): def get(self, request, format=None): ..... pass def post(self, request, format=None): ..... pass Now in the urls.py, i want something like this: urlpatterns = [ url(r'^user\/?$', UserView.as_view()), url(r'^user_content\/?$', UserView.as_view()), ] user only accept get request and user_content only accept post request. -
rest_framwork_swagger occured "TypeError: 'Link' object does not support item assignment"
A project using Django, DRF, swagger. url config below: schema_view = get_swagger_view(title='Pastebin API') urlpatterns = [ url(r'^$', schema_view), url(r'store', include('store.urls')), ... # other urls using routers.SimplerRouter ] and store/urls.py: router = routers.SimpleRouter() router.register(r'', views.StoreViewSet) urlpatterns = router.urls and views.StoreViewSet: class StoreViewSet(BaseObject, GenericViewSet): permition_class = () @list_route() def detail(self, request): return {} @list_route(url_path='detail/export') def detail_export(self, request): return {} after python manage.py runserver, visit http://127.0.0.1:8000/# and a TypeError occured: File "/usr/local/share/.virtualenvs/dev-finance/lib/python2.7/site-packages/rest_framework_swagger/views.py", line 32, in get schema = generator.get_schema(request=request) File "/usr/local/share/.virtualenvs/dev-finance/lib/python2.7/site-packages/rest_framework/schemas.py", line 242, in get_schema links = self.get_links(request) File "/usr/local/share/.virtualenvs/dev-finance/lib/python2.7/site-packages/rest_framework/schemas.py", line 276, in get_links insert_into(links, keys, link) File "/usr/local/share/.virtualenvs/dev-finance/lib/python2.7/site-packages/rest_framework/schemas.py", line 79, in insert_into target[keys[-1]] = value TypeError: 'Link' object does not support item assignment [ERROR] 2017-05-04 15:25:06,936 log_message(basehttp.py:131) "GET / HTTP/1.1" 500 20384 The error message shows, the Link object can't assign value, like dict does. If I rename the method name from detail_export to details_export, everything goes fine again. Guessing error occured when rest_framework's @list_route decorater transfer the method's url to Link object. why other methods just goes fine? how can I solve this? -
Another CSRF issue Django + jQuery + AJAX
I have a 10x10 field contains 100 tiles (divs with an img in every div, droppable objects). I have a cap (draggable object) that player can drag and drop into any of tiles. I've already made mechanism to snap it to the middle of a tile. But when i bring the screen closer/farer the cap ran away from its tile. How could i attach the cap to a tile? function snapToMiddle(dragger, target) { var topMove = target.position().top + (target.outerHeight(true) - dragger.outerHeight(true)) / 2; var leftMove = target.position().left + (target.outerWidth(true) - dragger.outerWidth(true)) / 2; dragger.outerWidth(true)) / 2; dragger.animate({top: topMove, left: leftMove}, {duration: 300, easing: 'easeOutBack'}); console.log(target.offset());} $('.cover,.r0,.r90,.r180,.r270').droppable({ drop:function(event,ui){snapToMiddle(ui.draggable,$(this));}, over:function(event,ui){greenLight(ui.draggable,$(this));}, out:function(event,ui){offLight(ui.draggable,$(this));}, }); $('.player').draggable( { opacity: .4, create: function(){ $(this).data('position',$(this).position()); // $(this).animate({top:$(this).position(0).top,left:100},{duration:3000,easing:'easeOutBack'}); console.log($(this).position()) }, cursorAt:{left:15}, cursor:'move', start:function(){$(this).stop(true,true)} } -
Django redirect function keep old url path
The problem is when I try to use django.shortcuts.redirect in my view function, Django doesn't simply opening new url path from return redirect('url',) but add wished url path to current url. EG Current url is: /home/page1 On page on button press I call views function which: return redirect ('/home/page2',)After this, instead wished url /home/page2 I recieve /home/page1/home/page2How to rid of old url part from redirection?