Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Date format in django queryset extra() in mysql
Sales(models.Model): # ... ommitted fields... amount = models.DecimalField(...) date = models.DateTimeField(...) I'm filtering sales data with the total amount of sales in a month using this query Sales.objects.all() .extra(select={'month': 'MONTHNAME(date)'}) .values('month') .annotate(total=SUM('amount')) .values('month', 'total') The output something like this: [ { "total": 186.0, "month": "July" }, { "total": 278.0, "month": "August" } ] but what i want is to format the month name in 3 letters only to display like this: 'Jul' and 'Aug' and .extra(select={'month': 'DATE_FORMAT(date, '%b')'}) doesn't work. Django: v1.10+ Database: MySQL -
Django-Truncated incorrect DOUBLE value: 'None'
The web system has two mysql databases,one can run normal,but another is down.when I try to GET it,Browser displays the error Truncated incorrect DOUBLE value: 'None' i have checked my source code,and don't have coding errors,so I guess there's a problem with the database, but I don't know how to fix it. And the format of the mysql database is correct -
Nginx+daphne WebSocket connect doesn't receive
I use nginx as reverse proxy for daphne to use django channels. Here's my nginx.conf server { listen 80; server_name <ip_addr>; location / { proxy_pass http://0.0.0.0:8001; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; 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; } } in daphne's log: 2017-07-17 08:45:35,011 DEBUG WebSocket daphne.response.xxx open and established 2017-07-17 08:45:35,011 DEBUG WebSocket daphne.response.xxx accepted by application but WebSocket's connect in client side doesn't receive any message Can you help me? -
Django User model UpdateView "No URL to redirect to"
I want to be able to edit existing users info (like first name etc.) from users panel. I have a list of all users displayed and when I press "edit" button I get "No URL to redirect to. Either provide a url or define a get_absolute_url method on the Model." error. Here is some of my code: class UserUpdate(UpdateView): model = User fields = ['first_name', 'last_name', 'email'] pk_url_kwarg = 'user_id' template_name = 'companies/user_update.html' urls.py url(r'^users/$', views.user_index, name='user_index'), # /company/user/<id> url(r'^users/(?P<user_id>[0-9]+)/$', views.user_detail, name='user_detail'), # /company/users/<id>/update/ url(r'^users/(?P<user_id>[0-9]+)/update/$', views.UserUpdate.as_view(), name='user_update'), I tried fixing it by adding this code to models.py, but I get same error class UserMethods(User): def get_absolute_url(self): return reverse('companies:user_detail', kwargs={'pk': self.pk}) class Meta: proxy = True I also tried adding this method to UpdateView in views.py, but with this I get "'UserUpdate' object has no attribute 'user_id'" def get_success_url(self): return reverse('companies:user_detail', kwargs={ 'user_id': self.user_id}) -
Installing Django on Bluehost
I'm wanting to use django on bluehost, and I've gotten as far as installing python 2.7, then running python get-pip.pyto install / update pip. And now hoping to install virtualenv; the instructions say to run sudo pip install virtualenv but neither the sudo or non-sudo version of this command works. Sudo is flat out not permitted on Bluehost's shared hosting environment, and when I type pip, I get command not found. So I am to assume pip is still not installed, despite the successful execution of python get-pip.py When I type which pip I get nothing, while which easy_install gives me a path. So is it there? I'm quite confused. I've been stuck for some time. Help is much appreciated. -
django-rest-framerwork serializer how to get user id
a model like this: class Album(models.Model): artist = models.ForeignKey(Musician, on_delete=models.CASCADE) name = models.CharField(max_length=100) release_date = models.DateField() num_stars = models.IntegerField() and serializer: class AlbumSerializers(serializers.ModelSerializer): count=serializers.SerializerMethodField() class Meta: module=Album fields=('__all__') def get_count(self,obj): #here how can i gei userid(request.user.id) return i just want know how can i gei user.id in serializer Thank you all very much -
Showing spinner until the whole section is loaded
I want to show loading spinner until a section on the page with images fully loads. I'm using Django, Jquery and Ajax. The Html is pretty basic, I have two divs as follows: On the left side is an table and on the right side is the detail page. I'm trying to show details on user click. When user click on one of the table rows I want to show the corresponding detail page. The onClick event with the ajax call is as follows: $('.panel-body').on('click', '[data-inspection-row]', function (e) { var inspection_id = e.currentTarget.dataset['inspectionId']; $.ajax({ type: "GET", url: '/master/inspection_details/' + inspection_id + "/", beforeSend: function () { $("#details-loader").removeClass("hidden"); }, success: function (result) { $('#right_side_content').hide().html(result).fadeIn(1000); $("#details-loader").addClass("hidden"); }, error: function (data) { $('#inspection-errors').removeClass('hidden').html(data.responseText); } }) }); The result that I get in success function comes from an Django template : {% for picture in data.pictures %} <a class="fancybox pad-no thumb" rel="ligthbox" href="{{ picture }}"> <img class="img-responsive" src="{{ picture }}"/> </a> {% endfor %} I added beforeSend function which is shown for a milliseconds but I still have a problem with the photos loading. When I click on one of the table rows on the left I get screen as follows for about 2-3 … -
Django Rest Framework Pagination - Return last page by default
I am working on a chats app using django rest framework to return a list of messages. These are my codes in api.py class MessageList(generics.ListAPIView): queryset = Message.objects.all() serializer_class = MessageSerializer pagination_class = MessagePagination def get_queryset(self): queryset = super(MessageList, self).get_queryset() return queryset.filter(room__id=self.kwargs.get('pk')).order_by('id') Using http://localhost:8000/chats/message-list//?page=?, I was able to get the list of messages I wanted in different pages. However, I would like the last page to be returned by default since I will also be implementing js infinite scrolling later on. In other words, by entering the url http://localhost:8000/chats/message-list//, the last page objects will be return instead. I am pretty new in django rest framework so I really appreciate any help given. Thanks in advance. -
Creating Folders for files using Django, MySQL and Boootstrap
Hello good people of Stack Overflow. I have a project at hand, and i hope someone here can help me wrap my head around this problem, here it goes: I am working on creating a file repository website, where users can sign up, log in and upload sensitive files (doc, pdf, zip, odt, ppt) to a database. i am using bootstrap for the front end of the site, and Django (along with MySQL) for the back end. Here is where i am stuck, I want the Users to be able to click a button to create a new folder and then rename it to what they please and upload their files to the new folder, I also want them to have the ability to delete said folders, if the users feel that they no longer need it. I do not know how to go about this. Please help me figure this out. Thank you. P.S: Sample of What I have in mind -
Django, How to handle multiple Form_Valids
I use class based views and i need to inherit two form_valids from different views for example. Class A(FormView) def form_valid() Does some stuff return super().form_valid Class B(FormView) def form_valid() Does some more stuff return super().form_valid Class C(Class A, Class B): def form_valid() takes form A and B stuff and does some more stuff return super().form_valid my Class C is only inheriting from the first form_valid and as this is a large project i'm trying to avoid having to revamp the views i'm inheriting to be able to just do the form stuff in class C. All suggestions welcome -
Can orator provides django models like fetures
I am using orator orm, But I want to use the feture of django model with the orator orm. Can anybody suggest me how can we do that? -
call function which return a response inside another function in django view
i need your help please, i've a view which download a file and i want to delete this file after download using a script bash, i tried to call the download function in another one but it didn't work, it just make the download not remove the file. In my views.py: def proc(request): download(request) subprocess.call("./remove.sh", shell=True) return response def download(request): file = open("/home/uker/video.mp4", "rwbt") response = HttpResponse(file.read(), content_type="video/mp4") response['Content-Disposition'] = 'attachment; filename=%s' % file return response -
How to collect social media data using GNIP in python?
I am a newbie in data modelers and need help in "How to extract social media data using GNIP API". Any leads? -
Django,uwsgi,virtualenv: ImportError: No module named site, with sudo
I am trying to run a Django app on CentOS6, with uwsgi, virtualenv and nginx. When I try to start uwsgi with the following command: sudo /usr/local/bin/uwsgi --ini myapp_uwsgi.ini --uid nginx --gid nginx I get the following error: Set PythonHome to /home/uesrname/.virtualenvs/virtualenvname ImportError: No module named site However when running uwsgi without sudo like: /usr/local/bin/uwsgi --ini myapp_uwsgi.ini --uid nginx --gid nginx it doesn't give the error above, and uwsgi works fine. myapp_uwsgi.ini looks like this: # myapp_uwsgi.ini file [uwsgi] # Django-related settings # the base directory (full path) chdir = /var/www/myapp # Django's wsgi file module = myapp.wsgi # the virtualenv (full path) #home = /usr/local/bin/virtualenv home = /home/username/.virtualenvs/myapp # process-related settings # master master = true # maximum number of worker processes processes = 10 # the socket (use the full path to be safe socket = /tmp/myapp.sock # ... with appropriate permissions - may be needed chmod-socket = 666 # clear environment on exit vacuum = true Could someone help me solve this error? -
Django and allowed_hosts again - error 400
At first - i'm not experienced user nor programmer/web admin, so please be kind to me :-) I have a django/apache combination and port forward on my router and trying to reach webserver from external world. Internal IP is 192.168.1.44 and port is standard 80. External IP is 185.47.222.180 and port 2346. As you can try yourself, when http://185.47.222.180:2346/ is typed in a browser, Django returns error 400. I was trying to set 185.47.222.180 and also 185.47.222.180:2346 in allowed_hosts in settings.py file, but result is the same. What am I doing wrong? -
Website goes unresponsive after directing to https in nginx server
I have a web application in django framework and I have setup an nginx server to serve the site. I have also setup SSL into the site. The site works fine with both http and https. Now I want to direct all http requests to https so my users always use the secure version. Here is my nginx config: server { listen 80; listen 443 ssl; server_name site.com www.site.com; ssl_certificate /path/to/SSL; ssl_certificate_key /path/to/SSL/key; location = /favicon.ico { access_log off; log_not_found off; } location /site_media/static/ { alias /home/user/folder/static/dist/; } location / { include uwsgi_params; uwsgi_pass unix:/tmp/site.sock; } } Now when I insert a 301 redirect to https and restart the server, the site goes unresponsive. return 301 https://$server_name$request_uri; into my server { ... } Any idea how to fix this issue, any suggestions would be highly appreciated. -
Is this view done correctly?
I was going to create view for URL:url(r'^users/(?P<user_id>[0-9]+)/objects$', views.UserObject) to create, update, delete or display object of the user. Furthemore, every user can have only one object. I would be grateful whether you could take a look and tell me if it is done correctly. @api_view(['GET', 'POST', 'PUT', 'DELETE']) def UserObject(request, user_id): if request.method == 'POST': try: Object.objects.get(user=user_id) return Response(status=status.HTTP_403_FORBIDDEN) except Object.DoesNotExist: serializer = ObjectSerializer(data=request.data) serializer.fields['user'].required = False if serializer.is_valid(): serializer.save(user_id=user_id) return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) try: object = Object.objects.get(user=user_id) except Object.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = ObjectSerializer(object) return Response(serializer.data) elif request.method == 'PUT': serializer = ObjectSerializer(object, data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) elif request.method == 'DELETE': object.delete() return Response(status=status.HTTP_204_NO_CONTENT) -
Breadcrumbs: Manager isn't available; Page is abstract
I re-created both the automatic menu/navigation as well as breadcrumbs on my Django-Wagtail website based on the example Wagtail site on Github. Everything worked perfectly until this morning, when I followed the Wagtail Form Example to create a form outside of the wagtailforms module. Now, whenever I try and access a Page which has breadcrumbs, I get the following error message: Environment: Request Method: GET Request URL: http://127.0.0.1:8000/frequently-asked-questions/ Django Version: 1.11.1 Python Version: 3.5.2 Installed Applications: ['home', 'enquire', 'blog', 'compressor', 'wagtail.wagtailforms', 'wagtail.wagtailredirects', 'wagtail.wagtailembeds', 'wagtail.wagtailsites', 'wagtail.wagtailusers', 'wagtail.wagtailsnippets', 'wagtail.wagtaildocs', 'wagtail.wagtailimages', 'wagtail.wagtailsearch', 'wagtail.wagtailadmin', 'wagtail.wagtailcore', 'modelcluster', 'taggit', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles'] Installed Middleware: ['django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.security.SecurityMiddleware', 'wagtail.wagtailcore.middleware.SiteMiddleware', 'wagtail.wagtailredirects.middleware.RedirectMiddleware'] Template error: In template C:\Users\ddl_9\Desktop\Nila\src\Nila\templates\base.html, error at line 59 Manager isn't available; Page is abstract 49 : <body class="{% block body_class %}{% endblock %}" data-spy="scroll" data-target="#myScrollspy"> 50 : {% wagtailuserbar 'bottom-left' %} 51 : 52 : {% block menu %} 53 : {% get_site_root as site_root %} 54 : {% top_menu parent=site_root calling_page=self %} 55 : {% endblock %} 56 : 57 : {% include "hero_image.html" with hero=page.hero caption=page.hero.text himage=page.hero.image %} 58 : 59 : {% breadcrumbs %} 60 : 61 : <a href="#" class="scrollToTop" style="background:url({% static 'img/scroll_to_top.png' %});background-size:cover"> … -
passing json data to html template using d3.js in django view
views.py is def index(request): fm_ds=Details.objects.filter(Gender='Female',Dept='Software',Shift='Day').count() m_ds=Details.objects.filter(Gender='Male',Dept='Software',Shift='Day').count() details_dict={} details_dict['Gender']='Female' details_dict['count']=fm_ds print details_dict context = {'data_json': json.dumps(details_dict)} print context return render(request, 'index.html', context=context) output is: {'data_json': '{"count": 2, "Gender": "Female"}'} now i need to pass this json to d3.js template to plot a graph of link of this kind. that is feMALE on x axis and count on y axis. index.html is <!DOCTYPE html> <meta charset="utf-8"> <style> /* set the CSS */ .bar { fill: steelblue; } </style> <body> <script src="//d3js.org/d3.v4.min.js"></script> <script> var margin = {top: 20, right: 20, bottom: 30, left: 40}, width = 960 - margin.left - margin.right, height = 500 - margin.top - margin.bottom; var x = d3.scaleBand() .range([0, width]) .padding(0.1); var y = d3.scaleLinear() .range([height, 0]); var svg = d3.select("body").append("svg") .attr("width", width + margin.left + margin.right) .attr("height", height + margin.top + margin.bottom) .append("g") .attr("transform", "translate(" + margin.left + "," + margin.top + ")"); // get the data var data_json = {{ data_json|safe }}; d3.json( data_json, function(error, data_json) { if (error) return console.warn(error); x.domain(data.map(function(d) { return d.gender; })); y.domain([0, d3.max(data, function(d) { return d.count; })]); svg.selectAll(".bar") .data(data) .enter().append("rect") .attr("class", "bar") .attr("x", function(d) { return x(d.gender); }) .attr("width", x.bandwidth()) .attr("y", function(d) { return y(d.count); }) .attr("height", function(d) { return height … -
Django : Creaate a model on creating a user
There is a Django model Item and an AbstarctUser itemOwner. Upon creating an itemOwner, I need to create its corresponding item. The views and models of Item and ItemOwner are as shown below: class ItemOwner(AbstractUser): owner_name = models.CharField(max_length=64, null=True, blank=True) item = models.ForeignKey(Item, related_name='owner',null=True) class ItemOwnerViewSet(viewsets.ModelViewSet): queryset = Item_owner.objects.all() serializer_class = ItemOwnerSerializer class Item(models.Model): name = models.CharField(max_length=64, verbose_name='name') class ItemViewSet(viewsets.ModelViewSet): queryset = Item.objects.all() serializer_class = ItemSerializer Item need to be created with the values that have been passed as arguments for creating ItemOwner. I know that a model can be created with modelname.save("parameters"). But here the parameters are accessed from the request and i don't know from where i should take the request instance using a ViewSet. What i am exactly looking for is a methode that will be called only when an ItemOwner is created, and this methode should have a request instance to retrieve the arguments so that i can create the Item model with it . How can i do it? -
How to make query in Django with avoiding timezone effect?
I'm new in Django. Here is my model look like e = Event.objects.all() e.values('start') [{'start': datetime.datetime(2017, 7, 13, 8, 0, tzinfo=<UTC>)}] So Event model saves start date with the specified timezone. If I make query like Event.objects.filter(start="2017-07-13") it return [] as shown below: Event.objects.filter(start="2017-07-13") [] Actually I want, It return that values which have start date 2017-07-13 avoiding timezone. Output in such case look like: Event.objects.filter(start="2017-07-13") [<Event:EventName>] Can someone help me figure out this problem. Any help would be appreciated. -
The built-in API Django documentation doesn't display anything
I am trying to add documentation to my Django app. I did everything in accordance with official Django Built-in API documentation. However when I open for instance localhost:8000/docs/ I don't get any result. There is only white screen. I would like to get something like this. I have no idea what is wrong. Everything seems to be done properly. I added coreapi, markdown and pygments to requirements.txt file. My urls.py: from rest_framework.documentation import include_docs_urls API_TITLE = 'API title' API_DESCRIPTION = '...' urlpatterns = [ url(r'^docs/', include_docs_urls(title=API_TITLE, description=API_DESCRIPTION)) ] Logs: django_1 | [16/Jul/2017 14:39:39] "GET /docs/ HTTP/1.1" 200 10156 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/docs/css/bootstrap-theme.min.017404ba6919.css HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/docs/css/bootstrap.min.1825bc9de3d6.css HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/docs/css/font-awesome-4.0.3.3c6725a71cd2.css HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/js/coreapi-0.1.0.b8a6a6e33df8.js HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/docs/css/base.4fca6813aaab.css HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/docs/css/jquery.json-view.min.a2e6beeb6710.css HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/docs/js/jquery.json-view.min.b7c2d6981377.js HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/docs/js/jquery-1.10.2.min.628072e7212d.js HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/docs/js/api.d5c3cd5658db.js HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:39] "GET /static/rest_framework/docs/js/bootstrap.min.79b5346433d3.js HTTP/1.1" 304 0 django_1 | [16/Jul/2017 14:39:40] "GET /docs/schema.js HTTP/1.1" 200 7456 -
Custom Group by query with Django ORM
My Django models are: class GeneralLedger(models.Model): title = models.CharField(..) class JournalPost(models.Model): debit = IntegerField() credit = IntegerField() gl = ForeignKey(GeneralLedger) journal = IntegerField() This code generating table like this Table General Ledger: id name 25 capital and reserve 26 Equity and liability 27 Retained Earning Table Gournal Post jouranl debit credit gl 1444 1000 0 25 1444 0 1000 26 I want new table like this Journal capital and reserve Equity and liability 1444 1000 1000 That means, I want a single row with column as field name for same Journal. How can I manage this with Django ORM? or any custom query ? -
Passing objects primary key from its view to its ManyToMany-relationship object view
I don't know if the title is clear. It's quite difficult for me to explain it in simple way because the problem is not that simple and I'm not a very good English speaker. Every suggestion for improving a title are welcome. So, let's go to the actual problem... In my application people can join different groups. Currently, I'm creating invitation system for this purpose, so user can send an invitation to another user. In a group view, I have a list of users which are not connected with this group, which allowing group members to invite those people. So, when I'm going to the group view, I am passing it's Primary Key. To create database cell about the invitation I need a group's PK and users PK as well (I want to do it using another view, but I'm not sure it's the best solution). My question is: How can I pass those two PKs to the new view where I will create group-user relation cell in a database? models.py: class Group(models.Model): name = models.CharField(max_length=500) members = models.ManyToManyField(User, blank=True, related_name="member") invitations = models.ManyToManyField(User, blank=True, related_name="invitations") views.py: def not_yet_members_list_view(request, pk): group = Group.objects.get(pk=pk) not_yet_members = User.objects.all() #doesn't matter args = … -
django rest framework: default on serializer.JSONField seems to be ignored?
I have a serializer.JSONField but when I view the Browsable API the default argument is seemingly ignored, and instead, null is set as the placeholder for the form. However, this then fails DRF's own validation: django.db.utils.IntegrityError: null value in column "state" violates not-null constraint Model field: state = models.TextField(blank=True, default='') Serializer field: state = serializers.JSONField(label='QB State', required=False, allow_null=False, default=' ') Also tried: state = serializers.JSONField(label='QB State', required=False, default=' ') state = serializers.JSONField(label='QB State', required=False, default='') state = serializers.JSONField(label='QB State') What am I missing here? Thanks in advance :) EDIT: I should note that if I omit the state field when submitting a POST request, the field is correctly populated with the default value (" "). How can I prevent the browsable API form pre-populating with the invalid string: null?