Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Access request user and url parameters in django decorator
I am trying to eliminate redundant code by creating a decorator to handle simple logic that is always repeated. Basically every view I create has the following logic to check if a user is in a class. @login_required def view(request, class_id): class_ = UserClasses.objects.get(user=request.user, class_id=class_id) # if the user is in the class if class_: I'd like to do the following: View: @user_passes_test(in_class(request.user, class_id)) @login_required def view(request, class_id): Decorator: from apps.classes.models import UserClasses def in_class(request, class_id): class_ = UserClasses.objects.get(user=request.user, class_id=class_id) if class_: return true else: return false What's the best way to go about achieving this? -
ArrayField to store custom Field value
I want to use an arrayfield to store a list of json strings which represent a specific custom class. What I have done is: from django.contrib.postgres.fields import JSONField, ArrayField from django.db import models # other imports class MyCustomField(models.Field): a = models.FloatField(blank=True, null=True) b = models.DateTimeField() c = JSONField(blank=True, null=True) def db_type(self, connection): return 'Text' def rel_db_type(self, connection): return 'integer UNSIGNED' def to_python(self, value): return json.loads(value) def get_prep_value(self, value): return json.dumps(value) class A(models.Model): # ... various normal fields here, then: pres = ArrayField(MyCustomField) def get_absolute_url(self): return reverse('foo:bar', kwargs={'pk': self.id}) But: python manage.py makemigrations throws the following error File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/contrib/postgres/fields/array.py", line 75, in set_attributes_from_name self.base_field.set_attributes_from_name(name) TypeError: set_attributes_from_name() missing 1 required positional argument: 'name' The full traceback is: Traceback (most recent call last): File "manage.py", line 13, in <module> execute_from_command_line(sys.argv) File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/core/management/__init__.py", line 367, in execute_from_command_line utility.execute() File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/core/management/__init__.py", line 341, in execute django.setup() File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models(all_models) File "<path_to_my_virtualenv_dir>/lib/python3.5/site-packages/django/apps/config.py", line 199, in import_models self.models_module = import_module(models_module_name) File "<path_to_my_virtualenv_dir>/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, … -
limit n results per group by - Django queryset
I am trying to create a query where I can pull the last 3 forum posts per category that is shown on the screen. Here is the way my model is setup: class ForumCategory(models.Model): name = models.CharField(max_length=40) description = models.TextField() class_id = models.ForeignKey(Class) class ForumPost(models.Model): name = models.CharField(max_length=100) details = models.TextField() author = models.ForeignKey(User) class_id = models.ForeignKey(Class) category = models.ForeignKey(ForumCategory) created_at = models.DateTimeField(auto_now_add=True) My current query returns the 3 most recent posts in general and not 3 per category: categories = ForumCategory.objects.filter(class_id=class_id) forum_post = ForumPost.objects.filter(category_id__in=categories.values_list('id', flat=True)).order_by('-category_id')[:3] So I first grab all categories that belong to a specific class and I want to list those categories along with the 3 most recent posts in each category. -
AngularJS and Django open a new HTML file on Button click
I am using AngualrJS for the frontend and Django for the backend of my website. Also, I am new to Django and AngularJS. I got my website running, now I want to open another site on a button click (method name: search). The html file that should be opened is in my templates folder (SearchResults.html). I tried different variants but nothing is working: <!DOCTYPE html PUBLIC> {% load staticfiles %} <html> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1"> <!-- Die drei oberen meta tags *müssen* zuerst im Head-Tag angegeben werden; alle anderen Tags können anschließend eingefügt werden --> <title>Next Event</title> <!-- Bootstrap --> <link href="{% static 'css/bootstrap.min.css' %}" rel="stylesheet"> </head> <script type="text/javascript" src="http://api.eventful.com/js/api"></script> <!-- jQuery (notwendig für Bootstraps JavaScript plugins) --> <script src="{% static 'js/jquery-3.2.1.min.js' %}"></script> <!-- Alle kompilierten plugins einbeziehen --> <script src="{% static 'js/bootstrap.min.js' %}"></script> <!-- Angular --> <script type="text/javascript" src="https://cdnjs.cloudflare.com/ajax/libs/angular.js/1.6.1/angular.min.js"></script> <!-- Main Datei für Javascript (tutorial) --> <script type="text/javascript" src="{% static 'js/main.js' %}"></script> <body ng-controller='NextController'> <div class="container-fluid"> <h1>Next Event</h1> <div class="form-group"> <label for="usr">Location</label> <input type="text" class="form-control" id="where" placeholder="Please enter a city." ng-model="query_params.location"> </div> <div class="form-group"> <label for="usr">Category</label> <input type="text" class="form-control" id="category" placeholder="Please enter a category." ng-model="query_params.category"> </div> <button ng-click="search()" type="button" class="btn btn-primary">Search</button> <p><br></p> <p … -
Speeding up django queries in large MySQL tables? (>2 million rows)
Hello fellow django programmers, I have a project, which stores measurement values of batteries (voltage, temperature, current, ...) in a MySQL database and plots the data in a chartit diagram. The user has to choose the period of time, in which he wants to see the measured values. The battery sends its values every five seconds to the server, so that I have more than 2 million rows in one table now. If the user wants to view the course of the battery values in the last month, I don't need the full "resolution" of all measurements every five seconds. Only one per hour or something like that. My current solution is, that all entries are collected and then only every 500. is given back to the browser, but that's not very efficient and it takes ~6-8 seconds to load the web page. How do I improve the query, so that I don't have to select all entries in the table and thus speed up the retrieving of the measurement data for a long period of time? Or should I migrate to another database system? I'm grateful for any suggestions. -
Show plus sign in Django template
Is there a filter in Django to print a positive float variable with a plus sign? e.g. 1.234 as +1.234 -
Best structure for Django project for multiple sites based on the same backend logic?
I've began working on a new large project - many city-based webshops, each working on its own subdomain of the one domain, for example, citydomain.webshop.com. There whould be about 40 of these websites at start to run simultaneously. Project's backend business logic and template styling is the same on every site. Some static files and database data would be both general across all sites and site-specific (logs, images, selling items, orders, etc.). My question is how to implement the best possible architecture in such a way that a certain user visiting the same URLs on different subdomains would get that subdomain's specific data processed by the same backend logic. I assume the following options of the possible architecture: 1) Django project instance: one instance for all sites OR many instances for each site? The first way seems far more logical than the second one in terms of DRY principle. I believe that ideally there should be ONE project instance with many subfoolders with subdomains' names for each site's specific images, logs, etc. 2) Database: one db for all sites OR many databases for each site? I tend to have ONE database too because of the same DRY principle. The great … -
Display editable decimal field with trailing currency symbol in admin interface (Django)
I have a simple model: class Product(models.Model): ... price = models.DecimalField(max_digits=4, decimal_places=2) ... def price_currency(self): return '%.2f €' % self.price And admin model: class ProductAdmin(admin.ModelAdmin): list_display = ['price_currency'] Achieves this list overview of products (only price column screenshot): The problem is that this field is not editable (in list view). Is there a way to make it editable and display the trailing currency symbol at the end? I can just call list_display = ['price'] and list_editable = ['price'], the problem is that then it does not show the euro sign at the end, ie: My ideal end goal would be: -
Are these VirtualHost settings workable with Django?
I'm deploying a Django app on a client's website and do not have direct access to the httpd.conf files. Site support has created the following for me but there does not seem to be any combination of STATIC_ROOT and STATIC_URL that I can get to work with this. Is it even possible? NOTE: the Django/Python pages are being served just fine on subdomain.mywebsite.com--I'm only missing the static files. (Sorry to obfuscate the URLs and IPs...client is very private.) NameVirtualHost ##.###.###.# <VirtualHost ##.###.###.#> DocumentRoot /home/httpd/html/subdomain.mywebsite.com/public_html ScriptAlias /cgi-bin /home/httpd/html/subdomain.mywebsite.com/cgi-bin ServerName www.subdomain.mywebsite.com CustomLog /home/httpd/logs/subdomain.mywebsite.com_access_log combined ServerAlias subdomain.mywebsite.com Alias /static/ /home/httpd/html/subdomain.mywebsite.com/public_html/static/ #<Directory /home/myusername/rym_notices/static> <Directory /home/httpd/html/subdomain.mywebsite.com/public_html/> allow from all </Directory> <Directory /home/httpd/html/subdomain.mywebsite.com/public_html/> <Files wsgi.py> allow from all </Files> </Directory> ProxyPreserveHost On ProxyPass / http://127.0.0.1:8000/ ProxyPassReverse / http://127.0.0.1:8000/ </VirtualHost> -
What is best way of implementing ajax with django so debugging is possible
What is best way of implementing ajax with django. The problem I faced is that for example when using djangorestframework decorator for implementing ajax, the code is impossible to debug in django log. For example, I couldn't get that the I need to use BigInteger field instead of IntegerField because Django didn't log out index out of range error which was only raised when I tested the same command seperetly in shell. Another way, is writing tests, but what is the most simple and clean way of using ajax with django? -
Django+gunicorn service mistake?
I tried to deploy django on my server via this tutorial I have a problem with configurating gunicorn.service. When I do sudo systemctl start gunicorn sudo systemctl enable gunicorn sudo systemctl status gunicorn I get gunicorn.service - gunicorn daemon Loaded: loaded (/etc/systemd/system/gunicorn.service; enabled) Active: failed (Result: exit-code) since Sat 2017-05-13 11:47:49 MSK; 29s ago Main PID: 56584 (code=exited, status=203/EXEC) May 13 11:47:49 debian systemd[1]: Starting gunicorn daemon... May 13 11:47:49 debian systemd[1]: Started gunicorn daemon. May 13 11:47:49 debian systemd[56584]: Failed at step EXEC spawning /opt/bl...ry May 13 11:47:49 debian systemd[1]: gunicorn.service: main process exited, c...EC May 13 11:47:49 debian systemd[1]: Unit gunicorn.service entered failed state. Hint: Some lines were ellipsized, use -l to show in full. My structure of the project splitpoint@debian:/opt/blog$ tree . ├── myproject │ ├── manage.py │ ├── myproject │ │ ├── gunicorn.config.py │ │ ├── __init__.py │ │ ├── __init__.pyc │ │ ├── settings.py │ │ ├── settings.pyc │ │ ├── urls.py │ │ └── wsgi.py │ └── static │ └── admin │ ├── css │ etc └── venv ├── bin │ ├── activate etc My gunicorn.service [Unit] Description=gunicorn daemon After=network.target [Service] User=splitpoint Group=www-data WorkingDirectory=/opt/blog/ ExecStart=/opt/blog/venv/bin/gunicorn --workers 3 --bind unix:/opt/blog/myproje$ [Install] WantedBy=multi-user.target How can I … -
How to use Objects.filter() for a list in Mezzanine/Django?
I am facing difficulty in querying element from database. Keyword is an field in BlogPost table which is list. e.g keyword=['python','java','django'] slug=java blogs = BlogPost.objects.filter(keyword__contains==slug) How to resolve this ? -
WSGI cannot be loaded as Python module
I'm getting this error 'path-to/wsgi.py' cannot be loaded as Python module. I've never had it before having loaded many Python / Django projects by mkdir directory cd directory virtualenv env env/bin/pip install -r requirements.txt Then FTP in the files and then env/bin/python manage.py migrate env/bin/python manage.py collectstatic env/bin/python manage.py createsuperuser Today it isn't working. I've read a number of posts with similar issues but they seem to be due to different versions of python. Mine aren't. Any ideas. -
python today's date in a specific format
I want to use today's date in 2017-05-14 format in my django view. Consider following at the place of TODAY. @api_view(('GET',)) def get_specific_game_finish_count_today(request, gameId): specific_game_finish_count_today = Game_state.objects.filter(game_id=gameId, current_date=TODAY).count() data = {} data['count'] = specific_game_finish_count_today return JSONResponse(data) How can I achieve that? -
Django run view automatically every day
On my website I have a system of liking and uliking models. I want to make view, that checks every users number of likes received. If the number of likes exeeds 5, than the django should send email to the user, saying that he has more than 5 likes. How could I i make this work? Thank you in advance -
Django Channels giving failed to load resource error in google developer tool
I am using the django/channels-examples by andrew godwin on github i have it on webfaction I am using the /multichat/ example from his channels-examples. I am encountering an error the index.html page loads normally but without the websocket functions as in it just looks like regular html no chat functions. I will include the files below thanks. urls.py from django.conf.urls import url from django.contrib import admin from django.contrib.auth.views import login, logout from chat.views import index #urls.py urlpatterns = [ url(r'^$', index), url(r'^accounts/login/$', login), url(r'^accounts/logout/$', logout), url(r'^admin/', admin.site.urls), ] #base.html <!DOCTYPE html> {% load staticfiles %} <html> <head> <title>{% block title %}{% endblock %}</title> <meta charset="UTF-8"> <link rel="stylesheet" href="{% static "css/style.css" %}" type="text/css" media="screen" /> <script src="{% static "js/jquery-1.12.2.min.js" %}" type="text/javascript"></script> <script src="{% static "channels/js/websocketbridge.js" %}" type="text/javascript"></script> {% block extra_head %}{% endblock %} </head> <body> <header> <h1>{% block header_text %}{% endblock %}</h1> {% if user.is_authenticated %} <a href="/accounts/logout/">Logout</a> {% endif %} </header> <section> {% block content %} {% endblock %} </section> {% block extra_body %}{% endblock %} </body> </html> #index.html {% extends "base.html" %} {% block title %}MultiChat Example{% endblock %} {% block header_text %}MultiChat Example{% endblock %} {% block content %} <ul class="rooms"> {% for room in rooms %} <li … -
On refreshing a page with logged in user I get this error code:Forbidden (403). What's the solution?
Here is how I defined my user_login view function def login_user(request): if request.method == "POST": username = request.POST['username'] password = request.POST['password'] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) albums = Album.objects.filter(user=request.user) return render(request, 'violin/index.html', {'scale': scale}) else: return render(request, 'music/login.html', {'error_message': 'Disabled account: Contact admin'}) else: return render(request, 'violin/login.html', {'error_message': 'Invalid credentials'}) return render(request, 'violin/login.html') Here is my code error: Forbidden (403) -
Snippets not appearing on webpage
I am trying to build a snippet based the Wagtail tutorial here. I have built my snippet in models.py and create a custom template tag in the templatetags folder and connected the snippet to a Page via ForeignKey. I have also created the html template and run both makemigrations and migrate. The Snippet is a header image and a caption which appears on all pages except for the homepage. Code as follows: Snippet Model: @register_snippet class HeroImage(models.Model): text = models.CharField(max_length=255) image = models.ForeignKey( 'wagtailimages.Image', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) panels = [ FieldPanel('text'), ImageChooserPanel('image'), ] def __str__(self): return self.text Snippet Custom Template Tag: @register.inclusion_tag('hero_image.html', takes_context=True) def hero_images(context): self = context.get('self') if self is None or self.depth <= 2: hero = () else: hero = HeroImage.objects.all() return { 'hero': hero, 'request': context['request'], } Snippet connected to Page: class MenuPage(Page): hero = models.ForeignKey( 'home.HeroImage', null=True, blank=True, on_delete=models.SET_NULL, related_name='+' ) content_panels = Page.content_panels + [ SnippetChooserPanel('hero'), ] I have created two Snippets and selected one in my Page in the admin interface. In the template I have tried many different calls to the Snippet but they all return nothing. Calls I have tried include: {{ page.hero }} {{ page.hero.text }} {{ hero.text }} … -
How to link to user-uploaded profile pictures (ImageField) in Django templates?
I have instances of this model: class UserProfile(models.Model): user = models.OneToOneField(User, related_name='profile', primary_key=True) #Each User is related to only one User Profile prof_pic = models.ImageField(blank=True, upload_to='profile_pictures') All the profile pictures are uploaded via population script in django_project_folder/media/profile_pictures I have access to all the details inside the template via the context dictionary but I don't know what to put inside the image tag. <img src=" what to put here?? " id="second" class="img-circle img-responsive"> I tried linking the prof_pic via the context dictionary like this but it appeared broken: <img src=" {{ req1.req1.traveler.profile.prof_pic }} " id="second" class="img-circle img-responsive"> I looked at this document but didn't know how to link media files in the template. I have done the MEDIA_ROOT configuration and I already know how to link static files. -
I'm new to python and I want to create a script which will automatically input data into a HTML Text field. How to?
Suppose there is a simple form.html file containing the following code : <form> First name:<br> <input type="text" name="firstname" value=""> <br> <input type="submit" value="Submit"> </form> I want to create a python script which should automatically fill the value in the text field and submit the form. How do I do? -
How to develop multiplayer game website through python, Django, pygame?
I like to implement playing cards multiplayer website. I know python, Django and pygame . But I don't know implementation of multiplayer game website. Can you please explain step by step process for online multiplayer game development. Thanks Hari -
Django - Remote User Authentication Changes Session IDs
I have enabled authentication via Remote_User (docs here) and have subclassed RemoteUserBackend into a class I've called MyRemoteUserBackend to allow for setting of User attributes when a user first visits my site (for example, setting their User object firstname, lastname, email, etc.) The problem is that, with MyRemoteUserBackend enabled, sessions don't seem to persist for the users, and data is not passed between views, causing broken views. I have thoroughly tested each View's forms and can confirm the problem does not resided with invalid forms. When I disable/comment out MyRemoteUserBackend and instead enable/comment in RemoteUserBackend within SETTINGS, sessions DO persist for the users (session_key persists for each user). When MyRemoteUserBackend is enabled, session_key does not persists, as if the site thinks what is in fact one user is actually two separate users. What is wrong with MyRemoteUserBackend that is screwing up sessions and sessions_keys for users? Let me know if you need any other info. Thank you. SETTINGS: MIDDLEWARE_CLASSES = ( 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.auth.middleware.RemoteUserMiddleware', #<--- required ) AUTHENTICATION_BACKENDS = [ 'hrops.MyBackends.MyRemoteUserBackend', #<--- sessions don't persist 'django.contrib.auth.backends.ModelBackend', # 'django.contrib.auth.backends.RemoteUserBackend', ] MyRemoteUserBackend: from django.contrib.auth.backends import RemoteUserBackend class MyRemoteUserBackend(RemoteUserBackend): def clean_username(self, username): return username.split('\\')[1] # e.g. "<domain>\\<username>" becomes … -
Angular django is not rendering components
I'm totally new using angular and I have a very basic question. Well, reading about Angular 4 Quickstart but there are defined some .ts files, but are those .ts files necessaries or can I do a minimalist integration? Well, I'm doing something like this: In my html file I included: <script type="text/javascript" src="/static/js/angular.min.js" /> <script type="text/javascript" src="/static/js/app.js" /> The file angular.min.js is a reference of https://ajax.googleapis.com/ajax/libs/angularjs/1.5.6/angular.min.js app.js import { Component } from '@angular/core'; @Component({ selector: 'my-app', template: `<h1>Hello {{name}}</h1>` }) export class AppComponent { name = 'Angular'; } And, In my html file: <my-app>Loading AppComponent content here ...</my-app> But, it not firing. What I'm doing wrong? -
'ErrorDict' object has no attribute 'status_code' while validating form
I have models.py and forms.py as bellow . I want only alpha numeric inputs . after submitting the form, i am getting the error :'ErrorDict' object has no attribute 'status_code' Kindly suggest . from django.core.validators import RegexValidator alphanumeric = RegexValidator(r'^[0-9a-zA-Z]*$', 'Only alphanumeric characters are allowed.') class News_Post(models.Model): Country=models.CharField(max_length=20, validators=[alphanumeric]) State=models.CharField(max_length=20, validators=[alphanumeric]) District=models.CharField(max_length=20, validators=[alphanumeric]) Area=models.CharField(max_length=20, validators=[alphanumeric]) Photo_link=models.CharField(max_length=50,blank=True) News_Title=models.CharField(max_length=200, validators=[alphanumeric]) News=models.TextField(validators=[alphanumeric]) created_date=models.DateTimeField(auto_now_add=True,) author = models.CharField(max_length=20) def __str__(self): return self.News_Title forms.py: from django import forms from django.forms import ModelForm class NewsForm(forms.ModelForm): Country=forms.CharField(max_length=20, required=False, help_text='Optional.') State=forms.CharField(max_length=20, required=False, help_text='Optional.') District=forms.CharField(max_length=20, required=False, help_text='Optional.') Area=forms.CharField(max_length=20, required=False, help_text='Optional.') Photo_link=forms.CharField(max_length=50, required=False, help_text='Optional.') News_Title=forms.CharField(max_length=200, required=True, help_text='Required') News=forms.CharField(widget=forms.Textarea) class Meta: model = News_Post fields = ('Country','State','District','Area','Photo_link','News_Title', 'News', ) exclude = ["author"] -
Python - Access Javascript file object in Django
I am building an app that sends multiple files as email attachments, using jQuery and Django. I store the files in a buffer that the user can add and delete from, and sending them over a POST Ajax request as such: //Build the message message_buffer.forEach(function(entry){ body += '\n' + entry; }); var files = $.merge(attachment_buffer.photos, attachment_buffer.documents); var form = new FormData(); form.append("csrfmiddlewaretoken", csrf_token); form.append("client_id", client_id); form.append("subject", subject); form.append("body", body); form.append("files", files); $.ajax({ url: window.location.origin + '/dashboard/ajax/send_message', method: "post", data: form, processData: false, contentType: false, cache: false, beforeSend: function(){ //Block UI }, success: function(data){ if(data.status == 'success'){ console.log(data); //Show success and clear all the data stores. } else { console.log(data.message); } }, error: function(err){ console.log(err.responseText); } }); Problem is when i get this buffer (a list of JS file objects) in my django view, they are gotten as unicode and i dont know how to parse them. I need to be able to attach the files to the django EmailMessage instance like this: for attachment in attachments: mail.attach(attachment.name, attachment.read(), attachment.content_type) Please advice, thank you.