Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I send an xml request and receive an xml response in django Python?
How to make a xml http request and get xml response in django python? request <RDVMessage> <Header> {Authorization:'54873' } </Header> <Body> <Request> <CustomerID> 12345</ CustomerID > </Request> </Body> </RDVMessage> Response: <RDVMessage> <Header> {Authorization:'54873'} </Header> <Body> <Response> <ID> 56789</ID > </Response> </Body> </RDVMessage> -
Django Queryset find data between date
I don't know what title should be, I just got stuck and need to ask. I have a model called shift and imagine the db_table like this: #table shift +---------------+---------------+---------------+---------------+------------+------------+ | start | end | off_start | off_end | time | user_id | +---------------+---------------+---------------+---------------+------------+------------+ | 2018-01-01 | 2018-01-05 | 2018-01-06 | 2018-01-07 | 07:00 | 1 | | 2018-01-08 | 2018-01-14 | 2018-01-15 | Null | 12:00 | 1 | | 2018-01-16 | 2018-01-20 | 2018-01-21 | 2018-01-22 | 18:00 | 1 | | 2018-01-23 | 2018-01-27 | 2018-01-28 | 2018-01-31 | 24:00 | 1 | | .... | .... | .... | .... | .... | .... | +---------------+---------------+---------------+---------------+------------+------------+ if I use queryset with filter like start=2018-01-01 result will 07:00 but how to get result 12:00 if I Input 2018-01-10 ?... thank you! -
Django to Android
I have a web application set-up with Django (Python), and I want to convert it to an Android app (.apk). Question 1 : Can I use Django (with some extra-packages) to create the .apk Question 2 : Do I have to use Android Studio ? (I'm using Atom as a Text Editor). -
Django doesn't logout a user
I have a django application that is successfully able to signup and login a user.However I am unable to logout a user. In the front end, I have a webpage that contains a power button icon, which on clicking should trigger a logout request. I am using angular js for front end index.html <div class="col-xs-2"> <span style="opacity: 0.5;font-family: FontAwesome;font-size: 14px;color:#838F98;text-align:center;cursor:pointer" ng-click="logout()"> <i class="fa fa-power-off" aria-hidden="true"></i> </span> </div> Here I use ngclick to call the logout() function that is defined in my index.js index.js $scope.logout = function() { var url = '/logout'; var toSend = { username: username_id, } $http({ method: 'POST', url: url, data: toSend, }).then(function(response) { response.data; }) }; This function calls the /logout url for which I have defined the function in my views.py file views.py @csrf_exempt def logout_view(request): print(request.user.is_authenticated()) if request.POST: logout(request) print(request.user.is_authenticated()) return HttpResponseRedirect('login.html') return HttpResponseRedirect('login.html') But when I click the power icon on the webpage, nothing happens.The user stays in the page and I don't event get any error message. What am I doing wrong? -
How to call Grandchild in Wagtail
I am using Wagtail for Django and want to call a grandchildren in the template but don't know how to do that. I am new at this and can't seem to find anything in the wagtail documentation. I see the Page Query Reference docs here but don't know how to apply it. My Django project tree are as follows: project/ home/ models.py > class HomePage news/ models.py > class NewsPostPage > class NewsIndexPage In the home template, I want to insert the most current news from the news app to the template. home/models.py from django.db import models from django.utils.translation import ugettext_lazy as _ from modelcluster.models import ParentalKey from wagtail.admin.edit_handlers import FieldPanel from wagtail.core.models import Page from news.models import NewsIndexPage class HomePage(Page): why_choose_us_title_en = models.CharField( verbose_name=_('[EN] Why Choose Us Title'), max_length=200, default='', blank=True, ) why_choose_us_subtitle_en = models.CharField( verbose_name=_('[EN]Why Choose Us Subtitle'), max_length=200, default='', blank=True, ) content_panels = Page.content_panels + [ FieldPanel('why_choose_us_title_en', classname='full title'), FieldPanel('why_choose_us_subtitle_en'), ] subpage_types = [ 'news.NewsIndexPage', ] @property def featured_products(self): return ProductPage.objects.filter(featured=True) news_index = NewsIndexPage news/models.py from datetime import timedelta from django.db import models from django.utils.translation import ugettext_lazy as _ from django.utils import timezone from wagtail.admin.edit_handlers import FieldPanel, RichTextFieldPanel from wagtail.core.fields import RichTextField from wagtail.core.models import Page from … -
Django 404 Page Not Found blog.views.post_detail
I'm new with django and I use mysql. I followed the tutorial to make blog with django. I made list and detail blog, but when I clicked the detail post of blog, the error comes Page Not Found (404) Raised by: blog.views.post_detail. These are my site urls.py, blog urls.py, models.py and views.py. Site urls.py: from django.conf.urls import include, url from django.contrib import admin urlpatterns = [ url(r'^admin/', include(admin.site.urls)), url(r'^blog/', include('blog.urls', namespace='blog', app_name='blog')), ] blog urls.py: from django.conf.urls import url,include from . import views urlpatterns = [ url(r'^$', views.PostListView.as_view(),name='post_list'), url(r'^(?P<year>\d{4})/(?P<month>\d{2})/(?P<day>\d{2})/'\ r'(?P<post>[-\w]+)/$', views.post_detail, name='post_detail'), ] models.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.db import models from django.utils import timezone from django.contrib.auth.models import User from django.core.urlresolvers import reverse class PublishedManager(models.Manager): def get_queryset(self): return super(PublishedManager,self).get_queryset()\ .filter(status='published') class Post(models.Model): STATUS_CHOICES = (('draft', 'Draft'), ('published', 'Published'),) title = models.CharField(max_length=250) slug = models.SlugField(max_length=250,unique_for_date='publish') author = models.ForeignKey(User,related_name='blog_posts') body = models.TextField() publish = models.DateTimeField(default=timezone.now) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) status = models.CharField(max_length=10,choices=STATUS_CHOICES,default='draft') objects = models.Manager() published = PublishedManager() class Meta: ordering=('-publish',) def __str__(self): return self.title def get_absolute_url(self): return reverse('blog:post_detail', args=[self.publish.year, self.publish.strftime('%m'), self.publish.strftime('%d'), self.slug]) views.py: # -*- coding: utf-8 -*- from __future__ import unicode_literals from django.shortcuts import render,get_object_or_404 from .models import Post from django.core.paginator import … -
delete object through Django REST API
I'm trying to delete "Product" object using Django REST API but don't know how to do this. serializer: class ProductSerializer(serializers.ModelSerializer): class Meta: model = Product fields = ('id', 'product_name', 'measure', 'barcode') I can create product using this function def create_product(request): data = request.POST serializer = ProductSerializer(data=data) if serializer.is_valid(): serializer.save() But I don't know how to delete There is no serializer.delete() method. -
Django - User not getting logged in
I am using JWT authentication for my django-rest-framework and react project. So, I have defined a URL path that provides the JWT token. path('api/auth/token/', obtain_jwt_token), I have defined another path which retrieves the current logged-in user: path('current_user/', current_user, name='current-user'), current_user: @api_view(['GET']) def current_user(request): if not request.user.is_authenticated: return Response('User is not authenticated') profile = Profile.objects.get(user=request.user) serializer = CurrentProfileSerializer(profile) return Response(serializer.data) The problem is, after I log in at api/auth/token/ and then go to current_user/, I am getting 'User is not authenticated' response. I thought that obtain_jwt_token returns a token and logs in the user to request.user. Am I wrong for assuming this? Please ask if I need to provide any more details. -
Dango Category and Sub-Category
how would you assign allow_unicode to foreignkey, when i run this code there is no slug field populated for particular language! also can this model be used to generate provinces and cities as well? model: class Category(models.Model): name = models.CharField(max_length=150, db_index=True) slug = models.SlugField(max_length=150, db_index=True, allow_unicode=True) parent = models.ForeignKey('self', on_delete=models.CASCADE, null=True, blank=True) thanks in advance -
create copy of model - django
I have a django app that model.py file is : from django.db import models class Author(models.Model): name = models.CharField(max_length=50) class BlogPost(models.Model): title=models.CharField(max_length=250) body=models.CharField() author=models.ForeignKey(Author, on_delete=models.CASCADE) date_created=DateTimeField(auto_now=True) def copy(): # copy post with all of post comment class Comment(models.Model): blog_post=models.ForeignKey(BlogPost, on_delete=models.CASCADE) text=models.CharField(max_length=500) Now I want to when call copy function create copy of post with all of post comments and save it in database. -
display images through javascript
I am working on quiz project using django where I have to show image on 5 different questions, handled by javascript. But somehow the images are not being shown: Here is the image of my js file Snippet of my css file and static directory Snippet of html file for the same Although when I display image through css, it works perfectly fine, but not through js file. May be the fault is in defining the url but then it's working fine through css then why not js. Images are stored in images directory. -
Django - Retrieve current user
I am trying to retrieve the current logged in user using the following serializer: @api_view(['GET']) def current_user(request): serializer = CurrentProfileSerializer(request.user) return Response(serializer.data) And this is the CurrentProfileSerializer: class CurrentProfileSerializer(serializers.ModelSerializer): user = UserSerializer(required=True) class Meta: model = Profile # PROFILE MODEL HAS A ONE-TO-ONE FIELD WITH USER MODEL fields = '__all__' depth = 1 class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('first_name', 'last_name', 'email', 'password') I am getting this Error when I am trying to go to the current_user URL: Got AttributeError when attempting to get a value for field user on serializer CurrentProfileSerializer. The serializer field might be named incorrectly and not match any attribute or key on the User instance. Original exception text was: 'User' object has no attribute 'user'. -
Celery Function not called
I try to create a progress bar with celery. Unfortunately my worker function get not called. def checkconfig_post_new (request): job = do_work.delay() print ("Work started") return HttpResponseRedirect ( reverse ( 'poll_state' ) + '?job=' + job.id ) # this decorator is all that's needed to tell celery this is a worker task @task() def do_work(): for i in range(10): sleep(0.1) print (i) current_task.update_state(state='PROGRESS', meta={'current': i, 'total': 10}) The print statement "Work started" will never be printed out. Also the "i" will never be printed. It seems, that the program will stop working. -
django-tabbed-admin Django 2.0 compatibility issue with RequestContext
Today i was trying tabbed admin with Django 2.0.7 and i got this error: Exception Type: | TypeError context must be a dict rather than RequestContext. Exception Location: djangostack-2.0.7-0/apps/django/lib/python3.6/site-packages/Django-2.0.7-py3.6.egg/django/template/context.py in make_context, line 274 It seems the whole issue starts from here /tabbed_admin/templatetags/tabbed_admin_tags.py in render_tab_fieldsets_inlines: at line 40 shown below: 39 context["fieldset"] = f 40 return render_to_string(template, context) 41 elif entry['type'] == 'inline': Kindly help, i dont know how to fix this. Any hint will be helpful. Thanks i tried return render_to_string(template, {'context':context}) but it didnt work. -
Django: Best practice for importing views in urls file
I've read in a book that you should avoid doing this: from .views import * What I am currently doing is the following: from . import views My first question is, if this is the same thing just written differently? My second question is if I should import it this way above or should I import every view separately? from .views import (DetailView, EditView, DeleteView, ListView, AnotherView, OneMoreView) -
Django restframework jwt "Invalid payload." erorr
I use Django restframework jwt .. when I pass the token in the headers I got "detail": "Invalid payload." I wonder what might be causing this error ?? -
How to seed Django project ? - insert a bunch of data into the project for initialization
I'ved been developing in Django and was wondering if there is a way to seed data into the database in Django. In ruby on rails, I use seed.rb and then run "rake db:seed" in command line. Main reason I want to seed some data on statuses, types, etc for the project initialization. Is there something similar ? -
CSRF token missing or incorrect in json data with post request using javascript, django 2.0, python 3.6
my javacript post request using json data: function myAjax(type, url, data){ var xhttp = new XMLHttpRequest(); if (!window.XMLHttpRequest) xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText); } }; xhttp.open(type, url, true); xhttp.setRequestHeader('X-Requested-With', 'XMLHttpRequest'); //xhttp.setRequestHeader('Content-Type', 'application/x-www-form-urlencoded'); xhttp.setRequestHeader('Content-Type', 'application/json;charset=UTF-8'); var br = JSON.stringify(data); console.log(br); type=="GET"?xhttp.send():xhttp.send(br); } data={ csrfmiddlewaretoken:"{{csrf_token}}", sss: 'sssssssss', } myAjax("POST","http://localhost:8008/testv/",data); Javascript console output: {"csrfmiddlewaretoken":"WcQnuWdsGgxDlTf5r8VKypuXpVCms0ElSxzACMg9cRIkOQLGbb92EkoxEfLT2qzS","sss":"sssssssss"} POST http://localhost:8008/testv/ 403 (Forbidden) django shell: Forbidden (CSRF token missing or incorrect.): /testv/ I don't want to use @csrf_exempt. Please help. -
Web Chatting Application in Django
I am new to Django trying to develop a chatting web project and stuck . Can someone help me which approach I should use. I want to pass textbox data to Python without changing URL and I am not able to pass it. My Javascript code $("#button").click(function(){ var msg = $('#textbox').val(); I used this ajax code below. However I am not able to retrieve the result in views.py file $('.ajaxProgress').show(); $.ajax({ type: "POST", url: "http://localhost:8080/bot/", dataType: "json", async: true, data:{ csrfmiddlewaretoken: '{{ csrf_token }}', message: $('#textbox').val() }, success: function(json){ $('#test').html(json.message); $('.ajaxProgress').hide(); } }); $('#textbox').val(""); }); can someone please explain how can I use it in views.py. I am getting Forbidden error of csrf_token -
Getting 404 Not Found on NGINX when uploading a file via Django Admin
I'm working on an NGINX + Gunicorn + PostgreSQL + Django + Docker project but I'm having problems when uploading files via the Django admin. When I upload the server receives it and creates the proper database entries for it (User who made it, date, filename, etc.) This content shows flawlessly but when I try to access this file I keep getting a 404 Not Found message. If I manually access the Gunicorn Docker container volume and do a find / -name "Filename.pdf" it does find the file inside /opt/services/media/files/2018-07-29/Filename.pdf so it looks like the file is being uploaded, then why am I unable to access it? This is my NGINX config: # Upstream server, which is our Gunicorn application. upstream project_server { server webapp:8000; } # Main server server { listen 80; server_name localhost; client_max_body_size 5M; location /static { alias /opt/services/webapp/static; } location /media { alias /opt/services/webapp/media; } location / { # Everything is passed to Gunicorn proxy_pass http://project_server; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header Host $host; proxy_redirect off; } } For Gunicorn I execute it with: CMD ["gunicorn", "-c", "config/gunicorn/conf.py", "--bind", ":8000", "--chdir", "project", "project.wsgi:application"] and the config: name = 'project' loglevel = 'info' errorlog = '-' accesslog = '-' … -
django- ImportError: cannot import name 'app'
I tried searching online but couldn't resolve the error. Can someone please help me out with the error? Thanks. Here is the error seen in the command prompt. C:\projects\producthunt>python manage.py unserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x037946A8> Traceback (most recent call last): File "C:\Users\Nidhi\AppData\Local\Programs\Python\Python36-32\lib\site-packag es\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Nidhi\AppData\Local\Programs\Python\Python36-32\lib\site-packag es\django\core\management\commands\runserver.py", line 112, in inner_run autoreload.raise_last_exception() File "C:\Users\Nidhi\AppData\Local\Programs\Python\Python36-32\lib\site-packag es\django\utils\autoreload.py", line 248, in raise_last_exception raise _exception[1] File "C:\Users\Nidhi\AppData\Local\Programs\Python\Python36-32\lib\site-packag es\django\core\management\__init__.py", line 327, in execute autoreload.check_errors(django.setup)() File "C:\Users\Nidhi\AppData\Local\Programs\Python\Python36-32\lib\site-packag es\django\utils\autoreload.py", line 225, in wrapper fn(*args, **kwargs) File "C:\Users\Nidhi\AppData\Local\Programs\Python\Python36-32\lib\site-packag es\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\Nidhi\AppData\Local\Programs\Python\Python36-32\lib\site-packag es\django\apps\registry.py", line 120, in populate app_config.ready() File "C:\Users\Nidhi\AppData\Local\Programs\Python\Python36-32\lib\site-packag es\django\contrib\admin\apps.py", line 23, in ready self.module.autodiscover() File "C:\Users\Nidhi\AppData\Local\Programs\Python\Python36-32\lib\site-packag es\django\contrib\admin\__init__.py", line 26, in autodiscover autodiscover_modules('admin', register_to=site) File "C:\Users\Nidhi\AppData\Local\Programs\Python\Python36-32\lib\site-packag es\django\utils\module_loading.py", line 47, in autodiscover_modules import_module('%s.%s' % (app_config.name, module_to_search)) File "C:\Users\Nidhi\AppData\Local\Programs\Python\Python36-32\lib\importlib\_ _init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 994, in _gcd_import File "<frozen importlib._bootstrap>", line 971, in _find_and_load File "<frozen importlib._bootstrap>", line 955, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 665, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 678, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\projects\producthunt\products\admin.py", line 3, in <module> from .models import Product ImportError: cannot import name … -
Django - detect which form was submitted in a page
I have multiple form fields, and multiple submit buttons on a same page. I want to detect by which form field a POST request is triggered. I am using CBV and my post() method has this: def post(self, request, **kwargs): .... form1 = Form1(request.POST, instance=Model1.objects.filter(some_filtering...) form2 = Form2(request.POST, instance=Model2.objects.filter(some_filtering...) form3 = Form3(request.POST, instance=Model3.objects.filter(some_filtering...) form4 = Form4(request.POST, instance=Model4.objects.filter(some_filtering...) # this is the code I want to know if POST request is triggered by form1... # do something.... return super().post(request, **kwargs) return super().post(request, **kwargs) How can I detect which form triggered POST request? -
Django - Form does not accept value auto-filled by setting html value attr
I have an html input field that looks like this: <input type="number" name="bha_number" value="5" disabled="disabled" class="form-control django-input-form" required="" id="id_bha_number"> Here, value="5" is pre-filled in my view by the following code: context['bha_list_form'].fields['bha_number'].widget.attrs['value'] = last_bha_number + 1 context['bha_list_form'].fields['bha_number'].widget.attrs['disabled'] = 'disabled' When I submit the form, and print the form by overriding my post() method, using: bha_list_form = BHA_List_Form(request.POST) print(bha_list_form) it prints this: <tr> <th><label for="id_bha_number">Bha number:</label></th> <td> <ul class="errorlist"> <li>This field is required.</li> </ul> <input type="number" name="bha_number" required id="id_bha_number" /> </td> </tr> It means that the user did not fill out the form field. But to my understanding, filling out a form has the same effect as setting html value attr equal something. So if I pre-filled the field by manually setting the html value, it should still recognize it as user input, but it doesn't. I know that my form is correct, because if I don't pre-fill the value, but instead actually fill out the form, it prints this: <tr> <th><label for="id_bha_number">Bha number:</label></th> <td><input type="number" name="bha_number" value="1" required id="id_bha_number" /></td> </tr> So there must be something wrong with my way of pre-filling the form field. How can I achieve this? ++ I want to do it without modifying my form forms.py, … -
Unable to post json data using javascript
function myAjax(type, url, data){ url = type == "GET"? (url+"?"+data): url; var xhttp = new XMLHttpRequest(); if (!window.XMLHttpRequest) xmlhttp = new ActiveXObject("Microsoft.XMLHTTP"); xhttp.onreadystatechange = function() { if (this.readyState == 4 && this.status == 200) { console.log(this.responseText); } }; xhttp.open(type, url, true); xhttp.setRequestHeader('Content-Type', 'application/json'); console.log(JSON.stringify(data)); type=="GET"?xhttp.send():xhttp.send(JSON.stringify(data)); } myAjax("POST","http://localhost:8008/testv/", {csrfmiddlewaretoken:"{{csrf_token}}",sss: 'sssssssss',}); I'm using django 2.0 with python 3.6. I know csrf_token is required to post data and I am passing it. But still in javascript console I get: 403 Forbidden error. In servers console I get: CSRF token missing or incorrect. What am I doing wrong here? -
Django - attributes with same foreign key type is not allowed, how to solve this?
In my Django model, I have this model with 3 attributes with same foreign key type. employee = models.ForeignKey(Employee) approved_by = models.ForeignKey(Employee) created_by = models.ForeignKey(Employee) However, it complains on this after doing "makemigrations". Here is the errors: SystemCheckError: System check identified some issues: ERRORS: railercomapp.Leave.approved_by: (fields.E304) Reverse accessor for 'Leave.approved_by' clashes with reverse accessor for 'Leave.created_by'. HINT: Add or change a related_name argument to the definition for 'Leave.approved_by' or 'Leave.created_by'. railercomapp.Leave.approved_by: (fields.E304) Reverse accessor for 'Leave.approved_by' clashes with reverse accessor for 'Leave.employee'. HINT: Add or change a related_name argument to the definition for 'Leave.approved_by' or 'Leave.employee'. railercomapp.Leave.created_by: (fields.E304) Reverse accessor for 'Leave.created_by' clashes with reverse accessor for 'Leave.approved_by'. HINT: Add or change a related_name argument to the definition for 'Leave.created_by' or 'Leave.approved_by'. railercomapp.Leave.created_by: (fields.E304) Reverse accessor for 'Leave.created_by' clashes with reverse accessor for 'Leave.employee'. HINT: Add or change a related_name argument to the definition for 'Leave.created_by' or 'Leave.employee'. railercomapp.Leave.employee: (fields.E304) Reverse accessor for 'Leave.employee' clashes with reverse accessor for 'Leave.approved_by'. HINT: Add or change a related_name argument to the definition for 'Leave.employee' or 'Leave.approved_by'. railercomapp.Leave.employee: (fields.E304) Reverse accessor for 'Leave.employee' clashes with reverse accessor for 'Leave.created_by'. HINT: Add or change a related_name argument to the definition for 'Leave.employee' or 'Leave.created_by'. …