Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django database objects not displaying
I keep getting <QuerySet [<Member: - >]> whenever I try to display all objects within a model class through Member.objects.all() in the shell. This is my code, note that the Book class is displaying them correctly when I call all objects, but the Member class does not: class Book(models.Model): Titel = models.CharField(max_length=100) Author = models.CharField(max_length=100) Genre = models.CharField(max_length=100) ISBN13 = models.CharField(max_length=13) def __str__(self): return self.Author + ' - ' + self.Titel class Member(models.Model): Name = models.CharField(max_length=15) Surname = models.CharField(max_length=15) Mailadres = models.CharField(max_length=15) Birth = models.DateField(auto_now_add=True, auto_now=False) Leerlingnummer = models.CharField(max_length=15) def __str__(self): return self.Name + ' - ' + self.Surname -
Django authentication and permissions
I posted a question on SO that had various questions regarding the confusion that I have on this particular matter. I was told that I should break down my questions into little pieces since my question was too broad, so here I go. I have a backend ready with a lot of views, models and serializers from DRF. Now I want to apply authentication to my app and create RESTful apis that are consumed at the front-end. So the doubts that I have How does authentication work? Does Django create different model tables for each of its user? If so, how do I retrieve data per user from Django? Now comes the second case If above two are true, then how do I go about using permission in DRF to serve only the data that is relevant to a particular user? I hope my questions are clear. In case they are not, suggest me edits. I'd also like some examples(if any) on how does this all happens. Also, if you want to see the original post. -
Nodejs post file to Django without using multipart
Im trying to post a single file to Django server using nodejs, but Im too lazy to composed a multipart payload because the only purpose that django interface serving is to receive a file. so in nodejs code I do this: var options = url.parse('http://my_django_file_interface'); options.method = 'post'; options.headers = {'content-type': 'application/octet-stream'} var req = http.request(options); var read_stream = fs.createReadStream('file/need/to/upload'); read_stream.pipe(req); and in my django's view: def receiveFile(request): print request.read(10000) print request.body print request.POST print request.FILES return httpResponse('fine') but none of those 'print' yield a thing. my question is where is my uploaded file? is Django too smart so he drops the payload somehow? -
How to prevent Django's label_tag function from escaping the label?
Example: >>> example.label &#x3bb;<sub>blabla</sub> >>> example.label_tag() [...]&amp;#x3bb;&lt;blabla&gt;[...] Even calling mark_safe(example.label) before label_tag() does not prevent Django from escaping the HTML. How can I get label_tag() to return unescaped labels? -
Docker and Nginx proxy_pass between containers
I'm trying to run configuration with Docker, Nginx, Gunicorn and Django. Currently I successfully managed to run my container with Gunicorn and Django app using this command: docker run --publish 8003:8000 user/app:latest Now when I connect to localhost:8003 I see my application running. At this point I would like to set up my Nginx in container to point to this app whenever I browse to localhost/app My Nginx.conf file looks like this: ... http { server { listen 80; location /app { proxy_pass http://127.0.0.1:8003; proxy_set_header Host $host; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; } } } ... I run it with: docker run --publish 80:80 user/nginx:latest This does not work and I can't wrap my head around this, thanks for any ideas how to solve this problem! -
Django Tutorial 1 - ImportError: No module named apps
I am following this Tutorial: https://docs.djangoproject.com/en/1.10/intro/tutorial02/ In subsection "Activating models" i should add some code in the mysite/settings.py INSTALLED_APPS = [ 'polls.apps.PollsConfig', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] when i run the command python manage.py makemigrations polls i get the following errormessage Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 354, in execute_from_command_line utility.execute() File "/usr/lib/python2.7/dist-packages/django/core/management/__init__.py", line 328, in execute django.setup() File "/usr/lib/python2.7/dist-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/lib/python2.7/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/lib/python2.7/dist-packages/django/apps/config.py", line 112, in create mod = import_module(mod_path) File "/usr/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) ImportError: No module named apps i don't have a folder or a file called "apps" in my "polls" folder, so i am wondering about the "polls.apps.PollsConfig" syntax. i found some posts in the web telling that in django version 1.7 there where some changes. I am using: Ubuntu 16.04 LTS Python 2.7.11+ django.VERSION (1, 8, 7, 'final', 0) -
How can I test a form with FileField in Django?
I have this form: # forms.py class BookForm(forms.ModelForm): class Meta: model = Book fields = ['book_title', 'language', 'author', 'release_year', 'genre', 'ages', 'cover'] Type of fields: Where book_title and author are CharField, language and genre are too CharField but for them I have choice option, release_year and ages are IntegerField, and the last cover are FileField. Choice Options: # models.py ENGLISH = 'english' LANGUAGE_CHOICES = ( (ENGLISH, 'English'), ) ADVENTURE = 'adventure' GENRE_CHOICES = ( (ADVENTURE, 'Adventure'), ) Now: I want to test this form, but I don't know how can test cover, here is my form test. # test_forms.py from .. import forms from django.core.files import File class TestBookForm: def test_form(self): form = forms.BookForm(data={}) assert form.is_valid() is False, 'Should be invalid if no data is given' img = File(open('background')) data = {'book_title': 'Lord Of The Rings', 'language': 'English', 'author': 'J. R. R. Tolkien', 'release_year': 1957, 'genre': 'Adventure', 'ages': 16, 'cover': img} form = forms.BookForm(data=data) assert form.is_valid() is True I tried: from django.core.files.uploadedfile import SimpleUploadedFile img = open('background') uploaded = SimpleUploadedFile(img.name, img.read()) {'cover': uploaded} This is my error: E assert False is True E + where False = <bound method BaseForm.is_valid of <BookForm bound=True, valid=False, fields=(book_title;language;author;release_year;genre;ages;cover)>>() E + where <bound method … -
Django: Add user to group via Django Admin
How can I add users to a group in Django admin interface of "Change Group"? I have seen dirty hacks to get this working for older django version. How to solve this with Django 1.10? emphasize: I want this on the page "Change Group", not on "Change User". -
Installed georasters successfully but unable to import it
I installed georasters using "pip install georasters".But I am unable to import it in python.The following error comes: Traceback (most recent call last): File "<pyshell#0>", line 1, in <module> import georasters File "D:\Python\lib\site-packages\georasters\__init__.py", line 3, in <module> from .georasters import get_geo_info, map_pixel, map_pixel_inv, aggregate, create_geotiff, align_rasters, \ File "D:\Python\lib\site-packages\georasters\georasters.py", line 37, in <module> import pandas as pd File "D:\Python\lib\site-packages\pandas\__init__.py", line 25, in <module> from pandas import hashtable, tslib, lib File "pandas\src\numpy.pxd", line 157, in init pandas.hashtable (pandas\hashtable.c:38509) ValueError: numpy.dtype has the wrong size, try recompiling Kindly clarify. -
Django authentication with DRF
I have developed a RESTful backend with a lot of django views and a lot of model fields in Django with their serializers serializing data for frontend consumption. Now I need to develop an authentication system and I am really confused about it. The questions that I have in my mind are - Should I make a different model that holds user credentials and check against each post request? If so, should I make all other models refer to this model with a foreign key? If not, then how to store data per user and filter get requests on the front-end per user to get only the data associated with that particular user? How does token works? How does a token sent from the front-end validates at the back-end, when each time a user logs-out and logs back in, a new token is sent? (i.e. How does backend knows the token at the front-end has changed) I know my questions are quite naive but I am relatively new and google does not return the right answers to such queries(tried that), or maybe I am querying things wrong. Any help or guidance is appreciated and you can also correct my questions … -
Multiple generic.ListView in Django
I would like to know if possible to have a multiple (generic.ListView) in a view. like this. TIA class AboutView(generic.ListView): template_name = "mrswabergerApp/header.html" model = mrsAbout context_object_name = 'about' def get_queryset(self): return mrsAbout.objects.all() class IndexView(generic.ListView): model = mrsBlogs template_name = "mrswabergerApp/index.html" context_object_name = 'blogs' def get_queryset(self): return mrsBlogs.objects.all() -
Django rest swagger api list contain its own url
My urls.py shows below: urlpatterns = [ url(r'^v1/', include('apps.api.urls')), url(r'^docs/$', schema_view) ] I don't know why it shows docs, can i remove it and how -
Django get renamed uploaded image url
I am working on a project that will allow the user to upload image. The uploaded image will later on displayed and be passed to another form. To do this, I need to get the image url of the uploaded image. Here is my code: def inputImage(request): if request.method == 'POST': form = ImageDetailsForm(request.POST, request.FILES) if form.is_valid(): form.save() message = "The image was successfully uploaded!" imageName = str(request.FILES['image'].name) imageURL = settings.MEDIA_URL + "/" + imageName return render(request,'success.html', {'message': message, 'image': imageURL}) The code is working, however a problem would occur if the user uploads a file with an existing filename at the storage. To avoid conflict, Django automatically renames the file but the line imageName = str(request.FILES['image'].name) only returns the original filename of the uploaded image. I have also tried to use imageName = str(form.cleaned_data['image'].name) but still no changes. It returns "/media//1.png" instead of "/media//1_0rnKMaT.png" Any ideas on how to get the URL of the current upload in Django? -
Django & Allauth Login Redirect Issue
For some reason after login the page doesn't redirect to where LOGIN_REDIRECT_URL points but remains on a blank page /accounts/login/ with code 200. So, after login I get a blank page and have to refresh (F5) to get to my LOGIN_REDIRECT_URL. After the refresh I am successfuly loged in. ACCOUNT_LOGOUT_REDIRECT_URL works fine, returns code 302 and redirects directly without a blank page but LOGIN_REDIRECT_URL doesn't. If I change the LOGIN_REDIRECT_URL after refresh I am redirected to the changed location, this works fine. But first I am always stuck on a blank page /accounts/login/. Can't find out why this happens. There is no error message, I haven't find any issue in the AllAuth LoginView. There is not much code to show, this is built-in django and allauth functionality that i have successfuly used in other apps on lesser django version, this is my first project with django 1.10.1. It is also my first mobile project with jquery mobile functionality. So here is my settings: DEBUG = True ALLOWED_HOSTS = ['*'] SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') INSTALLED_APPS = [ 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', #'django.contrib.flatpages', 'appconf', 'avatar', 'myApp', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', 'django.contrib.admin', 'lockdown', ] MIDDLEWARE_CLASSES = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', … -
How to control representation of relation inside a serializer in DRF?
I have several serializers with related fields or serializers as fields, but with the default configuration of Django Rest Framework, either everything is dumped, or only the ID, or a URL. I want to be able to control the verbosity of the representation a bit more: sometime I want just the ID or my related field; sometime I want the full object dump. I may want the ID in ouput, and the dump in output. Right now I have to serialize everything manually because I can't find a quick and easy way to tell DRF, hey, here just do this. Is there such a way ? -
how to define Django settings without default DB settings?
According to Django Docs we can define empty django settings like this {} but it still raises error . """ Django settings for impactFund project. For more information on this file, see https://docs.djangoproject.com/en/1.6/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/1.6/ref/settings/ """ # Build paths inside the project like this: os.path.join(BASE_DIR, ...) import os BASE_DIR = os.path.dirname(os.path.dirname(__file__)) PROJECT_PATH = os.path.split(os.path.abspath(os.path.dirname(__file__)))[0] # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/1.6/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 's^(gvcg1_!!!8wnpikp[hj4+%ypay1$zsf54=j6o3cuuxigjxiscqno' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True TEMPLATE_DEBUG = True ALLOWED_HOSTS = ['*'] # Application definition INSTALLED_APPS = ( 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.humanize', 'Ken_app', 'app', 'captcha', 'django.contrib.sites', 'treebeard', 'djangocms_text_ckeditor', 'cms', # django CMS itself 'mptt', # utilities for implementing a modified pre-order traversal tree 'menus', # helper for model independent hierarchical website navigation #'south', # intelligent schema and data migrations 'sekizai', # for javascript and css management 'djangocms_admin_style', # for the admin skin. You **must** add 'djangocms_admin_style' in the list **before** 'django.contrib.admin'. # to enable messages framework (see :ref:`Enable messages <enable-messages>`) ) MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.gzip.GZipMiddleware', … -
Django model id turns into a tupple
I have a superClass for my models as below class BaseModel(models.Model): """ BaseClass vase aksare model ha """ def __init__(self, *args, **kwargs): super(BaseModel, self).__init__(args, kwargs) print('******> base model __init__') status = models.IntegerField(default=1) is_deleted = models.BooleanField(default=False) create_user = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_creator_related") create_date = models.DateTimeField() update_date = models.DateTimeField() update_user = models.ForeignKey(User, related_name="%(app_label)s_%(class)s_updater_related") class Meta: abstract = True def validate(self): print('^^^^^^^^^^^^^^^^^^^^^^^^^^^^base validation') and I have a profile model as below class Profile(BaseModel): def __init__(self, *args, **kwargs): super(Profile, self).__init__(args, kwargs) """ User profile """ user = models.OneToOneField(User, related_name='profile') mobile = models.CharField(max_length=25, null=True) firstname_en = models.CharField(max_length=500, null=True) lastname_en = models.CharField(max_length=500, null=True) gender = models.IntegerField(default=0) birth_date = models.DateTimeField(null=True) edu_bg = models.ForeignKey('Category', related_name="profile__edu_bg", null=True) region = models.ForeignKey('Category', related_name="profile__region", null=True) credit = models.DecimalField(default=0, decimal_places=6, max_digits=15) key = models.TextField(null=True) secret = models.TextField(null=True) I have an erro when I want to insert a new userProfile as below: TypeError: int() argument must be a string, a bytes-like object or a number, not 'tuple' then print the vars(userprofileObject) and realized that 'id': ((), {}), however, I have not set it. When I removed the init functions or set id to None in insertion code, problem solved. Any idea? I need those init and also dont want to set id=None in my code -
Django upload limits
I want to make've limited the number of users on the upload file. For example: Every day, users are limited to 1 image file. Views class Upload(views.LoginRequiredMixin, generic.CreateView): model = Posts form_class = UploadForm template_name = 'icerik_yukle.html' def form_valid(self, form): self.object = form.save(commit=False) self.object.author= self.request.user self.object.save() return super(Upload, self).form_valid(form) Models class Gonderi(models.Model): author= models.ForeignKey(User, related_name="gonderi") slug = models.SlugField(unique=True, max_length=10, default=id_olustur) image = models.FileField(upload_to=yukleme_adresi, blank=True) subject= models.CharField(max_length=50, blank=True) descrip = models.TextField(max_length=250, blank=True) category= models.ForeignKey(Kategori, verbose_name="Kategori") tags = TaggableManager() created= models.DateTimeField(auto_now_add=True) updated= models.DateTimeField(auto_now=True) is_public = models.BooleanField(verbose_name='Göster', default=True) -
DjangoORm:Apply order by on Foreign key fileds
class Game(models.Model): player = models.ForeignKey(place, null=True, blank=True, verbose_name="place") total_score = models.ForeignKey(score, null=True, blank=True, verbose_name="place") class Place(Time): child = models.CharField(max_length=100, blank=True, verbose_name="child", db_index=True) class Time (models.Model): time = models.CharField(max_length=100, null=True, blank=True, verbose_name="time") I want to sort the data based on time Django Orm to retrieve data & applying order by in descending order Game.objects.filter(...).order_by('-player__time ') Somewhere I am missing.Can someone point to the problem? -
django json response and ajax call
Kindly let me know how to consume django api method using jquery ajax call, because when I try to access directly URL am getting response, however when I send request using jquery ajax call, it goes to error function. Dajango code: def rain_api(request): data = {} data['test'] = 'hello' return HttpResponse(json.dumps(data), content_type = "application/json") JQuery code: requestURL="http://ipaddress/raindata $.ajax({ url: requestURL, dataType: "json", success:function(result){ console.log(result) }, done:function(result){ console.log(result) }, error:function(error){ console.log(error); } }) -
model IntegerField() to django-template with ordinal
I have a model with IntegerField() class Room(models.Model): type = models.CharField(max_length=50) floor = models.IntegerField() And i would like it to display in a template with ordinal suffix. {% for room in rooms %} <div> <p> {{ room.type }}</p> <p> {{ room.floor }} </p> </div> {% endfor %} I would like the floor output like this. 1st, 2nd, 3rd, 4th... 10th.. 12th.. 13th.. 15th... -
Django - urls.py and views.py and resolving error 404
I'm fairly new to django. I completed the django project tutorial, and took away a good understanding of it, at least I thought I did. My understanding of how urls.py and views.py are related is urls.py points to the function of views.py and looks for a file to execute based on a page. Here is my file structure: The root folder is right above the "friendfinder" folder called "ff" The 404 error I have shows on all 3 static html pages: index, friends, and contacts. Here is what my urls.py page looks like: from django.conf.urls import url from gather import views urlpatterns = [ url(r'^interest/', views.InterestView.as_view(), name="interest"), url(r'^$', views.index, name="index"), url(r'^friends/', views.friends, name="friend"), url(r'^contact/', views.contact, name="contact"), ] This is my views.py page: import json from django.http import HttpResponse from django.http import JsonResponse from django.shortcuts import render from django.views import View from gather.models import Interest def index(request): all_interests = Interest.objects.all() return render( request, ' gather/index.html', { 'stuff': 'TEST', 'interests': all_interests } ) def friends(request): return render(request, 'gather/friends.html') def contact(request): return render(request, 'gather/contact.html') class InterestView(View): def post(self, request): try: json_data = json.loads(request.body.decode('utf-8')) new_interest = Interest( name=json_data['name'], description=json_data['description'], approved=False ) new_interest.save() return HttpResponse('ok') except ValueError: return HttpResponse('Fail', status=400) def get(self, request): try: search … -
r'^(?P<pk>\d+)$ URL 404ing
I'm trying to use this link <a href="Annotation/{{ vod.id }}"> to load another page in my website base on primary key of videos. My url file is as follows: urlpatterns = [ url(r'^$', ListView.as_view(queryset=Vod.objects.all().order_by("-date")[:25], template_name="Annotation/home.html")), url(r'^(?P<pk>\d+)$', ListView.as_view(queryset=Vod.objects.get(pk=1).posts.all().order_by("-date"), template_name="Annotation/post.html")), ] I get the standard 404 from the links generated using the aforementioned link. As a side note, I was also wondering how to use the link or url to know which pk to use when generating pages with this url. Right now, for debugging purposes, I'm just using qureyset=Vod.objects.get(pk=1). Thanks! -
django foreign key lookup aggregate data
I am making a tool inventory/tracking system. My current question is how can I gather the total number of tools that are currently checked out, and subtract that amount from the total quantity that I have of that tool. So that I can display a quantity on hand. So that a user can make sure that the tool is currently in the shop and is not checked out by someone borrowing it. Models: class ActiveTransactionManager(models.Manager): def get_queryset(self): return super(ActiveTransactionManager, self).get_queryset().filter(CheckInDate = None) class Tool(models.Model): ToolID=models.CharField(max_length=100, primary_key = True, unique=True, db_column='ToolID') Quantity=models.IntegerField(null=False) Location=models.CharField(max_length=100, null=False) CategoryID=models.IntegerField(null=True) Deleted=models.BooleanField(default=0) objects=models.Manager() class Meta: managed=True db_table='Tool' def __unicode__(self): return self.ToolID def get_absolute_url(self): return reverse("ToolSearch:toolSearchResults", kwargs={"pk": self.ToolID}) class ToolCheckIn(models.Model): CheckOutID=models.AutoField(primary_key=True) ToolID=models.ForeignKey(Tool, db_column='ToolID', on_delete=models.CASCADE,) PartyID=models.ForeignKey(Borrower, db_column='PartyID', on_delete=models.CASCADE,) Quantity=models.IntegerField(null=False) CheckOutDate=models.DateField(null=False, default=datetime.datetime.now) CheckInDate=models.DateField(null=True) Deleted=models.BooleanField(default=0) objects=ActiveTransactionManager() class Meta: managed=True db_table='ToolTransaction' ordering=('CheckOutID',) def __unicode__(self): return str(self.CheckOutID) def get_absolute_url(self): return reverse("ToolSearch:toolCheckin", kwargs={"pk": self.CheckOutID}) View: def tool_search(request): if request.method == 'POST': instance = None pk = (request.POST.get('toolid', 'Nothing Found')) instance = Tool.objects.all().filter(ToolID__icontains=pk) context = { "ToolID": instance } return render(request, "toolsearchresults.html", context) return render(request, "toolsearch.html") I was receiving this error: Related Field got invalid lookup: icontains I have removed the line of code in my view that is listed above that was causing the … -
Django Model to Associative Array
Is there any way to convert a django models to an associative array using a loop for HttpResponse. class Guest(models.Model): fname = models.CharField(max_length=200) mname = models.CharField(max_length=200, default="", blank=True, null=True) lname = models.CharField(max_length=200) gender = models.CharField(max_length=20, choices=gender_choices, default="") birth_date = models.DateField() address = models.TextField() phone = models.CharField(max_length=20) mobile = models.CharField(max_length=20, default="", blank=True, null=True) fax = models.CharField(max_length=20, default="", blank=True, null=True) email = models.CharField(max_length=200) id_type = models.CharField(max_length=200, default="", blank=True, null=True) id_number = models.CharField(max_length=200, default="", blank=True, null=True) my expected result was like this { "fname" : "sample", "mname" : "sample", "lname" : "sample", ... }