Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - open and read from a text file
I'm trying to open a file and read from that file but when doing so i'm getting an error no such file or directory my views.py: from django.shortcuts import render from django.http import HttpResponse from preguntasyrespuestas.models import Pregunta from django.shortcuts import render_to_response from django.template import loader,context import re file = open("address.txt","r") content = file.read() file.close() def address_lan1(): addr1 = re.findall('address\s(.*?)\s',open('address.txt','r').read()) if len(addr1[0]) > 0: print 'Address',":",addr1[0] else: print "no se encontro un Address en Lan 1" return addr1[0] address_lan1() def index(request): var = address_lan1() return render_to_response('django_examples/index.html', {'var':var}) My text file: address 192.168.70.15 My html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>NETWORK</title> </head> <body> <form method="post" name="test"> <h4>NETWORKING</h4> <div class="col-sm-9"> <label class="col-sm-3 col-sm-3 control-label">Address 1 : </label> <input type="text" class="form-control" name="addr1" value="{{ var }}"> </div> <input type="submit" name="submit" value="Guardar Cambios"> <input type="submit" name="submit" value="Calcular"> </form> </html> This is my app structure: Basically All I need is to open my address.txt and get the value of address but cannot open that file. What am I doing wrong? thanks.. -
S3 Boto 403 Forbidden Unless Access Given to "Any Authenticated AWS User"
I am using Python and Boto to upload images to S3. I can get it to work if I add a grantee of "Any Authenticated AWS User" and give this grantee permission to upload/delete. However, my impression from the documentation and several different posts on this site is that this would allow literally any authenticated AWS user, not just those authenticated to my account, to access the bucket, which I do not want. However, I am unable to upload files (403) if I only give upload/delete permission to the owner of the account, even though I authenticate like this: s3 = boto.connect_s3(aws_access_key_id=AWS_ACCESS_KEY_ID, aws_secret_access_key=AWS_SECRET_ACCESS_KEY) im = Image.open(BytesIO(urllib.urlopen(self.url).read())) filename = self.url.split('/')[-1].split('.')[0] extension = self.url.split('.')[-1] out_im2 = cStringIO.StringIO() im.save(out_im2, im.format) key = bucket.new_key(filename + "." + extension) key.set_contents_from_string(out_im2.getvalue(), headers={ "Content-Type": extension_contenttype_mapping[extension], }) key.set_acl('public-read') self.file = bucket_url + filename + "." + extension What am I doing wrong in this situation? -
Default Django QuerySet ordering: by PK?
Could you please confirm that Django querysets are ordered by PK by default (i.e., when there's no order_by, and the model doesn't have a non-default ordering specified in it's meta)? -
Django translation generate all possible values
Suppose I want to translate strings 'into ukrainian language', 'into russian language', 'into french language' into 4 different languages. I want to automate this process: Create list langs = ['ukrainian' , 'russian', 'french'] # this can be a big list, that's why I'm asking this question {lang: ugettext('into %(lang)s language' % dict(lang=lang)) for lang in langs} At runtime dictionary is as expected: {'ukrainian': 'into ukrainian language', etc.} But makemessages gives me only one string 'into %(lang)s language'. Is there anyway to generate all string? I need this because each language in different languages has different cases. Thank you. -
Djando non valid for error
HTML <form action="/manager/" method="post" > {% csrf_token %} {{ form.as_p }} <input style="margin-bottom: 10px;" type="text" class="form-control" name="firstName" required placeholder="First Name"> <input style="margin-bottom: 10px;" type="text" class="form-control" name="lastName" required placeholder="Last Name"> <input style="margin-bottom: 10px;" type="number" step="0.01" class="form-control" required maxlength="4" placeholder="Starting Wage"> <input type="submit" value="Add Employee" class="btn btn-default" aria-haspopup="true" aria-expanded="false" /> </form> models.py class employee(models.Model): firstName = models.CharField(max_length=100) lastName = models.CharField(max_length=100) wage = models.DecimalField(max_digits=4, decimal_places=2, default=13.00) def __str__(self): return self.lastName views.py def manager(request): template = loader.get_template('manager.html') all_employees = employee.objects.all() context = { 'all_employees': all_employees, } if request.method == 'POST': form = addEmployee(request.POST) if form.is_valid(): # firstName = form.cleaned_data['firstName'] # lastName = form.cleaned_data['lastName'] # wage = form.cleaned_data['wage'] # employee_obj = employee.objects.create(firstName=firstName, lastName=lastName, wage=wage) # employee_obj.save() form.save() return HttpResponse(template.render(context, request)) else: return HttpResponse(template.render(context, request)) else: return HttpResponse(template.render(context, request)) forms.py class addEmployee(forms.Form): firstName = forms.CharField(label='First Name', max_length=100) lastName = forms.CharField(label='Last Name', max_length=100) wage = forms.DecimalField(max_digits=4, decimal_places=2) I am trying to get this form to work. I had used Debug commands to try and fix it but I am not sure what I am failing to do. New to Django and trying to figure it all out :) Thanks -
Django GET ?q="parameter" in get_queryset Class Based View
How do I access the "parameter" word in the url: operations_product_search/?q=parameter here: class ASearchView(ListView): ... def get_queryset(self, **kwargs): q = self.kwargs["q"] <--- This is not working -
Django - not showing my var in template
I'm starting in Django. I'm trying to pass to my template my var to be shown in my browser but not working. here's my views.py from django.shortcuts import render from django.http import HttpResponse from preguntasyrespuestas.models import Pregunta from django.shortcuts import render_to_response # Create your views here. def index(request): string = 'hi world' return render_to_response('test/index.html', {'string': string}) here's my urls: from django.conf.urls import * from django.contrib import admin from django.contrib.auth.views import login from preguntasyrespuestas.views import index urlpatterns = [ url(r'^$', index, name='index'), ] my html: <!DOCTYPE html> <html> <head> <title> Preguntas </title> </head> <body> <p>{{ string }}</p> </body> </html> Basicaly I want to show what's in string in my template. but not working.. My error: Using the URLconf defined in django_examples.urls, Django tried these URL patterns, in this order: ^$ [name='index'] The current URL, test/index.html, didn't match any of these. What am I doing wrong? Thanks.. -
Django - Search in list
I have a list which is contain matched values from database and have a datatable on page also. So I want to search on this datatable , I pass search value template to views like: <form id="c-search" action="/supplier"method="GET"> <input type="search" name="q" autocomplete="off" placeholder="Search..."> </form> And I get value in views: if request.GET: search_value = request.GET.get('q') # sth for search return redirect('/supplier', locals()) But, I don't make search.query have filter attribute but list not have and I can't convert list to query also. Note: Why I have a list(why not query) : I can't get values different tables on database and match fromObjects.filter(foo).all(). I use the cursor execute. -
Replace PrimaryKeyRelatedField with another field
I have models which consist in a User model and a Present one. A User can have multiple Present but a Present has a unique User: My models.py is: from django.db import models from django.contrib.auth.models import User class Present(models.Model): name = models.CharField(max_length=15) price = models.FloatField() link = models.CharField(max_length=15) isAlreadyBought = models.BooleanField() user = models.ForeignKey(User, related_name='presents', on_delete=models.CASCADE) My serializers.py are: from django.contrib.auth.models import User, Group from rest_framework import serializers from blog.models import Present, Location from django.contrib.auth.models import User class UserSerializer(serializers.ModelSerializer): presents = serializers.PrimaryKeyRelatedField(many=True, queryset=Present.objects.all(), required=False) class Meta: model = User fields = ('username', 'password', 'email', 'presents') def create(self, validated_data): user = super().create(validated_data) if 'password' in validated_data: user.set_password(validated_data['password']) user.save() return user class PresentSerializer(serializers.ModelSerializer): user = serializers.PrimaryKeyRelatedField(queryset=User.objects.all(), read_only=False, many=False) class Meta: model = Present fields = ('name', 'link', 'price', 'isAlreadyBought', 'user') def create(self, validated_data): return Present.objects.create(**validated_data) Currently, if I want to get the all the presents associate with a given User, I use the primary key (in views.py): class PresentsOfUser(viewsets.ModelViewSet): queryset = Present.objects.all().filter(user=33) serializer_class = PresentSerializer However, I would rather use the username field of the User instead of the primary key. I have tried using a SlugRelatedField but I am not sure this is the right way to achieve my goal. -
Django and ajax - POST not recognized in django view
I'am quite new here so forgive my mistakes regarding format. I have been playing around with Django and Ajax. I am trying to make a slider where i can go through projects that i have done. The problem currently is that the ajax POST doesn't get recognized in the django view (or thats atleast what i am thinking - im a beginner so i might definitely be wrong). If i do a form with input and submit it gets recognized. Tried to debug it and seems that the ajax POST cant get past the if statement in django views (if request.method == 'POST'). I am trying to pass a jquery variable, that gets updated when clicking next and prev links in the html, through ajax post. This will keep the track of the id of the project. This has to go to django view in order for me to link the user input and set the id for the project to be displayed through django template. Appreciate the help, thanks a lot. Heres the setup: portfolio.html <!--generate csrftoken--> <script> function getCookie(name) { var cookieValue = null; if (document.cookie && document.cookie != '') { var cookies = document.cookie.split(';'); for (var i … -
django type error cannot concatenate str and deferred attribute objects
In the code I am connecting to my database and creating a bunch of links. I am following the tutorial here: https://www.youtube.com/watch?v=b0d09mYsORs with the code as is, the instructor is able to run the code. I am not. I am unsure what a deferred object is, and what the issue may be. I have read the docs for a while, and am requesting some assistance while I continue to push. The code: def index(request): allAlbums = Album.objects.all() html = '' for album in allAlbums: url = '/music/' + str(album.id) + '/' html += '<a href ="' + url + '">' + Album.albumTitle + '</a><br>' return HttpResponse(html) -
Django with apache2 and wsgi error
I want to run my django app in my own apache server.But when im use following config files i getting the following error. RuntimeError: populate() isn't reentrant And im not use virtualenv. Django Version : 1.10.4 Wsgi.py: import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "yuyyu.settings") application = get_wsgi_application() Apache Conf. File: <IfModule mod_ssl.c> <VirtualHost _default_:443> ServerName example.com ServerAdmin webmaster@localhost #DocumentRoot /var/www/html Alias /static /var/www/html/yuyyu/static <Directory /var/www/html/yuyyu/static> Require all granted </Directory> <Directory /var/www/html/yuyyu/yuyyu> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess yuyyu python-path=/var/www/html/yuyyu:/usr/local/lib/python2.7/dist-packages/ WSGIProcessGroup yuyyu WSGIScriptAlias / /var/www/html/yuyyu/yuyyu/wsgi.py ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined SSLEngine on SSLCertificateFile /etc/apache2/ssl/apache.crt SSLCertificateKeyFile /etc/apache2/ssl/apache.key <FilesMatch "\.(cgi|shtml|phtml|php)$"> SSLOptions +StdEnvVars </FilesMatch> <Directory /usr/lib/cgi-bin> SSLOptions +StdEnvVars </Directory> BrowserMatch "MSIE [2-6]" \ nokeepalive ssl-unclean-shutdown \ downgrade-1.0 force-response-1.0 # MSIE 7 and newer should be able to use keepalive BrowserMatch "MSIE [17-9]" ssl-unclean-shutdown </VirtualHost> </IfModule> Apache Error.log: [Fri Dec 02 20:26:53.294689 2016] [:error] [pid 8930] [remote SERVER_IP:4207] mod_wsgi (pid=8930): Target WSGI script '/var/www/html/yuyyu/yuyyu/wsgi.py' cannot be loaded as Python module. [Fri Dec 02 20:26:53.294766 2016] [:error] [pid 8930] [remote SERVER_IP:4207] mod_wsgi (pid=8930): Exception occurred processing WSGI script '/var/www/html/yuyyu/yuyyu/wsgi.py'. [Fri Dec 02 20:26:53.294800 2016] [:error] [pid 8930] [remote SERVER_IP:4207] Traceback (most recent call last): [Fri Dec 02 20:26:53.294863 2016] [:error] [pid 8930] [remote … -
Django generic authentication in views
How can I avoid needing to have this piece of code in every view function : if request.user.is_authenticated(): return HttpResponse("OK") else: return HttpResponse("Load_Login_Form") But instead execute it everytime/before an url/view is "called"? -
regex pattern not including pattern from url to html django
playing with django and I have a pattern in my url regex. the value for the album id is a number. I wish to have that number included in the ouputed html in the response. what the url looks like: http://127.0.0.1:8000/music/4/ what the returned html looks like: Details for Album id: what the returned html should look like: Details for Album id: 4 my code: the url pattern: url patterns = [ # / music/<albumid> url(r'^(?P<album_id>)[0-9]+/$', views.detail, name='detail'), ] the view method: from django.shortcuts import render from django.http import HttpResponse def detail(request, album_id): return HttpResponse("<h2> Details for Album id: " + str(album_id) + "</h2>") by what I am looking at everything is correct so I am clueless. Any ideas would be wonderful -
Celery - How to route task to local worker only
I have a Django view where a user can upload a file to process. I'd like to hand off the processing to a celery task but I need to give the task a path to the file. The problem is I have 3 servers running the Django app and the same three servers running celery workers. Is there a way I can tell Celery I only want the task to run on a worker that's on the same server where the file was uploaded? (Or is there a way better way to do this? I don't have any shared locations all three servers can see files.) -
Django-Tastypie self children
Trying to make api for multiple subtasks. I have the task model, that can have another task as a parent: class Task(models.Model): parent_task = models.ForeignKey("Task", null=True, blank=True) name = models.CharField(max_length=64) def __unicode__ (self): return self.name Now I'm trying to make tastypie resource: class TaskResource(ModelResource): parent_task = fields.ForeignKey(TaskResource, 'parent_task', full=False) <-- ERROR HERE class Meta: queryset = Task.objects.all() resource_name = 'task' list_allowed_methods = ['get', 'put', 'post', 'delete'] include_resource_uri = False def dehydrate(self, bundle, for_list=False): bundle.data["subtasks"] = "how?" <-- HOW?? return bundle Thanks for your time. P.S. I need something like this: [ { "id": 1, "name": "Task 1", "subtasks": [ { "id": 1, "name": "Task 1", "subtasks": [...] } ] }, { "id": 2, "name": "Task 2", "subtasks": "how?" } ] -
Biopython module in Django
Currently I'm working on some Django application. I have to use Entrez, so obviously I have to import Biopython. And here is my question- Do users of my app could use this function connected with Entrez even if they don't have biopython? -
Django TypeError: logout() takes at least 1 argument (1 given)
I don't understand why this url is giving me an error: from django.contrib.auth import views as auth_views from django.core.urlresolvers import reverse_lazy ... url(r'^logout/$', auth_views.logout(next_page=reverse_lazy("dashboard:operations_login")), name="operations_logout"), ... The error is: Django TypeError: logout() takes at least 1 argument (1 given) -
how to show a google map view in django admin view for a polygon field
I've been trying to show google map view for a polygon field in my django admin view without using olwidget. But against geom field I get a blank view. No map widget. I am upgrading django version in my app from 1.3 to 1.10 and need to keep compatibility with both versions so cannot use olwidget(not compatible with django 1.10). I was using olwidget to show google map widget in django 1.3 version env. In Django 1.10 there is a OSMGeoAdmin class but that doesn't give me the view that is in my second image link. So, need a way to show google map view that works in both versions of django. from django.contrib.gis.maps.google import GoogleMap from django.contrib.gis.admin.options import GeoModelAdmin from django.contrib.gis.db import models class GoogleMapAdmin(GeoModelAdmin): GMAP = GoogleMap(api_url="api-url") map_template = 'gis/google/google-map.html' class MyMapModelAdmin(GoogleMapAdmin): list_display = ('name', ) list_map = ['geom'] class MyMapModel(models.Model): name = models.CharField(max_length=100) geom = models.PolygonField() blank view previous view using olwidget -
Deploying locally made and finished django project to production server that already has Nginx
I cannot find any tutorials to upload my finished django project onto a running server using Nginx. I have been working on this for a week and I can't get the server to load anything else other than the default /var/www/html/index.nginx-debian.html. Any help or pointing in the right direction would be great. Using python3. Thanks. -
How to insert data into django app database using a web API
On a server, I have a Django app with a database. At the client, I am writing a Python script to send data through https to the server and have the server insert that data into the database. How should I approach this problem? I am in control of both the server and the client. The reason for wanting to do this is to have an API to insert data into the database. -
Django API and Web App (Architecture)
I just built an API in Django to act as a wrapper around MySQL. There are mobile clients that will interact with the API to get data. For a website, I want to build a Django application, but I'm confused as to how to approach its interaction with the Django API. Should it be in the same project and share the model? Should it be another app in the same project and not have a back-end at all and just interact with the API through calls? Help is much appreciated, thanks. -
Session in Class Based Views
I try to set session in FormView and show variable in success template,but it don't show anything. class LoginFormView(FormView): form_class = AuthenticationForm template_name = "blog/login.html" success_url = "blog/index.html" def form_valid(self, form): self.user = form.get_user() login(self.request, self.user) self.request.session["username"] = self.request.POST['username'] return super(LoginFormView, self).form_valid(form) In template I try this code {{request.session["username"]}} -
How to use visual studio code to debug django
I'm new inot django development and come from desktop/mobile app development with Xcode and related IDE. I've to use Django and I was wondering if there was a efficient way to debug it using Visual Studio Code (or Atom). Any help related to Django IDE would be helpful too. -
Wagtail Content Change Based on User Input/Location
I am working on a web site that requires English/French versions of the content, but also requires different content (in some cases, i.e. different pages/buttons) depending on user location (province). I don't want to automatically detect their location, since that is not 100% foolproof and I don't want users in a certain location seeing something that is offered to users in another province if it is not available to them. I am considering getting user input somehow when the user lands on the site, like asking them which province they are located in, and then setting a variable based on their input. Once the variable is set, I can show/hide certain content based on the variable value. Is this the best way to go about something like this? Do you have any suggestions on how to get the user input? Would a pop up box be best? Or maybe a landing page with a form where they choose their location first and then they are directed to the main site after they click? Any suggestions would be appreciated. Thank you.