Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
AJAX Success Response Button Not Opening Modal
I'm creating an activity feed of communications, notes, and tasks. Each one has buttons for editing and deleting, which opens up a modal for either changing information or confirming the delete. The modals work fine. Once I load the data after a successful AJAX response, the buttons click (and the call is successfully made to the view) but the modal does not open. I've tried making the buttons "live" and appending the button, but the modal still won't open. This is the origin AJAX -- $(document).ready(function(){ $('.task_completed').click(function() { var id = $(this).attr('id'); var type_id = $('#contactID').attr('value'); $.ajax({ method: "POST", url: "{% url 'communications:task_completed_activity' %}", data: {'id': id, 'type': 'Contact', 'type_id': type_id}, beforeSend: function (xhr) { xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}'); }, success: function(response) { $('.infinite-container').html(response); } }); }); }); This is an example of the modal that's failing to open -- $(document).ready(function(){ $(".task-delete").click(function(){ $("#taskDelete").modal(); }); }); This is the AJAX for the button -- $(document).ready(function(){ $('.task-delete').click(function() { var id = $(this).attr('id'); $.ajax({ method: "POST", url: "{% url 'communications:delete_confirm' %}", data: {'id': id, 'type': 'task'}, beforeSend: function (xhr) { xhr.setRequestHeader("X-CSRFToken", '{{ csrf_token }}'); }, success: function(response) { document.getElementById("task-object").innerHTML = response.object; document.getElementById("task-description").innerHTML = response.description; $('#task-id').val(response.id); } }); }); }); Let me know if … -
django models retrieving data
i m new to django.this is my model class . how can i retrieve data from depertment and doctor in my template plz write urls and view. from django.db import models class Hospital(models.Model): name=models.CharField(max_length=300) location=models.CharField(max_length=1000) def __str__(self): return self.name class Department(models.Model): hospital=models.ForeignKey(Hospital,on_delete=models.CASCADE) name=models.CharField(max_length=300) def __str__(self): return self.name class Doctor(models.Model): department=models.ForeignKey(Department,on_delete=models.CASCADE) name=models.CharField(max_length=300) designation=models.CharField(max_length=300) qualification=models.CharField(max_length=500) image=models.ImageField(default='default.png',blank=True) address=models.CharField(max_length=550) def __str__(self): return self.name -
How to filter a filed when it is Null or null character string?
How to filter a filed when it is Null or null character string? I can only to check when it is null: DataDictionary.objects.filter(parentlevel__isnull=True) How about Null or null character string? -
Validating a signed cookie set by Django in the browser
Django sets a signed cookie in the client's browser, and I have the following settings for managing cookie sessions: SESSION_ENGINE = 'django.contrib.sessions.backends.signed_cookies' SESSION_COOKIE_AGE = 86400 SESSION_SAVE_EVERY_REQUEST = False When I set the cookie value in the request headers and use this code to validate the cookie, I get this error message: raise BadSignature('Signature "%s" does not match' % sig) BadSignature: Signature "REDACTED"" does not match This is how I validate the signed cookie from the request payload (taken from the docs here https://docs.djangoproject.com/en/1.11/topics/signing/#using-the-low-level-api): cookie = '"blahhh:1redacted:redactedk"' from django.core.signing import Signer signer = Signer() signer.unsign(cookie) I even stripped out the " at the beginning and end of the cookie value, and that didn't work either. I also included the cookie key like this: session_id="blahhh:1redacted:redactedk". Is my understanding of how signed cookies work wrong? Am I using the API wrong? What is going on here? -
python merge two query sets and addition of matching records
I have a need to merge two querysets together with simalar data. Set 1 (stats) has a list of teams, total points for that team and the division the team is in. Set 2 (spares) has a list of teams that have had a member spare for them which includes the teams and points (no division for this set). What I would like to do is merge the querysets into one and when the teams match, just add the spares points to the team total, keeping the team name and division. The code i am using below will sort of do what i am looking for except it does not include the teams that never had a spare on it. Consider the following data. Stats List Team 1 : 8 Points : Division A Team 2 : 3 Points : Division B Team 3 : 7 Points : Division A Team 4 : 5 Points : Division B Team 5 : 4 Points : Division A Spares List Team 1 : 3 points Team 3 : 6 Points So what I want to do is merge these two lists where the teams match but total their points. In this case … -
Django field validator not working at all
So im trying at add a simple validator that checks against a postcode and returns a validation error if the user inputs non alphanumberics. But after trying i cant seem to get even the most basic validation message to show up. Here is my form i used the example field validation just to try get it to show up but it doesn't class CartAddShippingDetailsForm(forms.Form): first_name = forms.CharField(max_length=100) last_Name = forms.CharField(max_length=100) email = forms.EmailField() address1 = forms.CharField(max_length=100) town = forms.CharField(max_length=100) postcode = forms.CharField() country = LazyTypedChoiceField(choices=countries) additional_note = forms.CharField(max_length=100, required=False) def clean_postcode(self): data = self.cleaned_data['postcode'] if "fred@example.com" not in data: raise forms.ValidationError("You have forgotten about Fred!") else: return postcode This my views.py def shipping_details(request): cart = Cart(request) shipping_form = CartAddShippingDetailsForm() if request.method == 'POST': shipping_form = CartAddShippingDetailsForm(request.POST) if shipping_form.is_valid(): return redirect(reverse('test_order')) else: return render(request, 'shippingdetails.html', {'cart': cart, 'shipping_form': shipping_form}) and the html {% extends "base.html" %} {% load static %} {% block title %}Shipping{% endblock %} {% block content %} <form action="{% url 'test_order' %}" method="post"> <div class="colcontainer"> {% csrf_token %} {{ shipping_form }} <input type="submit" name="Submit"> </div> </form> {% endblock %} i have also tried using the validator because i just want to check that the field contains only alphanumeric … -
Django Foreign Key not registering in serializer
I am trying to overwrite the create method in my view. In my Child Serializer Class, I have the parent model as a foreign key. From the view, I am only provided the parent_id. I have to get the parent model instance first. After I get the parent model instance, I want to pass that into the serializer. However in my API view, I'm getting "parent": null. Why is that? Here is what my code looks like: class ChildList(generics.ListCreateAPIView): queryset = Child.objects.all() serializer_class = ChildSerializer def create(self, request, *args, **kwargs): parent_id = request.data.get('parent_id') parent = Parent.objects.get(id=hh_id) serializer = self.get_serializer(data={'parent':parent}) if serializer.is_valid(): self.perform_create(serializer) headers = self.get_success_headers(serializer.data) return Response(serializer.data, status=status.HTTP_201_CREATED, headers=headers) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) class ChildSerializer(serializers.ModelSerializer): class Meta: model = HandHistoryObject fields = ('parent',) -
Django admin userlinks is not showing up
I extended base_site.html template and it's working correctly. {% extends "admin/base.html" %} {% load i18n %} {% block title %} {% trans 'Test Admin' %} {% endblock %} {% block userlinks %} {{ block.super }} {% endblock %} {% block nav-global %}{% endblock %} And now I've created a template for my submit form which looks like this. {% extends "admin/base_site.html" %} {% load i18n static %} {% block userlinks %} {{ block.super }} {% endblock %} But no userlinks is showing up. -
What is the correct way to organize Django apps when serving data to multiple graphs?
I am currently working on a site that displays warehousing information, but am having trouble wrapping my head around Django's app concept when it applies to serving data for multiple pages of graphs. I currently have 3 apps: Authentication - handles registration pages and user profiles Notifications - manages alerts to the users when there are changes in the data Warehousing - all of the other data is served from here onto the templates The "warehousing" app has grown way too large, since it provides data for the rest of the site (4 different templates), each of which has several graphs and also includes a map of warehouse locations and a log of warehousing equipment. I understand that each Django app is supposed to have a single focus, but what is the proper way to structure them when dealing with an application like this where a majority of the site is pages of interactive graphs? -
Can I add an "url file with namespace" inside of an url file from an AppHook?
Having a CMS with many apps (nested apps): /Dashboard (app hook) ----url.py ----cms_apps.py ----/Product --------/SomeCustomManagement -----------url.py -------url.py /MainSiteCMS In my main site I have a page that use "Dashboard" as AppHook, it works fine. "Dashboard.cms_apps": from cms.app_base import CMSApp from cms.apphook_pool import apphook_pool class DashboardApp(CMSApp): name = "My Store" urls = ["dashboard.urls"] app_name = "store" apphook_pool.register(StoreApp) And inside "dashboard.urls": from django.conf.urls import url, include from .product import views as product_view urlpatterns = [ url(r'^$', product_view.home, name="producthome"), ] And everything works fine. But if I want to add in "dashboar.urls" url from another apps (a lot of apps): from django.conf.urls import url, include from .product.urls import urlpatterns as product_urls urlpatterns = [ url(r'^', include(product_urls, namespace="product")) ] and "product.urls": from .SomeCustomManagement.urls import urlpattern as scm_urls urlpatterns = [ url(r'^$', views.home, name="store-home"), url(r'^Management/', include(scm_urls, namespace="products")) ] ... I generate a link with: "store:products:managementlink", I tested the whole scenario outside of the CMS and works fine, but when I tried to combine all with the CMS, it gives me the following error: Django Version: 1.11 Exception Type: NoReverseMatch Exception Value: 'products' is not a registered namespace inside 'store' Note: The code above is not my real code, I can't paste my real code and … -
Possible to have a simple auth that does not use the Django user model?
I want to override the BaseAuthentication class and just add a very simple check for username and password. Their will only be one user/pass in plain text that can be kept in a .txt file. This is just a POC and I am not at all worried about security vulnerabilities that come along with this. I guess the first question I have is can I create auth that does NOT use the User object in Django, I essentially just want to raise an error if user/pass does NOT match, otherwise continue (if that makes sense). from django.contrib.auth.models import User from rest_framework import authentication from rest_framework import exceptions class ExampleAuthentication(authentication.BaseAuthentication): def authenticate(self, request): username = request.META.get('X_USERNAME') if not username: return None try: user = User.objects.get(username=username) except User.DoesNotExist: raise exceptions.AuthenticationFailed('No such user') return (user, None) How I want to use it (example): # auth required only for POST requests permission_classes = (IsAuthenticatedOrReadOnly,) def get(self, request, format=None): variable_names = JobExecutionEnvSet.objects.all()[:8000] serializer = JobExecutionEnvSetSerializer(variable_names, many=True) return Response(serializer.data) def post(self, request, format=None): serializer = JobExecutionEnvSetSerializer(request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Returning values of a 'ReturnList' without the key in DjangoRestFramework
So I have this Serializers class MovieSerializer(serializers.ModelSerializer): class Meta: model = Movie fields = ('name', 'thumbnail', 'source_url', 'duration') class SingleCategorySerializer(serializers.ModelSerializer): movies = MovieSerializer(many=True, read_only=True) class Meta: model = MoviesCategories fields = ('movies',) The Movie model has a relationship with the movies categories as follows category = models.ForeignKey(MoviesCategories, related_name="movies", on_delete=models.DO_NOTHING) Now when I try this serializer = SingleCategorySerializer(movie_category, many=True), the result of serializer.data is [ { "movies": [ { "name": "Guardians of the Galaxy", "thumbnail": "https://nerdist.com/wp-content/uploads/2016/08/Guardians-of-the-Galaxy-poster-2.jpg", "source_url": "http://dl.tehmovies.org/94/10/Star.Wars/Star.Wars.Episode.II.Attack.of.the.Clones.2002.1080p.5.1CH.Tehmovies.ir.mkv", "duration": "05:30:09" }, { "name": "Star Wars II", "thumbnail": "https://images-na.ssl-images-amazon.com/images/I/51TEG6X589L.jpg", "source_url": "http://dl.tehmovies.org/94/10/Star.Wars/Star.Wars.Episode.II.Attack.of.the.Clones.2002.1080p.5.1CH.Tehmovies.ir.mkv", "duration": "05:32:26" } ] } ] I only want the values of the movies to be returned. Like this [ { "name": "Guardians of the Galaxy", "thumbnail": "https://nerdist.com/wp-content/uploads/2016/08/Guardians-of-the-Galaxy-poster-2.jpg", "source_url": "http://dl.tehmovies.org/94/10/Star.Wars/Star.Wars.Episode.II.Attack.of.the.Clones.2002.1080p.5.1CH.Tehmovies.ir.mkv", "duration": "05:30:09" }, { "name": "Star Wars II", "thumbnail": "https://images-na.ssl-images-amazon.com/images/I/51TEG6X589L.jpg", "source_url": "http://dl.tehmovies.org/94/10/Star.Wars/Star.Wars.Episode.II.Attack.of.the.Clones.2002.1080p.5.1CH.Tehmovies.ir.mkv", "duration": "05:32:26" } ] Any help will be appreciated. -
How to speed up page loading time for images fetched from third party servers and external urls?
At the moment, we have built a simple Django application that simply fetches images from ImgUr APIs using the following endpoint: https://api.imgur.com/endpoints/gallery#gallery-search Then, it forwards the result to front-end for rendering which is simply HTML templates with jQuery. However, images loading on the client side in the browser is very slow. How to speed it up? -
What is the proper way to keep one-off data?
I've got online shop on Django, where I want to keep some information like address or mobile phone of manager, but this information should be simply-edited by admin of the site. So, I couldn't leave it just as text in template or variable in code, because now I need to create some forms for editing this information. I don't sure what to do: create model Info in my database with all fields which I want to keep or create couple of models for each. Or maybe there is a better solution? -
Why is this Popen call returning a "io.UnsupportedOperation: fileno" error in Django 2.0?
I recently upgraded my project to Django 2.0, and an error started cropping up. First off, I use django_gulp to start a gulp process whenever I start the django runserver. I'm using the runserver_plus branch of the django_gulp project. Here's the relevant code snippet from the django_gulp project, where it makes the subprocess.Popen call. This call was functioning correctly in Django 1.11.x. from __future__ import print_function import atexit import os import psutil import subprocess import sys import traceback from signal import SIGTERM from concurrent.futures import ThreadPoolExecutor from django.core.management.base import CommandError from django.conf import settings from django_extensions.management.commands.runserver_plus import Command \ as DjangoExtensionsRunserverCommand from env_tools import load_env class Command(DjangoExtensionsRunserverCommand): """ Subclass the RunserverCommand from Staticfiles to set up our gulp environment. """ def __init__(self, *args, **kwargs): self.cleanup_closing = False self.gulp_process = None super(Command, self).__init__(*args, **kwargs) @staticmethod def gulp_exited_cb(future): if future.exception(): print(traceback.format_exc()) children = psutil.Process().children(recursive=True) for child in children: print('>>> Killing pid {}'.format(child.pid)) child.send_signal(SIGTERM) print('>>> Exiting') # It would be nice to be able to raise a CommandError or use # sys.kill here but neither of those stop the runserver instance # since we're in a thread. This method is used in django as well. os._exit(1) def handle(self, *args, **options): try: env = … -
Django expire cache every N'th HTTP request
I have a Django view which needs can be cached, however it needs to be recycled every 100th time when the view is called by the HTTP request. I cannot use the interval based caching here since the number will keep changing upon traffic. How would I implement this? Are there other nice methods around except maintaining a counter (in db) ? -
How do I make a Django model instance to relate to another model instance
I want to have the amount under Rent to increment on the amount under Accounts. When a user types in the amount in Rent it should deduct or add in the amount in Account and should reset if paid or stay the same when not paid. class Account(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=250) number = models.PositiveIntegerField(help_text="Account number", unique=True, blank=True, null=False) currency = models.CharField(max_length=3, choices=ALLOWED_CURRENCIES) creation_date = models.DateTimeField(auto_now_add=True) amount = models.DecimalField(max_digits=MONEY_MAX_DIGITS, decimal_places=MONEY_DECIMAL_PLACES, help_text="Latest" "balance", default=0, blank=False, null=True) class Rent(models.Model): source = models.ForeignKey(Account, on_delete=models.CASCADE, verbose_name="Account holder.") amount = models.DecimalField(max_digits=MONEY_MAX_DIGITS, decimal_places=MONEY_DECIMAL_PLACES) date = models.DateTimeField(auto_now_add=True) -
How to upload private files to s3 using boto3 and serializer
I am using S3Boto3Storage to manage private file uploads to s3: // storage_backend.py class PrivateFileStorage(S3Boto3Storage): location = settings.AWS_PRIVATE_FILE_LOCATION default_acl = 'private' file_overwrite = False custom_domain = False I have a model that is using FileStorage: // models.py class PrivateFileModel(models.Model): file = models.FileField(storage=PrivateFileStorage()) I have my default storage set to PrivateFileStorage under my settings: // settings.py DEFAULT_FILE_STORAGE = 'myapp.storage_backend.PrivateFileStorage' And then I have my serializers: // serializers.py class PrivateFileSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = PrivateFileModel fields = ('url', 'file') I am able to save the private file directly to the model. However, when I try to save using PrivateFileSerializer, I am getting this error: botocore.exceptions.ClientError: An error occurred (404) when calling the HeadObject operation: Not Found How do I fix this? -
Extender usuario de Django
El problema lo tengo no en extender el modelo de Django es que necesito crear más de un tipo de usuario en concreto dos Estudiante y Profesor cada uno con atributos en común pero con otros propios de cada uno, alguien me pudiera dar alguna idea o ejemplo. -
Convert dynamic JSON array to HTML
I have a Django view that will return JSON data depending on what is given to it. Each JSON element will have the same fields but the returned JSON array will have a dynamic amount of elements. Here is an example of the possible JSON data that could be returned: [ { "Open Job Lines": 0, "Open Hours": 0, "Repair Order": "123454", "Expected Pay": 1.9, "Actual Pay": 1.0, "Pay Status": "Underpaid" } ] Here is an example or a JSON return with multiple elements: [ { "Open Job Lines": 0, "Open Hours": 0, "Repair Order": "123454", "Expected Pay": 1.9, "Actual Pay": 1.0, "Pay Status": "Underpaid" }, { "Open Job Lines": 0, "Open Hours": 0, "Repair Order": "123454", "Expected Pay": 1.9, "Actual Pay": 1.0, "Pay Status": "Underpaid" } ] Using JavaScript, I would like to turn this into HTML similar to following and assign it to a variable. Open Job Lines: 0 <br> Open Hours: 0 <br> Repair Order: 123454 <br> Expected Pay: 1.9 <br> Actual Pay: 1.0 <br> Pay Status: Underpaid <br> Open Job Lines: 0, <br> Open Hours: 0 <br> Repair Order: 123454 <br> Expected Pay: 1.9 <br> Actual Pay: 1.0 <br> Pay Status": Underpaid <br> -
Reverse for 'account_email_verification_sent' not found. 'account_email_verification_sent' is not a valid view function or pattern name
I'm trying to use allauth and rest-auth in my project and try to use the built in function in allauth to do this but this what i get : and here is my codeenter image description here settings.py ACCOUNT_EMAIL_VERIFICATION = 'mandatory' ACCOUNT_EMAIL_REQUIRED = True urls.py urlpatterns = [ re_path(r'^', include('rest_auth.urls')), re_path(r'^registration/', include('rest_auth.registration.urls')), ] -
Differentiating between Methods and Functions [duplicate]
This question already has an answer here: Difference between methods and functions [duplicate] 4 answers Difference between a method and a function 33 answers Relevant background: I have gone through LPTHW (while reading the official documentation as a point of reference), and am now learning about Django. When learning about functions, I never really stopped to think about the different ways that I called them. What different ways am I referring to? Well, for example: add(a, b) compared to: string.split() I started googling to try and find out why some are called with arguments, while others are simply called like '.function()'. I realised that .split(), in this case, may very well be a method rather than a classic function, and that that might be the reason for it being used this way. Are all functions that get called like ''.function()'' really methods, defined in classes? If so, does that mean that .split() is part of the string class? Are string-classes instantiated by just defining a string? Thank you! -
Django: separate shops
I would like to create a Django project which will do the following: There is a platform example.com which already have a "shop" functionality (app). This platform should provide an ability to users to create their own store inside platform. Users can set up a a shop on and will receive a url like user1.example.com user2.example.com In this cases each url is a separate store. The problem is: I don't know how to make each store to have its own shopping cart, order history, etc. I just need an advice: what is best to use to solve this problem (maybe, sessions or some other Django features?) -
Only protocol 3 supported error
I'm trying to configure Django with PostgreSQL on Windows Server 2012. but after a while i get this error only protocol 3 supported I'm using Postgres 9.6 and psycopg2 2.7.3 and Django 1.11 and mod_wsgi. In settings.py I have DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'mydb', 'USER': 'postgres', 'PASSWORD': 'mypassword', 'HOST': 'localhost', 'PORT': '5432', } } i read this question and also this question but did not found any solutions. Do you know any solutions for the problem? -
How to edit path for django unit tests?
I'm trying to run the standard 'python manage.py test` however I'm getting a: `ImportError: No module named 'draft1.app'` for all 9 of my apps in my project (9 errors). Full error example: ImportError: Failed to import test module: draft1.profiles Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 462, in _find_test_path package = self._get_module_from_name(name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/unittest/loader.py", line 369, in _get_module_from_name __import__(name) ImportError: No module named 'draft1.profiles' My project tree is: /draft1 /draft1 /profiles ... /bin /lib /include Any idea what the problem is?