Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django 1.11 don't load static image and show error in main page
I have a new problem: I don't know what is the problem, because I check it move the folder media to eventus folder, but it no working, and I change the path in MEDIA_URL, but it no working too. I think the problem will be in that I follow a tutorial of the version 1.6 of Django and some things are deferents in this new version and I don't know how to do it. my schema of the project is the next . ├── eventus │ ├── eventus │ │ ├── __init__.py │ │ ├── __pycache__ │ │ │ ├── __init__.cpython-36.pyc │ │ │ ├── urls.cpython-36.pyc │ │ │ └── wsgi.cpython-36.pyc │ │ ├── db.sqlite3 │ │ ├── settings │ │ │ ├── __init__.py │ │ │ ├── __pycache__ │ │ │ │ ├── __init__.cpython-36.pyc │ │ │ │ ├── base.cpython-36.pyc │ │ │ │ └── local.cpython-36.pyc │ │ │ ├── base.py │ │ │ ├── local.py │ │ │ ├── prod.py │ │ │ └── staging.py │ │ ├── urls.py │ │ └── wsgi.py │ ├── manage.py │ └── myapps │ ├── __init__.py │ ├── __pycache__ │ │ └── __init__.cpython-36.pyc │ ├── events │ │ ├── __init__.py │ │ … -
Group by and filter django model
I have the following data: 1, Red, Audi 2, Black, Audi 3, Black, BMW I want to get all rows that have both Red and Black colors for the same car. In this case I expect 1 and 2 in result, because Audi is both Red and Black, but not 3, since there is no Red BMW. How to achieve it with django orm? -
How to limit the number of choices in Django admin
Supposing I have two models, Group and Person, where Group is a foreignky field of Person. In the admin page, Group is represented as a drowndown/choice fields for the Person admin. Now, I want the number of choices to be limited to, say, five, and that they should be ordered according to their names. Currently, I have the following code: class PersonAdmin(admin.ModelAdmin): ... def formfield_for_foreignkey(self, db_field, request=None, **kwargs): if db_field.name == 'group': kwargs['queryset'] = Group.objects.order_by('name')[:5] return super(PersonAdmin, self).formfield_for_foreignkey( db_field, request, **kwargs) The problem is that when I try to save the record, I get the following error: AssertionError: Cannot filter a query once a slice has been taken.. I've searched for that error and found a lot of SO threads, but none of them seemed to help me with my case. -
Django Backgroundworker
I have a question to the Backgroundworker/ Django Framework. In my example, I have a Backgroundworker which sent a Websocket message to the Website. The question here: Has each Website call-up his own Backgroundworker Process? Or how can I handle that? -
Django working with external HTMLs
I am writing a small Django local project (with no access to internet). Let's say i have offline standalone version of Wikipedia(I believe it's HTML5 format) as that: . I am trying to write a simple Django front page where user would be able to click a button and be redirected to "wikipedia_for_schools/index.html" from where all the url control will be done by that offline wikipedia stand alone page. How is it possible to make? :/ I have tried creating a link in django template as <a href="/Rachel/modules/wikipedia_for_schools/index.htm" target="content">Click to see wikipedia</a> but that doesn't work cause Django complains that "http://172.30.10.67:8000/modules/wikipedia_for_schools/index.htm" Page not found, my urls.py is just urlpatterns = [ url(r'^$', views.IndexView, name='index'), and i think it's impossible to rewrite each file from wikipedia offline project to Django MVT model to provide urls, models and templates for each link. That's how my Django project structure looks like: And that's how offline Wikipedia index page looks Any help would be highly appreciated -
programmatically set columns of a tables when populating from a list
I am going to populate a django-tables2 list from a list and I am following the tutorial example: import django_tables2 as tables data = [ {'name': 'Bradley'}, {'name': 'Stevie'}, ] class NameTable(tables.Table): name = tables.Column() table = NameTable(data) My problem is that I do not know which are the fields needed, so it would be nice for me to be able to specify them at runtime from a list of names. E.g.,: needed_columns = ["name"] class NameTable(tables.Table): for field in needed_columns: ADD_FIELD(field, tables.Column()) Is this possible in some way?? -
Django Rest Framework model relations
I'm creating school project, Gallery app. I have next entities: Profile, Album, Image, Tag, Like, Comment. But i'm a little bit confused with relations. I created all, but i'm not sure everything is good. Please check: Profile: class Profile(models.Model): user = models.OneToOneField(User) albums = models.ManyToManyField("albums.Album", blank=True) commented = models.ManyToManyField("comments.Comment", blank=True, unique=False) liked = models.ManyToManyField("likes.Like", blank=True) profile_picture = models.ImageField( blank=True, null=True, upload_to='profile_pics') timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Album: class Album(models.Model): name = models.CharField(max_length=120, blank=False, null=False) owner = models.ForeignKey("profiles.Profile") description = models.TextField( max_length=500, null=True) images = models.ManyToManyField("images.Image", related_name="album_images", blank=True) is_public = models.BooleanField(default=False) timestamp = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) Image class Image(models.Model): name = models.CharField(max_length=120, blank=False, null=True) album = models.ForeignKey("albums.Album", related_name="album_id", null=True, blank=True) image = models.ImageField(verbose_name="Image", blank=True, null=True, upload_to='img') description = models.TextField(max_length=500, null=True, blank=True) comments = models.ManyToManyField("comments.Comment", related_name="all_comments", blank=True, unique=False) likes = models.ManyToManyField("likes.Like", related_name="all_likes", blank=True, unique=False) tags = models.ManyToManyField("tags.Tag", related_name="all_tags", blank=True) is_public = models.BooleanField(default=False) timestamp = models.DateField(auto_now_add=True) updated = models.DateField(auto_now=True) Tags class Tag(models.Model): name = models.CharField(max_length=120, blank=False, null=False) images = models.ManyToManyField("images.Image", blank=True) timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Likes class Like(models.Model): owner = models.ManyToManyField("profiles.Profile") image = models.ManyToManyField("images.Image") timestamp = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) Comments class Comment(models.Model): owner = models.ManyToManyField("profiles.Profile", unique=False) image = models.ManyToManyField("images.Image", unique=False) content = models.TextField(max_length=500, blank=False, null=False) timestamp = models.DateTimeField(auto_now_add=True) … -
Where can I learn Django with examples? [on hold]
I want to learn Django (intermediate level). Where can I get some good tutorials/books to learn Django? -
How to bind/trace django cache variable
I would like to save some value in Django cache and bind a trace function to it, so as soon as the value changes I would like to call a function. After the trace function has been called I would like to remove the bind. Django Cache Code. from django.core.cache import cache cache.set("MyVariable", value, None) cache.get("MyVariable") Pseudo Code: def callbackFunction(): print cache.get("MyVariable") cache.unbind("MyVariable", callbackFunction) def runOnce(): cache.bind("MyVariable", callbackFunction) # Bind Cache Variable runOnce() cache.set("MyVariable", 123, None) cache.set("MyVariable", 999, None) Expected printed result: 123 -
How can I inspect a ValidationError exception while testing with django TestCase?
I'm working with Django testing using a django.test.TestCase and I would like to know the pythonic way to inspect a validation error. I've come up with the below, which works, but it feels a little long winded and prone to error over a large number of tests self.valid_account.contact_number = "1234567" # Too short with self.assertRaises(ValidationError): try: self.valid_account.full_clean() self.fail("Did not raise validation error") except ValidationError as e: self.assertTrue('contact_number' in e.message_dict) raise e Is there a better way to inspect and test an exception? -
Heroku not loading procfile
I've tried other peoples solutions to getting there procfile recognised and it's just not working for me. Really confused about how I can get heroku to recognize my Procfile! I've moved it around into different folders and whatnot but it just won't recognise it. web: waitress-serve --port=$PORT alex1.wsgi:application This is my code. It's sitting right next to my requirements.txt file which is getting picked up by heroku fine. using echo to create the file or even echo is not working. https://github.com/Hewlbern/Videography-Website/tree/master/Alex1 <--- the github link that I'm trying to deploy to heroku from. Can see where i've placed it and etc if anyone can help! Such sad, many mad. -
Different databases for forms and authentification in django?
Is it possible to use one database for user authentifications in django and another database for working with django-forms? I work with non-relational data structures and feel comfortable with mongodb forms, but I unable to authorize my users, using mongodb. All posts describing mongodb-authentification with django referer to deprecated modules of mongoengine, which is no longer support django. So I decide to use mysql for user authentification and mongodb as main database, but cannot find information about defining special database for user authorization. -
Django-rest-framework: API documentation separate from app?
I want to be able to automatically generate API documentation for my project, but I don't want it to be published with the application itself, instead, I want it published in our local network and serve as a reference both for users of the API and the developers of the API. That is, I would want to design the interfaces first, write them as stubs, autogenerate the API documentation and publish it in the intranet. I have looked into a number of API documentation solutions, but all of them seem to add web-pages with the docs to the app itself. Is there a way to generate separate API docs? -
Django Models: Is it possible to overwrite the getter function of an attribute that is defined in an AbstractModel in its SubClass?
I have the following scenario: class AbstractProduct(models.Model): title = models.CharField(max_length=255) this abstractmodel is part of a third-party framework and therefore I cannot (should not) change the code of this abstract model. In my codebase I have the following: class Site(models.Model) domain = models.CharField(max_length=255) class ProductSiteLink(models.Model) product = models.ForeignKey(Product) site = models.ForeignKey(Site) product_title = models.CharField(max_length=255) class Product(AbstractProduct): price = models.DecimalField(decimal_places=2, max_digits=12) site = models.ManyToManyField(Site, through='ProductSiteLink') My goal is to move the title attribute of the Product to the ProductSiteLink Relation (product_title). Of course I could define get_product_title function in my Product model that looks up the right title for the product in the ProductSiteLink table and returns it. But since I cannot delete the title attribute of the Product model because it is defined in the AbstractProduct I would also have the possibility in the codebase to call product.title which would be misleading because it would return something different than get_product_title() . According to In Django - Model Inheritance - Does it allow you to override a parent model's attribute? : In normal Python class inheritance, it is permissible for a child class to override any attribute from the parent class. In Django, this is not permitted for attributes that are … -
(fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out
ERRORS: blog.Post.author: (fields.E301) Field defines a relation with the model 'auth.User', which has been swapped out. HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'. I know that I need to swap in settings.AUTH_USER_MODEL for auth.User, but for some reason doing this causes my blog to not show up. The routing is correct when I try to view blog from navigation bar but there is no content anymore. I also cannot login or create a new user on Django admin. These issues started occuring with setting an AUTH_USER_MODEL in settings for accounts. blog/models.py from django.db import models from django.utils import timezone from fitness_project import settings class Post(models.Model): author = models.ForeignKey('auth.User', related_name='User') #author = models.ForeignKey(settings.AUTH_USER_MODEL) title = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField( default=timezone.now) published_date = models.DateTimeField( blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'hello', 'blog', 'membership', 'accounts', 'django_forms_bootstrap', ] AUTH_USER_MODEL = 'accounts.User' AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', 'accounts.backends.EmailAuth', ) blog/admin.py from django.contrib import admin from .models import Post admin.site.register(Post) -
Django-reversion add new version to already created revision
I have created a "backup" functionality using the Django Reversion library for an object that keeps revision of a registered model, including the related objects (foreign keys etc.). Let's use the following case as an example. class Newspaper: title = models.CharField() class Article: newspaper = models.ForeignKey('Newspaper') When the user clicks to keep a backup of a newspaper object, a revision of the newspaper is created along with the already created articles, under the same revision. I did it so that when the user chooses to revert back to the latest backup, all related objects under the same revision to be reverted. The problem starts when a new article of the newspaper is created after the revision is created. The issue is that if the user chooses to revert to the previous revision (the one before creating the new article), the new article will still be there because it was not registered in the latest revision. Furthermore, I don't want to create a new revision every time a new article is created because then there might be other changes included that the user will not want to include to the revision. What I think might be a suitable solution, is when … -
python 3.5.2, django 1.11.5
Halo, i'm trying to upload a file using filefield. But i always failed. when statement form.errors.as_data() executed, the browser return 'tempfile'. I already trying to find solution from django documentation and some django references. But, still can't fix it. ;( Here's my view.py def dataprocessing(request): if request.method == 'POST': form = DocumentForm(request.POST, request.FILES) if form.is_valid(): import pdb; pdb.set_trace() newdoc = Document(docfile=request.FILES['myfile']) newdoc.save() #Redirect to the dataprocessing after POST #return render(request, 'dataprocessing.html') return HttpResponse("success") else: return HttpResponse(form.errors.as_data()) else: import pdb; pdb.set_trace() form = DocumentForm() #A empty, unbound form return render(request, 'dataprocessing.html', {'form': form}) models.py class Document(models.Model): docfile = models.FileField(upload_to='documents/%Y/%m/%d') forms.py class DocumentForm(forms.Form): tempfile = forms.FileField() And dataprocessing.html <form method="post" enctype="multipart/form-data" action="{% url "dataprocessing" %}"> <div class="form-group"> <label for="up">Input Data</label> {% csrf_token %} <input type="file" name=myfile class="filestyle" data-buttonName="btn-primary" data-buttonBefore="true" data-size="sm" accept="application/vnd.ms-excel, application/vnd.openxmlformats-officedocument.spreadsheetml.sheet" id="up"> </div> <div class="form-group"> <button type="submit" class="btn btn-primary btn-block">Upload Data</button> <button type="button" class="btn btn-primary btn-block">Download Template</button> </div> </form> -
How to lay out a REST Project?
I recently tried learning the django-restframework and now I want to turn my new and fragile knowledge into a test project. It is a Project that contains rendered html templates as well as an API to a React Native front-end. Is it recommendable to write all the views as APIViews (api_views for function based) instead of regular Django views (e.g. GCBV)? Since I usually declare a template_name property it the view it is - sort of -bound to the website? Or can I later declare the way I want to render dynamically depending on weather I want to render to the app or the website? Or do I need separate views for the website and app regardless? -
DRF3 Creating nested serializers on m2m-relation
I have a User-model and a Concert-model. The Concert-model has a m2m-field to the User-model. In the Concert-views, I want a list of dictionaries of the User's with a relation to the Concert-model. This is what I got: models.py class User(AbstractBaseUser, PermissionsMixin): objects = UserManager() name = models.CharField(max_length = 255, default = "") date_added = models.DateField(auto_now=False, auto_now_add=True) email = models.EmailField(unique=True, db_index=True) (more but irrelevant) class Concert(models.Model): name = models.CharField(max_length = 255) technicians = models.ManyToManyField(User) serializers.py class ConcertListSerializer(serializers.ModelSerializer): technicians = UserDetailSerializer( many=True, read_only=True, source='concert_set' ) class Meta: model = models.Concert fields = [ 'name', 'technicians', 'id', ] class UserDetailSerializer(ModelSerializer): class Meta: model = User fields = [ 'name', 'email', 'id', ] What I expect is the technicians-field in the ConcertListSerializer to be a list of dictionaries with name, email and id of the users. Why does it not provide this like the DRF Documentation on Nested Serializers says it will .. ? -
Django channels websocket disconnects after handshake
I am building a simple chat room following examples of django channels. Everything worked like a charm yesterday and I managed to create a chatroom and even managed to chat in there. All of a sudden without any change in my code the Websocket started disconnecting immediately after connection and handshake. My setup: Django == 1.10.5 Python == 2.7 channels == 1.1.8 asgi-redis == 1.4.2 daphne == 1.3.0 My consumers.py looks like this: consumers.py: @channel_session def ws_connect(message): room = message.content['path'].strip("/") message.channel_session['room'] = room Group("chat").add(message.reply_channel) message.reply_channel.send({"accept": True}) And the frontend part : $(function() { // When we're using HTTPS, use WSS too. var ws_scheme = window.location.protocol = "ws"; var chatsock = new WebSocket(ws_scheme + '://' + window.location.host + window.location.pathname); chatsock.onmessage = function(message) { var data = JSON.parse(message.data); var chat = $("#chat"); var ele = $('<tr></tr>'); console.log(data); ele.append( $("<td></td>").text(data.timestamp) ); ele.append( $("<td></td>").text(data.handle) ); ele.append( $("<td></td>").text(data.message) ); chat.append(ele) }; $("#chatform").on("submit", function(event) { var time = new Date(); var string = time.getHours() + ":" + time.getMinutes() + ":" + time.getSeconds(); // var timestamp = time.getHourMinuteSecond(); var message = { timestamp: string, handle: $('#handle').val(), message: $('#message').val() }; console.log("submit"); chatsock.send(JSON.stringify(message)); $("#message").val('').focus(); return false; }); }); Maybe an update in some technology is out. I am struggling … -
Create an estimator tool in Django Python
I am new to Django. I have read the official documentations and managed to create models in Django. I have a task to create an estimator tool that could provide the estimate(cost) to the user when he selects the hardware/softwares etc. This could be something similar to this http://calculator.s3.amazonaws.com/index.html. This is only for reference but I want to add details dynamically and I want to have edit option also for the details added. So far I have come to this below point (check image for reference) but I cannot edit this once I save. Could anyone direct me to any tutorial/project that I can follow to achieve my task? -
Issue with Django Template Background
I'm getting an issue with my background template picture. Each time I'm loading Django template, my background is black in the first time, then becomes good with my picture after 0.5/1 second. I wrote in my script (Common HTML Template) : {% load staticfiles %} {% load static %} {% load user_tags %} {% load variables %} <style> body { background-image:url("{% get_static_prefix %}{{ mytheme }}/images/bg.jpg"); } </style> The url path is good because my picture is loaded, but I have this black background before during ~ 1s I didn't write background picture in my CSS file, but only in my common template (navbar template which is called each time). Do you have any idea ? -
How to overwrite django-redux default user registration form
When the default django-registration-redux registration page loads, it displays fields for username, email, password, along with labels instructing the user on minimum xters for username, and a list of instructions on setting password. I want to be able to add some fields to the form, also, I want to remove the list of instruction labels. I could do it with JS but how do i overwrite the class from the django-registration-redux. Pls i really need help. I have tried subclassing different classes, yet no headway. -
How socket file is created in Gunicorn
I am deploying a Django project using Gunicorn as application server and Nginx as a web server. This is the tutorial http://tutos.readthedocs.io/en/latest/source/ndg.html which I am following. Code for the gunicorn_start.sh (kept in the folder where the project resides). #!/bin/bash NAME="visualization" DJANGODIR=/var/www/dist/adc # Django project directory* SOCKFILE=/var/www/dist/run/gunicorn.sock USER=barun GROUP=barun NUM_WORKERS=1 DJANGO_SETTINGS_MODULE=adc.settings DJANGO_WSGI_MODULE=adc.wsgi echo "Starting $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source /home/barun/anaconda3/envs/adcenv/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist RUNDIR=$(dirname $SOCKFILE) test -d $RUNDIR || mkdir -p $RUNDIR exec /home/barun/anaconda3/envs/adcenv/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ #we should put the address gunicorn address --name $NAME \ --workers $NUM_WORKERS \ --user $USER \ --bind=unix:$SOCKFILE Code for gunicorn.service (/lib/systemd/system/gunicorn.service): [Unit] Description=visualization gunicorn daemon [Service] Type=simple User=barun WorkingDirectory=/var/www/dist ExecStart=/home/barun/anaconda3/envs/adcenv/bin/gunicorn --workers 3 -- bind unix:/var/www/dist/run/gunicorn.sock adc.wsgi:application [Install] WantedBy=multi-user.target Everything is working fine. The location is given in gunicorn_start.sh file for creating a socket file, the run folder is created but gunicorn.sock file is not creating. There is not permission related problem Apart from this, The error I am getting in Nginx error.log file is: 4783#4783: *1 connect() to unix:/var/www/dist/run/gunicorn.sock failed (2: No such file or directory) while connecting to upstream, client: 172.16.1.213, server: 192.16.1.213, request: "GET / HTTP/1.1", upstream: … -
Django How to make use of the creation method for a custom user with permissions?
So I have this method: def create_editor(self, email, dob, password): user = self.create_user( email, dob, accepted_tos=True, password=password ) try: editors = Group.objects.get(name__iexact="Editors") except Group.DoesNotExist: editors = Group.objects.create(name="Editors") editors.permissions.add(Permission.objects.get(codename="can_give_discount")) # add can_give_discount permission user.groups.add(editors) user.save() return user To create a normal user and then add the user to the editor group I want to be able to create a manager from the normal django admin. But it looks like I have to manually create the group from the admin side.