Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Using namespace in django for anchor tag
I am nobish in django ,started django before 3 weeks.I am facing a issue regarding url in anchor tag in html page.I am including all files music urls.py from django.conf.urls import url from . import views app_name = 'music' urlpatterns = [ url(r'^$', views.index,name='music index'), url(r'^albums/$', views.albums,name='albums'), url(r'^albums/(?P<album_id>[0-9]+)/details/$',views.album,name='details') ] main urls.py from django.conf.urls import include,url from django.contrib import admin urlpatterns = [ url(r'^$', include('music.urls')), url(r'^music/', include('music.urls')), url(r'^admin/', admin.site.urls), ] music views.py from django.shortcuts import render , get_object_or_404 from .models import Albums,Music def index(request): return render(request,'music/index.html',{}) def albums(request): all_albums = Albums.objects.all() return render(request,'music/index.html',{'allalbums' : all_albums}) def album(request,album_id): single_album = get_object_or_404(Albums,pk=album_id) return render(request,'music/details.html' ,{'album' : single_album}) index.html <!DOCTYPE html> <html> <head> <title></title> </head> <body> <ul> <h1>This is music Page</h1> {% for album in allalbums %} <li><a href="{% url 'music:details' album.id %}">{{ album.album_name}}</a></li> {% endfor %} </ul> </body> </html> settings.py INSTALLED_APPS = [ 'music.apps.MusicConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] but when I run this code ,I am getting this issue(attaching image) ..and one more thing .. I am using linux, django 1.11.7 version -
Django: Per View authentication scheme
The django rest framework does allow per view authentication schemes: http://www.django-rest-framework.org/api-guide/authentication/#setting-the-authentication-scheme I think this is handy and I ask myself why this gets reinvented in the django rest framework. "Why does django not provide this?" is a question which would get closed here on stackoverflow soon. That's why I ask: How to get per view authentication schemes in django? -
changing behavior unique=true in nested relation serializer _ Django Restframework
I have two model in my models.py .they are related with OneToOne relation. with this structure: models.py class A (models.Model): foo = models.CharField() class B (models.Model): title = models.CharField(unique=True) some = models.OnToOneField(A, on_delete=models.CASCADE, related_name="some") serializers.py class BSerializer(serializers.ModelSerializer): class Meta: model = B fields = "__all__" class ASerializer(serializers.ModelSerializer): some = BSerializer() class Meta: model = A fields = "__all__" def update(self, instance, validated_data): some_data = validated_data.pop('some') instance.some.title = some_data.get('title', instance.some.title) instance.foo = validated_data.get('foo', instance.foo) a = instance.some instance.save() a.save() return instance so this structure working when i try to update.the title field must be always a unique. basically , the object is created so when i try to update this the title field must be unique but i need too exclude the instance from that uniqueness.how should i tell the django exclude this object from entire database? -
TemplateDoesNotExist at /app/detail/3/
I got an error,TemplateDoesNotExist at /app/detail/3/ app/post_detail.html.I wrote codes def top(request): content = POST.objects.order_by('-created_at')[:5] page = _get_page(blog_content, request.GET.get('page')) return render(request, 'top.html',{'content':content,"page":page}) class DetailView(generic.DetailView): model = POST def detail(request, pk): content = POST.objects.get(id=pk) return render(request, 'detail.html',{'content': content}) in top.html <div> {% for content in page %} <h2>{{ content.title }}</h2> <p><a href="{% url 'detail' content.pk %}">SHOW DETAIL</a></p> {% endfor %} </div> in detail.html <h2>{{ content.title }}</h2> <p>{{ content.text }}</p> When I access top.html,ordinary web site is shown, so it is ok.But when I put SHOW DETAIL links the error happens.I did not write post_detail.html anywhere in my codes, so I really cannot understand why post_detail.html causes mistake.As a test,I made post_detail.html is in same directory with top.html&detail.html,but same error happens.I wanna make a system when I put SHOW DETAIL links ,content's detail is shown.How should I fix this?What is wrong in my code? -
Check if a link is working and hide/disable if it's broken using HTML/JavaScript
So I am building my website using HTML/CSS. I would like to know what is the easiest way to check if a URL is availble? For example, I have a table with a cell that shows a link to some URL - <td width="100%"><center><a href="10.0.5.1"> Server.com </a></center></td> In this cell, there is a link to some url. I want to show the link as URL (a href) only if 10.0.5.1 is working using http! If it's not, I will show just a text, or not show it all... I have found some functions in Javascript that return true and false, but I dont know how to call the function in my html. Like, I was thinking of doing if (link works) : show link with a href, else: show just the string... Is it possible using Javascript function? If so, what's the function and how do I call it? -
limit and ajax in with select2
I am working with a selct2 widget and I want to add 2 options: 1- just show 10 items in default combo and reach others by search 2- have an Ajax call every time on keyup to search the entered string in search field. if that matters I am using this in django and use it as a widget: class Select2(forms.Select): """A combobox (a select field with filter)""" _html_template = trim_docstring(""" <script> $("#{id}").select2({{ language: "{language}", dir: "{dir}", }}); </script> """) @property def media(self): js = ("utils/select2-4.0.3/dist/js/select2.js", "utils/select2-4.0.3/dist/js/i18n/%s.js" % translation.get_language(), "utils/select2-corrections.js", ) css = {'all': ("utils/select2-4.0.3/dist/css/select2.css",)} return forms.Media(js=js, css=css) -
How to validate forms with a recursive validation function
I'm trying to validate some JSON post data recursively, but having trouble returning error reponses in the "child" calls. Here's a simplified version: POST data: { response_type: "parent", subresponses: [ { response_type: "foo", value: "something" },{ response_type: "bar", value: "something else" } ] } The post data can have an arbitrary number of child subresponses. View: def process_response(response): forms = { 'foo': FooForm, 'bar': BarForm, } if response.get('response_type') == 'parent': for subresponse in response.get('subresponses'): self.process_response(subresponse) else: form = forms[response.get('response_type')](response) if form.is_valid(): form.save() else: return JsonResponse({"message": str(form.errors)}, status=400) Of course, the process_response function will throw away the JsonResponse returned by an invalid subresponse in a child object; I need to test the return value instead. I throught about raising an exception in the child and catching it in the parent, but response_type may not be "parent" - so form validation and exception raising would occur at the "top level" in that scenario. Example: { response_type: "bar", value: "something" } Is there a Djangoey way of doing this? And if I'm doing it right, how do I test for returning JsonResponse(status=400) if so? -
fabric GUI interface doesn't load completely in browser
i installed fabric-bolt in my Ubuntu Desktop 16.04 according the Quickstart guid on this link : https://github.com/fabric-bolt/fabric-bolt but the GUI Interface can not load correctly in my browser. where is the problem. i need to do another steps to run fabric-bolt GUI completely? this is a picture of fabric-bolt GUI that i have : fabric-bolt GUI Interface -
How to change Django's start server time format?
When I start django server using following command: python manage.py runserver It shows current time likes: January 02, 2018 - 15:35:17 But I want to see time format: January 02, 2018 - 3:35:17pm How can I do it? Thank you -
Django project does not recognize installed packages
I made two projects using Pycharm (1st one is Python project and 2nd is Django project) and below are the screenshots for the installed packages I don't understand why Django project does not recognize my packages but Python project does recognize. Python version is also same i.e. Python3.5. I also checked the permission issues but you can see below there are similar permissions. user@user3 PycharmProjects]$ ls -l total 0 drwxr-xr-x. 8 user users 208 Dec 14 12:52 RMUE-APP drwxr-xr-x. 6 user users 80 Jan 2 10:51 RmueWeb Please guide me know what should I do to make it work ? -
Django SUM from INNER JOIN
I have a DB like this: class MyCPU(models.Model): cpu_name = models.CharField(max_length=100) cpu_count = models.IntegerField() class MyMachine(models.Model): hostname = models.CharField(max_length=50) ip = models.CharField(max_length=50) cpu = models.ForeignKey(CPU, on_delete=models.CASCADE) How can I achieve the result of following raw SQL command in Django ? select sum(cpu_count) as sum_cpu from my_machine inner join my_cpu on my_machine.cpu_id=my_cpu.id I basically want to sum how many CPU in all of machines. I have tried this solution but it did not work Machine.objects.annotate(total_cpu=Sum('cpu__cpu_count')) -
Django+gunicorn+nginx site runs perfect when using example.com:8000 but not when using example.com
I have a site on Digital Ocean VPS. But I get a bad gateway when accessing example.com but not when example.com:8000. Also when visiting the django-admin at example.com:8000/admin the default formatting is not coming. I guess nginx is not being able to serve the static content. Below is the service file for gunicorn: [Unit] Description=gunicorn daemon After=network.target [Service] Group=www-data WorkingDirectory=/FINlit ExecStart=/FINlit/venvforfinlit/bin/gunicorn --access-logfile - --workers 3 --bind unix:/FINlit/Finlit.sock Finlit.wsgi:application [Install] WantedBy=multi-user.target and the nginx config: upstream app_server_wsgiapp { server 127.0.0.1:8000 fail_timeout=0; } server { listen 80; server_name my_ip; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /FINlit; } location / { include proxy_params; proxy_pass http://unix:/FINlit/Finlit.sock; } } Thanks -
How to send image as input to django view using angular frontend?
I have an existing django web api with angular frontend, using which i can upload images and display them to the user.Now i want to extend this.On clicking the button "segment"(see image) it should pass the corresponding image to my python script on the backend, which does some processing on the image. I have my python script in the views.py file of the main app,which is some thing like this: from django.shortcuts import render def segment_image(request): if request.method == 'GET': form = segment_form() else: if form.is_valid(): info = request.POST['info_name'] output = script_function(info) ''' Here i am calling script_function,passing the POST data info to it''' return render(request, 'your_app/your_template.html', { 'output': output, }) return render(request, 'your_app/your_template.html', { 'form': form, }) '''here info is our image in some format''' def script_function(info): ... '''here goes my mian logic to process the image.''' ... return x,y,w,h I have never worked with images as inputs in angular,i dont know how to route the image using angularjs to my view.Now how can i implement this segmentImage() function in app.js file so that the function would call the corresponding view by passing this image as a POST argument. Below is my index.html file. <!DOCTYPE html> <html lang="en-US"> <head> … -
Django Database : SQLite vs MySQL in production
I'm new to Python/Django, and i using the default database (SQLite) for now, but someone told us that i must use MySQL in production. Using SQLite would be a problem ? -
How can I make a sum of numbers in a cycle in django?
I have a record with severall numbers. The column "Variação de saldo" is the simulation of the extract of some person. What I want the column "Saldo" to show is something like the real time balance. For example, in this case, I want "saldo" to show the sum of the numbers in "variação de saldo". Starting with the first record (in this case, 10); then, adding the next records (10-10=0 the second row will be 0; 0+5=5, the third row will be 5, and so on). How can I make this? enter image description here -
Host Django Rest API on AWS ec2 using Apache
I have built a very basic API using the Django Rest Framework following this tutorial: https://scotch.io/tutorials/build-a-rest-api-with-django-a-test-driven-approach-part-1 I have confirmed that this works on my local machine by following the instructions of the tutorial. Now I need to host this API on the internet. The easiest way to do this seems to be with AWS using Apache2 on an ec2, which I have attempted to do, but I can't seem to figure out how to make this work. I understand that I need to configure Apache2 for my application, which I have done following this tutorial: http://www.nickpolet.com/blog/deploying-django-on-aws/koAayBejnjdNwYfc6 modifying values as needed. My Apache2 configuration file is as follows: WSGIScriptAlias / /home/ubuntu/API/djangorest/djangorest/wsgi.py WSGIPythonPath /home/ubuntu/API/djangorest <Directory /home/ubuntu/API/djangorest/djangorest> <Files wsgi.py> Order deny,allow Require all granted </Files> </Directory> Alias /media/ /home/ubuntu/API/djangorest/media/ Alias /static/ /home/ubuntu/API/djangorest/static/ <Directory /home/ubuntu/API/djangorest/static> Require all granted </Directory> <Directory /home/ubuntu/API/djangorest/media> Require all granted </Directory> My project is housed in the home directory of the ec2 instance like so: ~/API/djangorest/... From here, shouldn't it be a simple matter of configuring Apache? I've waded through documentation for hours to no avail. This is basically the first project I've ever done that isn't a console application, so It's likely that I'm missing something obvious. In short, … -
Django queryset filter hourly data
I need to fetch all the users who came yesterday at a particular hour. Say, if I am running the query at 1:15pm, then users who came yesterday between 1pm and 2pm, should be returned. How can I achieve this? -
Installing only social account from allauth
I am trying to have social sign in on my site using allauth. However, I do not want all the other features that come along with it. For example, I don't want the accounts feature (login, sign up, etc.) I only want: allauth.socialaccount I tried installing only this app and I did get all the models that go with it Social accounts, Social application tokens, Social applications and sites Here's what I installed: INSTALLED_APPS = [ .... .... 'django.contrib.sites', 'allauth', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'allauth.socialaccount.providers.twitter', ] SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'METHOD': 'oauth2', 'SCOPE': ['email'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'LOCALE_FUNC': lambda request: 'en_US', 'VERSION': 'v2.4' }, 'google': { 'SCOPE': ['email'], 'AUTH_PARAMS': {'access_type': 'online'} }, 'twitter':{} } SITE_ID = 3 I have my own User model (inheriting from django.contrib.auth User model. I also have my own sign up page. All I want to do right now is try to get a link in the sign up page that allows the user to sign up with his social accounts (Facebook, Google, Twitter). How do I add these links to my custom sign up page? Please remember I only installed socialaccount and not accounts. I do not want allauth's sign up, login, change email, etc. … -
Deploy Django app on clients production environment
Hi i am new to python development. I have developed the web application using django and i am trying to deploy my application on client environment. I don't want to deploy the application with source code . I have pyc file but it's easily decode. -
How to know the compatible DRF version to Django version?
I just wanted to install and use Django v1.8 and then i installed the latest DRF version on top of it. When i created an initial migration of a model, it was generated an error : Maybe the Django version and the DRF version wasn't compatible which was i did't really know. Any idea how to find the compatible DRF for Django 1.8 ? -
nginx + gunicorn 400 error
I have setup my server to use nginx plus gunicorn for hosting a project. When I send POST request of small sizes everything is OK. But when I send POST requests of size about 5MB I get 400 error from server. I had set client_max_body_size in my nginx configuration to 100M. Can anyone help with this error? Following is how I send request to server : r = requests.post(url, json=data, timeout=180, cookies=cookies, headers=headers) 400 Error depends on data size. With large data size I get this error! -
Security - Is it Safe to Call a Django Function (Python) from an AJAX Request?
Basically, I'm wondering if this code is going to cause any security issues if I put it into production. csrf tokens are implemented and all requests are served over a strict HSTS HTTPS domain. I want to do it like this so I can display a 'loading' screen while the function runs. Otherwise, the app seems to 'hang.' The endpoint for the AJAX request is secure AFAIK, but I'd like some advice on how to ensure I'm not inadvertently doing something insecure. Sending a POST request to the run_shredder function initiates the shredder process (in this case it iterates through all the user's Reddit posts and comments, selectively deleting them.) Here is the Front end JS: $.ajaxSetup({ beforeSend: function (xhr, settings) { xhr.setRequestHeader('X-CSRFToken', '{{ csrf_token }}') } }); $(document).ready(function () { $('#output').DataTable({ 'autoWidth': true, 'responsive': true, 'processing': true, /* Adds the slick gear animation */ 'language': { processing: '<i class="fa fa-gear fa-spin fa-3x fa-fw"></i><span class="sr-only bg-primary"></span> ' }, 'ajax': { 'url': "{% url 'run_shredder' %}", 'dataSrc': '', 'type': 'POST', 'data': { 'account': '{{ account|safe }}', 'keep': '{{ time|safe }}', 'karma_limit': {{ karma_limit|safe }} } }, 'columns': [ {'data': 'cid'}, {'data': 'body'}, {'data': 'status'} ] }); }); Here is the Python … -
Django What is the super of mixin inherit from object
I'm reading a django app code: https://github.com/rogargon/myrecommendations/blob/master/myrestaurants/views.py#L26 He writes some code like: class LoginRequiredMixin(object): @method_decorator(login_required()) def dispatch(self, *args, **kwargs): return super(LoginRequiredMixin, self).dispatch(*args, **kwargs) class CheckIsOwnerMixin(object): def get_object(self, *args, **kwargs): obj = super(CheckIsOwnerMixin, self).get_object(*args, **kwargs) if not obj.user == self.request.user: raise PermissionDenied return obj class LoginRequiredCheckIsOwnerUpdateView(LoginRequiredMixin, CheckIsOwnerMixin, UpdateView): template_name = 'myrestaurants/form.html' Could you tell me what is the super here means? Maybe it just is a problem of python. Thanks! -
How to add dynamically field in crispy form
I don't how how to add dynamically field in crispy, actually i have not much knowledge in crispy form. Could anybody help me?i need this type of field. after click on add button, same field comes down. -
Production setup for celery
How can i setup Celery in Production Server using aws or digitalocean and broker as redis or rabbitmq. Please elaborate more on how we can resilience over the connection refused error while the broker is down.