Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Are middlewares an implementation of the Decorator pattern?
In Django, there is the idea of Middleware. It consists of changing the requests and passing it down to the next middleware and so on, and doing the reverse with the responses. Are middlewares implementation of the design pattern Decorator? Are they a particular case of the decorator? What are the differences between them? Also, what is the difference between the implementation of Decorator in Django and the GoF description of it? -
Implementing 404 page in Django, but receiving error
I'm trying to implement 404 page in my django project, and coming across this error. Can anyone help with this? Thanks in advance!! -
Django cart application allowing multiple instances of same product
I have a function in my views file that at the moment lets you either add a product and if the product is added it lets you remove it. What I want to achieve is to add multiple instances of the same product and not do a remove. What is the best way of amending this view to allow this? I have tried removing the else portion but that generates errors. def cart_update(request): product_id = request.POST.get('product_id') if product_id is not None: try: product_obj = Product.objects.get(id=product_id) except Product.DoesNotExist: print("Show message to user, product is gone?") return redirect("cart:home") cart_obj, new_obj = Cart.objects.new_or_get(request) if product_obj in cart_obj.products.all(): cart_obj.products.remove(product_obj) added = False else: cart_obj.products.add(product_obj) # cart_obj.products.add(product_id) added = True request.session['cart_items'] = cart_obj.products.count() # return redirect(product_obj.get_absolute_url()) if request.is_ajax(): # Asynchronous JavaScript And XML / JSON print("Ajax request") json_data = { "added": added, "removed": not added, } return JsonResponse(json_data) return redirect("cart:home") Thanks in advance. -
ImportError: No module named builtins - Google App Engine Standard - Django - Python 2.7
I'm trying to deploy an application and this error keeps coming up. I am using the commands below in my views/models/form/settings.py, in order to use the same code I did for Python 3. from __future__ import absolute_import, division, print_function from builtins import (bytes, str, open, super, range, zip, round, input, int, pow, object) I've already installed the library:future==0.16.0 on my requirements-vendor.txt On localhost I can run it, using a Conda Env (python 2.7) but the deployment on GAE(standard) I got the 500 Server Error. -
Django Using Multiple Forms in Calculator Program
How do I differentiate the post requests from different buttons in django? For instance, if I want to create a calculator, how do I make it so the POST of the "multiply" button is different from that of the "add" and the "subtract" buttons? EDIT: Here is my views.py: from django.shortcuts import render,get_object_or_404 from django.shortcuts import render_to_response from django.template import RequestContext from django.views.generic import TemplateView from django import forms # Create your views here. # def startPage(request): # return render(request, 'multiplication/detail.html') template_name1 = 'multiplication/detail.html' template_name2 = 'multiplication/multiplied.html' class myForm(forms.Form): quantity1 = forms.IntegerField(required=False) quantity2 = forms.IntegerField(required=False) def multiply_two_integers(x,y): return x*y def my_view(request): if request.method == 'POST': form = myForm(request.POST) if (form.is_valid()): x = form.cleaned_data['quantity1'] y = form.cleaned_data['quantity2'] product = multiply_two_integers(x, y) multiplied = True return render(request, template_name1, {'form': form,'product': product, 'multiplied': multiplied }) else: multiplied = False form = myForm() return render(request,template_name1,{'form': form, 'multiplied': multiplied} ) template_name1: <h1>Multiplication Function</h1> <form action = "{% url 'multiplication:my_view' %}" method = "POST"> {{ form.as_p }} {% csrf_token %} <input type = "submit" value ="Multiply"> <input type = "submit" value ="Add"> <!--<button type="submit"> Multiply </button>--> {% if multiplied %} <h1 style="color:blue; margin-left:75px;"> Answer: {{product}}</h1> {% endif %} </form> -
linux "date" is correct but python tzlocal reports utc in docker container
I am mounting in the docker compose file volumes: - /etc/localtime:/etc/localtime:ro When I go into the container with docker exec -it <containername> bash then run date it shows up properly. But in django and in python3 editor tzlocal shows UTC. ogixbuild$ docker exec -it qlogixwebapi bash root@3e1a15562c2f:/var/lib/django/webapi# date Thu Feb 8 15:14:31 MST 2018 root@3e1a15562c2f:/var/lib/django/webapi# python3 Python 3.6.4 (default, Dec 21 2017, 01:35:12) [GCC 4.9.2] on linux Type "help", "copyright", "credits" or "license" for more information. import tzlocal tzlocal.get_localzone() <StaticTzInfo 'Etc/UTC'> Anyone have any experience with this know how to get tzlocal to get the correct timezone? -
Running asynchronous code synchronously in separate thread
I'm using Django Channels to support websockets and am using their concept of a group to broadcast messages to multiple consumers in the same group. In order to send messages outside of a consumer, you need to call asynchronuous methods in otherwise synchronous code. Unfortunately, this is presenting problems when testing. I began by using loop.run_until_complete: loop = asyncio.get_event_loop() loop.run_until_complete(asyncio.ensure_future(channel_layer.group_send(group_name, {'text': json.dumps(message), 'type': 'receive_group_json'}), loop=loop)) Then the stacktrace read that the thread did not have an event loop: RuntimeError: There is no current event loop in thread 'Thread-1'.. To solve this, I added: loop = asyncio.new_event_loop() asyncio.set_event_loop(loop) loop.run_until_complete(asyncio.ensure_future(channel_layer.group_send(group_name, {'text': json.dumps(message), 'type': 'receive_group_json'}), loop=loop)) And now the stacktrace is reading the RuntimeError: Event loop is closed, although if I add print statements loop.is_closed() prints False. For context, I'm using Django 2.0, Channels 2, and a redis backend. -
Jinja2 using {{ url() }}
I am trying to figure out how to pass my user_id within my html using {{ url('detail') }} I have tried the following with no success: {{ url('detail') }} {{ url('detail', user_id=User.id) }} {{ url('detail', User.id) }} Here's part of my views and html: views.py urlpatterns = [ path('dashboard/', dashboard), path('user/<int:user_id>/', detail, name='detail'), ] dashboard.html {% for User in all_users %} {{ url('detail') }} {% endfor %} Any help on this would be appreciated, thanks -
How to retrieve a single record using icontains in django
I'm trying to query a single record using the following but I get a 500 error. cdtools = CdTool.objects.get(product=product_record.id, platform=platform_record.id, url__icontains=toolname) models.py class CdTool(models.Model): product = models.ForeignKey(Product) platform = models.ForeignKey(Platform) url = models.CharField(max_length=300) a model instance has an full url, but in my query 'toolname' is the short form (ie: google instead of https://google.com), so I'm trying to figure out what the correct query would be here. I'm open to modifying models.py as long as there is no data migration stuff involved. -
How to create that logger for Django?
URL: / client /[client_id]/ log / operator Method: POST Data: { "access_token": "TOKEN", "limit": 100, "sort": "asc", "start_date": "2018-01-01T00: 00: 00Z" } OR { "access_token": "TOKEN", "limit": 100, "sort": "asc", "offset": "500" } Success Response: { "result": "ok", "logs": [ { "date": "2018-01-01T00: 00: 00Z", "text": "Log entry" }, ... ] } Log entry in the format: "message. User: name the name of the operator." I need to create a request to receive logs of operator activity. Which returns a formatted log of all user actions. I have an activity application in which there is an OperatorLog model. from django.db import models from users.models import User from .constants import ACTIVITY_ACTIONS class OperatorLogManager(models.Manager): """Manager for operator logs""" def active(self): """Mark object as active""" return self.filter(is_delete=False) def get_by_user_id(self, id): return self.active().filter(pk=id) def get_by_client_id(self, client_uid): return self.active().filter(client_uid=client_uid) class OperatorLog(models.Model): """Model for logs""" user = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) is_deleted = models.BooleanField(default=False) action_type = models.CharField(max_length=32, сhoices=ACTIVITY_ACTIONS) message = models.TextField(max_length=2048) client_uid = models.CharField(max_length=50) bitrix_id = models.PositiveIntegerField() # Operator Manager objects = OperatorLogManager() def delete(self, **kwargs): self.is_deleted = True self.save() You need a public api (activity / api.py) to register events in other applications, There is also a file with a list of activity types … -
Django How to turn each list in a dictionary into a cloumn?
I have a dictionary with 6 keys and each key's value is a list with 100 elements my_dict = {"Key1":["name1", "name2", ..., "name100"], "Key2":["id1", "id2", ..., "id100"], ... "Key6":["type1", "type2", ..., "type100"]} I am trying to make a table that is 100 x 6, where each column will be a list. I have tried everything in the template and come up short every time. Is there some simple concept I am missing? Should I be manipulating the data in the backend to make it more manageable? -
How typing the correct path to my json file inside a javascript file
python 3.6.4 , django 2.0 I have a index.html which load this javascript file script.js and inside this i have problems to type the correct path to one json file data.json. The index.html now is displayed without the information from data.json , I am using a XmlHttpRequest object. function makeRequest(url){ ... http_request = new XMLHttpRequest(); http_request.open('GET', url, true); } ... window.onload = function(){ makeRequest("here/have/problems"); } Tree of my files inside index.html use {% static 'bar/scripts/script.js'%} and that work well, then inside script.js was trying typing "bar/data/data.json" but doesn't work. Guide me please in the correct way about this issue. -
social auth django: disconnect vs disconnect_individual
So I have added the disconnection pipeline to my application using python-social-auth. I noticed that there are two endpoints in the urls.py: disconnect - /oauth/disconnect/<backend>/ disconnect_individual - oauth/disconnect/<backend>/<association_id>/ Where backend could refer to the social provider (facebook, google-plus, linkedin, ...). Through my experiments, I find that the first endpoint, disconnect, will remove the logged in user's associated UserSocialAuth table entry. What does the second endpoint do? What does the association_id represent? Is it a way of dissociating one individual account if the user has two UserSocialAuth entries with the same backend? That doesn't make sense since the uid + provider must be unique. Can someone provide an example of when one would call the disconnect_individual? -
django model for subsite wagtail multisite
I am creating a wagtail instance which includes actually 4 sites: a portal-site and three nearly identical subsites. The subsites contain in the footer a django-form, and within this django-form I want to include a number of date-objects that are specific for the subsite. To clarify the setup: there will be a subsite for kids-training, youth-training and adults-training. The form needs to include the next three training-dates (DateTime) for the target-group, and these dates need to be created by the site-owner. I have not yet found a way to create a non-page model (django-model) that can be added to a subsite. Snippets seem not the way to go, and Site Settings does not seem to cover this usecase. Any solution-suggestion would be welcome. -
Just django dynamic formset and ajax
I use django dynamic formset and ajax to chekc the inventory. When I add a form, how to have ajax pick up change on the new form? dynamic formset adding forms $('#form-inline tbody tr').formset({ addText: 'add link', deleteText: 'remove', prefix: 'ptpositions' }); I loop the form in ajax but I don't think this is a good way. $(document).ready(function(){ {% for forms in formset %} $(".{{forms.stock.value}}").change( function(){ var symbol = $(".{{forms.stock.value}} option:selected").text(); {% endfor %} {% for forms in formset %} $.ajax({ url: "{% url 'inventory:get_position' ptinventory_obj.id date %}", type: "GET", data: { 'product': product }, datatype: 'json', success: function(data) { $(".{{forms.id.value}}_ouput").html(data.price); }}); {% endfor %} }); }) Now if I add form, then the ajax doesn't work. -
Visualization of xlsx files in a django project
I am willing to work on a project, in which I have a database (xlsx files), and I want to migrate it to a nosql database in order to visulize the data in plots, and then integrate it in a django website using plotly to make the graphs. My question is, is it better to migrate to a nosql database knowing that files will be added daily, or just use a sql one like postgresql? And which is better to do the job, mongoDB or Elasticsearch ? -
Trying to pass arguments from java script to python, and have python return back the result on my java script page
I am trying to test a simple function using java script and python. I am trying to pass some arguments from java script / HTML to python (which is running as a server) and get the results back to my HTML page. I noticed that the following isn't getting executed "utf-8">{% csrf_token %}", but i cant seem to know the reason. This snippet can be seen below int he HTML script. I really appreciate your help, and Thank you. I have attached both scripts: PYTHON: from django.http import HttpResponse from django.shortcuts import render_to_response from django.template import RequestContext def index(request): return render_to_response('index.html') def result(request): p = request.POST['answer'] return render_to_response('index.html', {'answer': p}, context_instance=RequestContext(request)) HTML: <head> <title>Index page</title> </head> <body> <div id="header">Welcome to index page</div> <div id="content"> <p>Enter your name</p> <form action="/MYURL" method="post" accept-charset="utf-8">{% csrf_token %} <input type="text" name="answer"> <input type="submit" value="Send!"> </form> <div id="header"> result</div> <div id="content"> <p>Your name is: {{ answer }}</p> </div> </div> </body> -
WSGI script cannot be loaded as Python Module
I have been trying to troubleshoot a internal server error ive been getting from my local install of django 2.0.2 whlist trying to run it in a python 3.6.3 virtualenv on apache 2.4.27 via mod-wsgi-py3 4.5.17 running in Daemon mode. In my apache2 error.log file I can see [Thu Feb 08 10:34:24.694864 2018] [wsgi:error] [pid 94364] [remote 127.0.0.1:47002] mod_wsgi (pid=94364): Target WSGI script '/var/www/wsgi-scripts/wurstblog.wsgi' cannot be loaded as Python module. Searching the internet far and wide I have found various potential solutions that include WSGI Script Cannot Be Loaded as Python Module -- 500 Internal Server Error 'How python is installed' 'Missmatch of mod-wsgi and python environment version' 'conflict with mod_python and mod_wsgi' I am not sure how to correct any problem with my python3 instalation, nor that of mod_python I read somewhere that the wsgi script needed to be executable so ls -l /var/www/wsgi-scripts gives -rwxr-xr-x 1 root root 454 Feb 8 10:52 wurstblog.wsgi it looks like this: import os import sys from django.core.wsgi import get_wsgi_application sys.path.append('/home/mike/blog-env/wurstblog/wurstblog') os.environ["DJANGO_SETTINGS_MODULE"] = "wurstblog.settings" application = get_wsgi_application() blog-env is my pthon3 virtualenv and wurstblog is where my django project is I have configured a virtualhost /etc/apache2/sites-enabled/wurst.conf <VirtualHost *:80> ServerAdmin myname@nospam.com <Directory /var/www/wsgi-scripts> <Files … -
Issues redirecting in Django
I'm deploying a django app, and I have two forms: One for rating and another for contact in the home page. Both of them redirect to the home page after save a model. The contact form works fine, but the rating form keeps the post url and doesn't save the model, and after doing it again, it save it. For example, I'm in www.site.com, then I send a post request from the rating form, the form redirect me to www.site.com/rating/ without saving the data. Then, if I'm send from www.site.com/rating/ the same form, the data is saved and redirect to www.site.com/rating/rating/ (404). The contact form works fine with the same process, and I think both are similar. The contact form redirects me to www.site.com like I want. I don't know why is this happening. urls.py urlpatterns = i18n_patterns( url(r'^admin/', admin.site.urls), url(r'^i18n/', include('django.conf.urls.i18n')), url(r'^', include('myapp.urls')), prefix_default_language=False ) myapp/urls.py urlpatterns = [ url(r'^contact/', views.contact, name='contact'), url(r'^rating/', views.raiting, name='rating'), url(r'^', views.index, name='home'), ] myapp/views.py def contact(request): if request.method != 'POST': raise Http404('acceding from GET') msg = ContactForm(request.POST) if not msg.is_valid(): context = { 'contact_errors': msg.errors } return render(request, 'home.html', context) msg.save() return redirect('home') def rating(request): if request.method != 'POST': raise Http404('acceding from GET') … -
Breadcrumps doesn't work correctly in django
I'am creating from the one template a categories and subcategories model in django. Now I have a few categories and subcategories added by Admin Panel. But now when I want to display in html the list of breadcrumps they doesn't displaying correctly and I getting a error. views.py from django.shortcuts import render, get_object_or_404 from .models import Kategoria, Firma def strona_glowna(request): return render(request, 'ogloszenia/index.html', {}) def show_category(request,hierarchy= None): category_slug = hierarchy.split('/') category_queryset = list(Kategoria.objects.all()) all_slugs = [ x.slug for x in category_queryset ] parent = None for slug in category_slug: if slug in all_slugs: parent = get_object_or_404(Kategoria,slug=slug,parent=parent) else: instance = get_object_or_404(Firma, slug=slug) breadcrumbs_link = instance.get_cat_list() category_name = [' '.join(i.split('/')[-1].split('-')) for i in breadcrumbs_link] breadcrumbs = zip(breadcrumbs_link, category_name) return render(request, "ogloszenia/detale.html", {'instance':instance,'breadcrumbs':breadcrumbs}) return render(request,"ogloszenia/kategorie.html",{'firma_set':parent.firma_set.all(),'sub_categories':parent.children.all()}) urls.py from django.urls import path from . import views urlpatterns = [ path('', views.strona_glowna, name='strona_glowna'), path('<hierarchy>/', views.show_category, name='category'), ] kategorie.html {% if sub_categories %} <h3>Podkategorie</h3> {% for i in sub_categories %} <a href="{{ i.slug }}"> {{ i.name }} </a> {% endfor %} {% else %} Brak podkategorii {% endif %} <div class="row small-up-1 medium-up-3" > {% if firma_set %} {% for i in firma_set %} <a href="{{ i.slug }}"> <img src="{{ i.title }}"> </a> <a href="{{ i.slug }}"> … -
When an object can belong to several other objects, where does the foreign key belong?
Using Django 1.11.6 and Postgres 9.2 If I have the following models: class RoughDraft(models.Model) class Manuscript(models.Model): rough_draft = models.ForeignKey(RoughDraft) class AudioBook(models.Model): manuscript = models.ForeignKey(Manuscript) class Series(models.Model): class Book(models.Model): manuscript = models.ForeignKey(Manuscript) series = models.ForeignKey(Series) I want to add a Notes model to my project to allow multiple users add comments to RoughDrafts, Manuscripts, Books and AudioBooks. Further, when a RoughDraft becomes a Manuscript or Manuscript becomes a Book or AudioBook, I want the Notes to be carried forward. Is it better to create a notes model like this: class Notes(models.Model): text = models.TextField() and add a notes = models.ManyToMany(Notes) field to each of RoughDraft, Manuscript, Book, Series and AudioBook or class Notes(models.Model): text = models.TextField() rough_draft = models.ForeignKey(RoughDraft, null=True, blank=True) manuscript = models.ForeignKey(Manuscript, null=True, blank=True) series = models.ForeignKey(Series, null=True, blank=True) book = models.ForeignKey(Book, null=True, blank=True) audio_book = models.ForeignKey(AudioBook, null=True, blank=True) Or should I create a ManuscriptNotes model, a RoughDraftNotes model, etc... -
Django CreateView autofill custom user
I want to use Django's GCBV CreateView to autofill the created_by field on my model with the current user. The official docs have a good example here but I'm using a custom user model and having trouble making it work. Here's my current setup: # models.py from django.conf import settings from django.contrib.auth.models import User from django.db import models class Author(models.Model): name = models.CharField(max_length=200) created_by = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, ) # views.py from django.contrib.auth import get_user_model from django.views.generic.edit import CreateView from myapp.models import Author class AuthorCreate(CreateView): model = Author fields = ['name'] def form_valid(self, form): form.instance.created_by = self.request.get_user_model() return super().form_valid(form) However upon form submission I get the error: AttributeError at /posts/new/ 'WSGIRequest' object has no attribute 'get_user_model' I'm setting my custom user incorrectly but not sure exactly where the error is. -
Make jenkins indicate failure on failed tests
I have a django test suite which is running on jenkins with the following build: virtualenv -p /usr/bin/python3.5 etl_api_virtualenv cd etl_api_virtualenv source bin/activate python --version cd $WORKSPACE/leg_apps ls pip install -r requirements-dev.pip ./api/test/run_api_tests.sh $WEB_ENV This is working, but when some of the unit tests fail, the job/build still is marked as a success. I can't figure out how to make the job indicator turn red and mark as a failure if the tests don't all pass. I'm not even sure what to Google to try to figure this out, so please forgive the apparent "lack of effort"... it's not the case. I'm just dead-ended at the start. -
Retrieving information form several textbox (Template) in Django
**I want to fetch information from course titile & course code textbox ,,,, if title & code both are given or only title /code data will be showed. Bt, in my code not working when only title are given.. what are the logical mistake..?? My View Code def search_view(request): c = 0 d = 0 c_title = '' c_code = '' course_Details = '' course_Details1 = '' if request.GET.get('Code'): c_code = request.GET.get("Code") if request.GET.get('Course_Title'): c_title = request.GET.get("Course_Title") if c_code != '': course_Details = Course.objects.filter(course_code=c_code) if (course_Details): c = 1 if c_title != '': if c == 1: course_Details1 = course_Details.filter(course_title=c_title) if (course_Details1): d = 1 if d == 1: course_Details = course_Details1 if d == 0: course_Details = Course.objects.filter(course_title=c_title) if c == 1 | d == 1: return render(request, 'index.html', {'course_Details': course_Details}) else: return render(request, 'index.html') -
How to best include field from Django ManyToManyField custom intermediary model when using prefetch_related?
Models: class User(models.Model): teams = models.ManyToManyField('Team', through='TeamMember', related_name='members') class Team(models.Model): pass class TeamMember(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) team = models.ForeignKey(Team, on_delete=models.CASCADE) position = models.CharField(max_length=255) I am trying to build a queryset that will fetch users and (running another query with prefetch_related) teams for those users with TeamMember.position included as one of the fields on the team without running any unnecessary queries or joins. Here is the queryset I have so far: User.objects.prefetch_related(Prefetch('teams', queryset=Team.objects.annotate(position=F('teammember__position')))) But it is doing an unnecessary join: SELECT `appname_user`.`id` FROM `appname_user` LIMIT 21; args=() SELECT (`appname_teammember`.`user_id`) AS `_prefetch_related_val_user_id`, `appname_team`.`id`, `appname_teammember`.`position` AS `position` FROM `appname_team` LEFT OUTER JOIN `appname_teammember` ON (`appname_team`.`id` = `appname_teammember`.`team_id`) INNER JOIN `appname_teammember` T3 ON (`appname_team`.`id` = T3.`team_id`) WHERE T3.`user_id` IN (1); args=(1,) It is joining appname_teammember twice when it doesn't need to. Anyone know how to eliminate that extra join?