Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
only part of task executed when connection lost on redis using django celery
I have a django celery task that is only partly executing. I start up the app and the connection looks good: INFO/MainProcess] Connected to redis://elasticache.cache.amazonaws.com:6379/0 [2018-02-17 23:27:24,314: INFO/MainProcess] mingle: searching for neighbors [2018-02-17 23:27:25,339: INFO/MainProcess] mingle: all alone [2018-02-17 23:27:25,604: INFO/MainProcess] worker1@test_vmstracker_com ready. I initiate the process and the task is received an executed: [2018-02-17 23:27:49,810: INFO/MainProcess] Received task: tracking.tasks.escalate[92f54d48202] ETA:[2018-02-18 07:27:59.797380+00:00] [2018-02-17 23:27:49,830: INFO/MainProcess] Received task: tracking.tasks.escalate[09a0aebef72b] ETA:[2018-02-18 07:28:19.809712+00:00] [2018-02-17 23:28:00,205: WARNING/ForkPoolWorker-7] -my app is working- Then I start getting errors and it doesn't finish the task where my app sends an email [2018-02-17 23:28:00,214: ERROR/ForkPoolWorker-7] Connection to Redis lost: Retry (0/20) now. [2018-02-17 23:28:00,220: ERROR/ForkPoolWorker-7] Connection to Redis lost: Retry (1/2 Does anyone know why only have executes and then the connection is lost? Here is the full stacktrace: [2018-02-17 23:28:19,382: WARNING/ForkPoolWorker-7] /usr/local/lib/python3.6/site-packages/celery/app/trace.py:549: RuntimeWarning: Exception raised outside body: ConnectionError("Error while reading from socket: ('Connection closed by server.',)",): Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/redis/connection.py", line 177, in _read_from_socket raise socket.error(SERVER_CLOSED_CONNECTION_ERROR) OSError: Connection closed by server. During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/local/lib/python3.6/site-packages/redis/client.py", line 2879, in execute return execute(conn, stack, raise_on_error) File "/usr/local/lib/python3.6/site-packages/redis/client.py", line 2764, in _execute_transaction self.parse_response(connection, '_') File … -
How do I replace content with other content in a Django template?
I am iterating over my model and I wanted to replace that list with content from same model, only sorted, just by using a button. Let's presume I have this: <div class="col-md-3"> <button>Replace content </button> </div <div class="col-md-9"> {% for c in cats%} {{c.name}} {% endfor %} <p>Content to be replaced</p> </div> <div class="col-md-9"> {% for c in animal.cats_set.all %} {{c.name}} {% endfor %} <p>Content to replace above content, sorted by if cat belongs to same animal</p> </div> How would I replace the content with the second content in this case ? Im thinking about a jQuery. -
ListField not found error in django
I am trying to use mongodb with django. My main poject name is 'mysite' and inside that there is an app named 'blog' and inside blog/models.py, I have written the following portion. from django.db import models from djangotoolbox.fields import ListField class Post(models.Model): title = models.CharField() text = models.TextField() tags = ListField() comments = ListField() I have installed djangotoolbox. When I run the command on python shell from blog.models import Post It shows the following error. >>> from blog.models import Post Traceback (most recent call last): File "<console>", line 1, in <module> File "E:\Study\mysite\blog\models.py", line 2, in <module> from djangotoolbox.fields import ListField File "C:\Program Files (x86)\Python36-32\Lib\site-packages\djangotoolbox\fields.py", line 4, in <module> from django.utils.importlib import import_module ModuleNotFoundError: No module named 'django.utils.importlib' >>> Why is this error occurring? and what is its solution? Because I have seen all over the internet and could not find any. -
I don't know how to render entries of my models properly in Django template
I have a Course model from which I render my courses in the template. It also allows me to paginate or search through them. But I also want to sort the courses by faculty or by study programme (other models) and be able to paginate or search through them as well. Basically I want that by clicking, for example, on faculty name on the left column, the content on right column will be replaced with the courses of that faculty, and they will also have pagination and be searchable. I think is easy, but I don't have any idea yet. def index(request): query_list = Course.objects.all() query = request.GET.get('q') if query: query_list = query_list.filter(Q(name__icontains=query)) paginator = Paginator(query_list, 1) page = request.GET.get('page') try: courses = paginator.page(page) except PageNotAnInteger: courses = paginator.page(1) except EmptyPage: courses = paginator.page(paginator.num_pages) context = { 'courses': courses, 'faculties': Faculty.objects.all(), 'departments': Department.objects.all(), 'studies': StudyProgramme.objects.all(), 'teachers': Teacher.objects.all() } return render(request, 'courses/index.html', context) <div class="container-fluid"> <div class="row"> <div class="col-md-3"> <div class="jumbotron"> <h4>Sort courses</h4> <hr> <br> <ul> {% for faculty in faculties %} <li><a href=""> {{ faculty.name }}</a></li> {% for department in faculty.department_set.all %} {% for study in studies %} <ul> {% if study.department == department %} <li>{{ study.name }}</li> {% endif … -
Django querying lists in Postgres JSONField
For the below given model, from django.contrib.postgres.fields import JSONField from django.db import models class Dog(models.Model): name = models.CharField(max_length=200) data = JSONField() def __str__(self): return self.name I have created an object as follows. Dog.objects.create( name='Rufus', data=[ { 'owner': 'Bob', }, { 'owner': 'Rob', }, ]) I want to query if the dog was owned by the given person, since the data is list how do I query if the list consists given value? >>> Dog.objects.filter(data__0__owner='Bob') ... <QuerySet [<Dog: Rufus>]> >>> Dog.objects.filter(data__0__owner='Rob') ... <QuerySet []> My Required result is, >>> Dog.objects.filter(query_on_data_to_know_if_the_given_person_is_owner='Rob') ... <QuerySet [<Dog: Rufus>]> -
Django logging in error- log in form does not log user in
When I try to log in as a user I can enter the username and password into the form and it continues to the next page, but it doesn't actually sign the user in. Where is my issue? login.html file: {% extends 'teammanager/base.html' %} {% block title %}Login{% endblock %} {% block content %} <h2>Login</h2> <form action="/profile/" method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Login</button> </form> {% endblock %} -
InvalidRequestError: This customer has no attached payment source
I've been following the Quickstart guides from Stripe. https://stripe.com/docs/quickstart https://stripe.com/docs/subscriptions/quickstart I have this code at the bottom of my subscription form. <script type="text/javascript"> var displayError= document.getElementById('card-errors'); var stripe= Stripe("pk_test_BjhejGz5DZNcSHUVaqoipMtF"); var elements= stripe.elements(); var style= { base: { fontSize: "1.1875rem", fontSmoothing: "always", fontWeight: "600" } }; var card= elements.create("card",{style:style}); card.mount("#card-element"); card.addEventListener('change', function(event) { if (event.error) { displayError.textContent = event.error.message; } else { displayError.textContent = ''; } }); var formID= "register-form"; var form= document.getElementById(formID); form.addEventListener("submit",function(event){ event.preventDefault(); stripe.createToken(card).then(function(result){ if(result.error) { displayError.textContent= result.error.message; } else { stripeTokenHandler(result.token, formID); } }) }); function stripeTokenHandler(token, formID) { // Insert the token ID into the form so it gets submitted to the server var form = document.getElementById(formID); var hiddenInput = document.createElement('input'); hiddenInput.setAttribute('type', 'hidden'); hiddenInput.setAttribute('name', 'stripeToken'); hiddenInput.setAttribute('value', token.id); form.appendChild(hiddenInput); // Submit the form form.submit(); } </script> Then my views.py has this: if registration_form.is_valid(): stripe.api_key= "sk_test_8rdFokhVsbsJJysHeKgyrMTc" stripeCustomer= stripe.Customer.create( email=request.POST["username"], ) subscription= stripe.Subscription.create( customer=stripeCustomer["id"], items=[{"plan":"plan_CLFfBrRAKl7TRt"}], ) This gives me an error: Internal Server Error: /login-register/ Traceback (most recent call last): File "/home/myUserName/myDjangoProjectWithStripe/local/lib/python2.7/site-packages/django/core/handlers/exception.py", line 42, in inner response = get_response(request) File "/home/myUserName/myDjangoProjectWithStripe/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 249, in _legacy_get_response response = self._get_response(request) File "/home/myUserName/myDjangoProjectWithStripe/local/lib/python2.7/site-packages/django/core/handlers/base.py", line 178, in _get_response response = middleware_method(request, callback, callback_args, callback_kwargs) File "/home/myUserName/myDjangoProjectWithStripe/local/lib/python2.7/site-packages/mezzanine/pages/middleware.py", line 98, in process_view return view_func(request, *view_args, **view_kwargs) … -
Auto pass or recieve a ForeignKey instance value
Say I have a Profile Model that gets created automatically from auth.models.User by using signals and on the Profile model OneToOneField, I have a company attribute tied to a Company model by ForeignKey. Meanwhile this Company model gets created at signup too via Foreignkey using formset_factory in views. What I am aiming to achieve is having the Company instance created at signup passed to the Profile instance Foreignkey as well. Tried using signals, overiding save methods etc. doesn't seem to be working. Here's a sample code, all suggestions are greatly appreciated in advance. from django.contrib.auth.models import User class Company(models.Model): comp_admin = model.ForeignKey(User, on_delete=models.CASCADE) comp_name = models.CharField(max_length=200) ............................. ............................. other attributes omitted ............................. class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company = models.ForeignKey(Company, on_delete=models.CASCADE) -
How to pull information saved from IP address call with GeoIP2() django models to display in my html
I have made function that gets the IP address and stores information from the city_data in GeoIP2(). I want to be able to get the Latitude and longitude from the city_data and display it in my html page. The problem i seem to be arriving at is that I am not able to call any of the information that is saved in the user session model. The information is there when i look at the admin as well as when i print out the querysets In the models i create a new session with usersession/usersessionmanager and and save that session as with the receiver Models.py from django.conf import settings from django.db import models from .signals import user_logged_in from .utils import get_client_city_data, get_client_ip class UserSessionManager(models.Manager): def create_new(self, user, session_key=None, ip_address=None, city_data=None, latitude=None, longitude=None): session_new = self.model() session_new.user = user session_new.session_key = session_key if ip_address is not None: session_new.ip_address = ip_address if city_data: session_new.city_data = city_data try: city = city_data['city'] except: city = None session_new.city = city try: country = city_data['country_name'] except: country = None try: latitude= city_data['latitude'] except: latitude = None try: longitude= city_data['longitude'] except: longitude = None session_new.country = country session_new.latitude = latitude session_new.longitude = longitude session_new.save() return session_new return … -
Rest api in django POST method
views.py from django.shortcuts import render, HttpResponse, get_object_or_404 from django.http import JsonResponse from .models import Locker from .serializers import LockerSerializer from rest_framework.response import Response from rest_framework import status from rest_framework.views import APIView from django.core import serializers def locker_data_response(request): if request.method == 'GET': locker_mac_address = request.GET.get('locker_mac_address') # this will return None if not found locker_information = get_object_or_404(Locker, locker_mac_address = locker_mac_address) print(locker_information) locker_information_serialize = LockerSerializer(locker_information) print(locker_information_serialize) return JsonResponse(locker_information_serialize.data) elif request.method == 'POST': locker_all_information_in_json = serializers.get_deserializer(request.POST()) print(locker_all_information_in_json) json data { "id": 1, "locker_name": "H15_c6d730", "locker_mac_address": "CE:B2:FE:30:D7:C6", "locker_rssi": -78, "locker_protocol_type": "5", "locker_protocol_version": "3", "locker_scene": "2", "locker_group_id": "0", "locker_org_id": "0", "locker_type": 5, "locker_is_touch": true, "locker_is_setting_mode": false, "locker_is_wrist_band": false, "locker_is_unlock": false, "locker_tx_power_level": "-65", "locker_battery_capacity": "57", "locker_date": 1518500996721, "locker_device": "CE:B2:FE:30:D7:C6", "locker_scan_record": "terterwer" } I am trying to send the json in this format from mobile device to my server.I check the get method, it works perfectly. But how can i post this json in my server and how can i get the json data in my server side? -
Multi select input in admin site
I am trying to create a form in Admin site that uses two fields from two different tables as input (single select & multi-select) and make it available for admin user selection and write this to another table. Following is my code. models.py class Employee(models.Model): id = models.IntegerField(primary_key=True, verbose_name='Employee Code') name = models.CharField(max_length=200, verbose_name='Employee Name') def __str__(self): return self.name class Product(models.Model): STATUS = (('New', 'New'), ('Go', 'Go'), ('Hold', 'Hold'), ('Stop', 'Stop')) code = models.IntegerField(primary_key=True, max_length=3, verbose_name='Product Code') name = models.CharField(max_length=100, verbose_name='Product Name') def __str__(self): return self.name class JobQueue(models.Model): emp_name = models.CharField(max_length=200, default='1001') product_code = models.CharField(max_length=200, default='100') admin.py: class JobQueueAdmin(admin.ModelAdmin): form = JobQueueForm fieldsets = ( (None,{'fields': ('emp_name', 'product_code'),}),) def save_model(self, request, obj, form, change): super(JobQueueAdmin, self).save_model(request, obj, form, change) forms.py: class JobQueueForm(forms.ModelForm): emp_name = forms.ModelChoiceField(queryset=Employee.objects.all(), widget=forms.ChoiceField()) product_code = forms.MultiValueField(queryset=Product.objects.all(), widget=forms.CheckboxSelectMultiple(), required=False) def save(self, commit=True): return super(JobQueueForm, self).save(commit = commit) class Meta: model = JobQueue fields = ('emp_name', 'product_code') When I start the web-server, I get the following error: AttributeError: 'ModelChoiceField' object has no attribute 'to_field_name' Can someone please shed some light on how do I get this form right? -
Django-allauth How to Ban Certain Users?
I'm using django-allauth for my Django web app. How can I ban certain users from logging in or restrict certain actions after they log in for a period of time? Should I just deactivate their accounts outright? What are some good solutions? -
Using Google/G-Suite as a user backend for django?
I'm looking at building a django app specifically designed for G-Suite domains. It requires users to be logged in to G-Suite, and would get permissions from groups in G-Suite. I know I could achieve this using django-allauth or similar, but that would involve the django app duplicating the user information in it's own database. In the interests of preventing unnecessary replication, is it feasible to have django directly use Google APIs to handle user logins, but still program the rest of the app in a django kind of a way? Are there any libraries that implement this? If not in django, are there other (python) frameworks that can do this? -
Create WiFi Hotspot project
I am a self-thought python programmer(amateur) and I would like to design a wifi hotspot program which would help to sell my wifi access on time period bases. If possible can someone please direct me where to get all the technical information on how I can go about it. -
Setup Django with Pycharm
I am currently following the tutorial in the link below to set up a Django file. https://www.jetbrains.com/help/pycharm/step-4-creating-and-running-your-first-django-project.html I can install Django for a certain project via adding a package in the project interpreter. In the picture in the link it seems that it is installed for every project. Also, I do not have a "more settings"-option in the new project options. What am I doing wrong? I am using Pycharm 2017.3.3. -
Two Django apps, and Two different servers
I' have two Django applications on two different servers. Server A = Regular Django App Server B = Django Based Rest API My question is how can I fetch the data from the Server A, using the RestAPI. This way I can keep the API and the other Django apps separate. Cheers, S -
jquery .load() causing elements to disappear
I'm using jquery "load()" to update some data whenever the user clicks on a like button. Here's my javascript code: $(document).on('click','.post-like',function(event){ event.preventDefault(); var data = $(this).attr("data"); var refresh = "#"+data; var urll = $(this).attr("formaction"); $.ajaxSetup({ headers: { "X-CSRFToken": '{{csrf_token}}' } }); $.ajax({ url :urll , type : 'POST', data: {}, success : function(json) { $( refresh ).load("{{request.path}} "+refresh); }, error : function(xhr,errmsg,err) { $('#results').html("<div class='alert-box alert radius' data-alert>Oops! We have encountered an error: "+errmsg+ " <a href='#' class='close'>&times;</a></div>"); // add the error to the dom console.log(xhr.status + ": " + xhr.responseText); // provide a bit more info about the error to the console } }); Everything function just fine when I refresh a div that contains the whole page. But when I try to target a specific element or a div inside the page, the element disappears or shifts position. -
django migrating existing database and not using all tables
I recently integrated an existing legacy database-MySQL into models.py in django. There are many tables in this database that I do not need imported in models.py. Is it a good practice to delete the tables one does not need-which corresponds to deleting the classes associated with those tables? -
Can the choices defined in a model class be accessed elsewhere outside the model class?
I have the following model class class Movies(models.Model): MOVIE_CHOICES = ( ('SHAW', 'Shashank Redemption'), ('NIGHT', 'In the Heat of the Night'), ('GOD', 'The God Father'), ('INVIC', 'Invictus'), ) and I am writing the values to a database table. When I query the database table, I will get the key back, e.g. I get 'INVIC" back. In my code I will need to get the value for the key, in this case 'Invictus'. To be able to do this, I need access to the data structure that holds the key-value pair. How to access MOVIE_CHOICES by key outside of the model class? Alternatively, can I use a dictionary to set values for choices? -
How do I replicate behaviour in my Django template?
I have this page which renders my courses from my Courses model. It also allows me to paginate or search through them. But I also want to sort the courses by faculty or by study programme (other models) and be able to paginate or search through them as well. Basically I want that by clicking, for example, on faculty name on the left column, the content on right column will be replaced with the courses of that faculty, and they will also have pagination and be searchable. I think is easy, but I don't have any idea yet. def index(request): query_list = Course.objects.all() query = request.GET.get('q') if query: query_list = query_list.filter(Q(name__icontains=query)) paginator = Paginator(query_list, 1) page = request.GET.get('page') try: courses = paginator.page(page) except PageNotAnInteger: courses = paginator.page(1) except EmptyPage: courses = paginator.page(paginator.num_pages) context = { 'courses': courses, 'faculties': Faculty.objects.all(), 'departments': Department.objects.all(), 'studies': StudyProgramme.objects.all(), 'teachers': Teacher.objects.all() } return render(request, 'courses/index.html', context) <div class="container-fluid"> <div class="row"> <div class="col-md-3"> <div class="jumbotron"> <h4>Sort courses</h4> <hr> <br> <ul> {% for faculty in faculties %} <li><a href=""> {{ faculty.name }}</a></li> {% for department in faculty.department_set.all %} {% for study in studies %} <ul> {% if study.department == department %} <li>{{ study.name }}</li> {% endif %} </ul> … -
Add console to Django error page
Does anyone know of a package that would let you add a console to the django error page? When my template produces an error I want to be able to check out my query sets without having to go back to my view pages/ pdb -
How to convert an existing Django app to run in a virtualenv?
There are so many questions about this, and so many tries I've made and probably bungled... But let me stick to the real problem: I have a fledgling Django app that I want to insulate from future changes to support software. I think putting in under a virtual environment is the answer. I'd like guidance, even just a pointer to the right Howto (one about migrating, not a fresh install). My environment is Ubuntu 16.04.3 LTS, apache2, python3.5 and django 2.0. I'll be upgrading to the next LTS, which is why I want to insulate this app from changes. Complicating matters is the fact that python2 and python 3 are both here, and pyhton2 is the default (what you get when you just call for "python". That makes things weird, for instance, because pip3 is uses the default python, so the output of 'pip3 freeze' is very different from what I get when I run it under python3, and I don't know the details of why. What has failed in the past is my attempts to do it following guidance aimed at a freshly installed OS. What's more, probably because I did something wrong, pip3 lives in my $HOME/.local/bin/pip3. I … -
Add CSRF token to hard coded Django form
I am building a static page with Jekyll that has a hard coded form, I am sending the form data to a Django server, I am having trouble generating a CSRF token. The only way I could get the data to save to the database was if I used a static csrf token which is hacky and pointless. Is there a better way this can be done? This is what I want: <form method="POST" action="http://djangoserver" > {% csrf_token %} <!-- Doesn't work in Jekyll --> <input type="text" name="name" required id="id_name" maxlength="100> </form> But obviously Jekyll doesn't know what that token is, and the POST doesn't send it to the Django Server. This works, but it is vulnerable and hacky, I need the same effect that actually generates a unique token every time. <form method="POST" action="http://djangoserver" > <input type="hidden" name="csrfmiddlewaretoken" value=" some long stuff" > <input type="text" name="name" required id="id_name" maxlength="100> </form> -
How to get PDF output to look exactly like HTML output
I am trying to create a PDF for my client to start invoicing their clients. I've dealt with creating PDFs in the past and remember it was a huge pain to create them. In my Django application, I have two view functions, one that just renders a template that I am using to design the invoice, and another that converts it into a pdf and renders the PDF as well. I have two tabs open side by side one that points to each version template HTML vs. PDF and they look completely different. Is there a special Markup language I have to use to create PDFs, or is their a python package out their that converts HTML to an exact replica of that HTML in PDF ? View Functions from django.shortcuts import render, HttpResponse from django.template.loader import get_template from io import BytesIO from xhtml2pdf import pisa def generate_pdf(template_src, context_dict={}): template = get_template(template_src) html = template.render({}) result = BytesIO() pdf = pisa.pisaDocument(BytesIO(html.encode("ISO-8859-1")), result) if not pdf.err: return HttpResponse(result.getvalue(), content_type='application/pdf') return None def ronin(request): template = get_template('ronin.html') context = {} html = template.render(context) pdf = generate_pdf('ronin.html', context) if pdf: response = HttpResponse(pdf, content_type='application/pdf') filename = "Invoice_%s.pdf" % ("12341231") content = "inline; filename='%s'" … -
what is the equivalent for assertDatabaseHas in Django
Coming from Laravel background learning Django. Forgive me if my question is naive. response = self.client.delete(reverse('details'), kwargs={'pk':pk}, format="json") self.assertEqual(response.status_code, status.HTTP_204_NO_CONTENT) The above test passes, and I would like to go a little further and try to check if the database actually has this item, of course I can query the db and try to match the count. But in Laravel I have used these methods to check for the existence/nonexistence of records. assertDatabaseHas('users', ['id' => 10]); //asserts true if record is present in users table. assertDatabaseMissing('users', ['id' => 10]); // asserts true if record is not present in users table Is there something similar present in Django?