Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Can I run a background process in Django without starting a parallel process?
This is a very naive question, but I feel I don't understand something fundamental about asynchronous/background tasks in django and python. I try to replicate a simple example provided by django-background-tasks (https://github.com/collinmutembei/django-background-tasks-example) in order to make django perform a background task 60 seconds later than it was actually run. But I guess the same is valid for any other background task manager such as Celery or Huey The example is pretty simple - as soon as the user accesses the url, a simple function that prints a message is executed without blocking the main django process, 60 sec later from background_task import background from logging import getLogger logger = getLogger(__name__) @background(schedule=60) def demo_task(message): logger.debug('demo_task. message={0}'.format(message)) The problem is that I really don't understand the basics. It doesn't run unless I start a separate (or detached) process python manage.py process_tasks. Should I always do it to make the background task work, or there is a way to do it without starting a parallel process? If I should start a parallel process, can I do it from inside of django code. Something like: import subprocess process = subprocess.Popen(['python', 'manage.py','process_tasks'], stdout=subprocess.PIPE, stderr=subprocess.PIPE) -
django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet.- django 1.11
After trying to implement Token Authentication using DRF, i get this error raised in my terminal. I have had seen other related relevant questions with solutions but none of them solved my issue. Below is my wsgi.py """ WSGI config for myApp project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/1.11/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myApp.settings") application = get_wsgi_application() stack trace Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/core/management/__init__.py", line 337, in execute django.setup() File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/System/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/importlib/__init__.py", line 37, in import_module __import__(name) File "/Users/emmnock/Desktop/peaceAppProject/peaceApp/peace/models.py", line 28, in <module> Token.objects.get_or_create(user=user) File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/query.py", line 464, in get_or_create return self.get(**lookup), False File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/query.py", line 371, in get clone = self.filter(*args, **kwargs) File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/query.py", line 782, in filter return self._filter_or_exclude(False, *args, **kwargs) File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/query.py", line 800, in _filter_or_exclude clone.query.add_q(Q(*args, **kwargs)) File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/sql/query.py", line 1261, in add_q clause, _ = self._add_q(q_object, self.used_aliases) File "/Users/emmnock/Desktop/peaceAppProject/lib/python2.7/site-packages/django/db/models/sql/query.py", line … -
Return an instance attribute when a user submits something
Right now I'm trying to make an e-commerce site. My problem is that I cant calculate the total amount the user has spent on the current purchase, I don't know how to use the price from the current Product object, instead I'm just getting None. I know there's probably a simple answer. Here's my models.py: from __future__ import unicode_literals from django.contrib.auth.models import User from django.db import models from django import forms, views from django.db.models import Sum class Product(models.Model): category = models.CharField(max_length=100) name = models.CharField(max_length=100) description = models.TextField() #photo = models.ImageField() price_CAD = models.DecimalField(max_digits=6, decimal_places=2) quantity = models.DecimalField(max_digits=2, decimal_places=0, null=True, editable=True) Here's my views def product_page(request): all_products = Product.objects.all() quantity_forms = QuantityForms(request.POST) quantity = request.POST.get('amount') grand_total = RevenueInfo.user_total if quantity > 0: return HttpResponse(Product().price_CAD) return render(request,'tracker/product_page.html', {'all_products':all_products, 'quantity_forms':quantity_forms}) This is the template: {% load staticfiles %} <!DOCTYPE html> <!DOCTYPE html> <html> {% for object in all_products %} <h3><a href="{{ object.get_absolute_url }}">{{ object.name }}</a></h3> <p>{{ object.description }}</p> <p>{{ object.price_CAD }}</p> <form method='POST'> {% csrf_token %} {{ quantity_forms.amount }}<button>Buy</button> </form> {% endfor %} </html> Right now I'm just trying to at least return the correct amount of the product the user pressed "buy" on. Then from there I'll calculate the total amount of … -
Django multiple image upload to S3
I am struggling to find a solution for a photo gallery in django. I've checkout out every django photo package (photologue, imagekit, etc.) I could find an none of them are really helping me in my quest. I am trying to build a simple image gallery that will allow me to upload multiple photos from the django admin and store them directly in Amazon S3. Can someone please point me to a simple photo app capable of achieving this or what would be the simplest approach? Thank you so much -
Python Magic not working with Django on Digitalocean server
I've recently been deploying a Django project on a digital ocean server (ubuntu). I'm using Nginx and securing the connection with lets encrypt. Here's my problem: I was able to use python magic to validate uploads (during development), but it doesn't seem to be working on on the production server. Here's my form validation: class PostForm(forms.ModelForm): def clean_sound(self): file = self.cleaned_data.get('sound',False) mime = magic.from_buffer(file.read(), mime=True) print(mime) if not mime == 'audio/mpeg': raise forms.ValidationError('File must be mp3') else: return file if file: if file.size > 4*1024*1024: raise ValidationError("Audio file too large ( > 4mb )") if not file.content_type in ["audio/mpeg","audio/mp3", "audio/mp4", "audio/ogg", "audio/wav"]: raise ValidationError("Wrong file type, make sure to use mp3/wav/mp4/ogg") if not os.path.splitext(file.name)[1] in [".mp3",".mp4", ".m4a", ".oga", ".ogg", ".wav"]: raise ValidationError("Doesn't have proper extension") return file else: raise ValidationError("Couldn't read uploaded file") class Meta: model = Places fields = [ 'usersave', 'title', 'longitude', 'latitude', 'sound', ] So yeah, it works perfectly fine on the development server, but throws the 'File must be mp3' validation error every time on the production server. Even if it is the correct file type. What gives? -
Djangorest framework same Generic Create View with GET and POST
I'm using a Generic CreateAPIView to save a model in the database. Here's my code: class AppointmentCreateAPIView(generics.CreateAPIView): permission_classes = (AppointmentCreatePermission,) queryset = Appointment.objects.all() serializer_class = AppointmentSerializer And in my urls.py file, I have this: urlpatterns[ url(r'^appointments/create', AppointmentCreateAPIView.as_view()), ] This url obviously supports the POST operation. However, I want to use this same url to handle a GET request, which would fetch the data necessary to populate the appointment creation form. I understand that I can use separate urls for get and post, but that's not what I'm looking for. Is it possible that I keep the same url, but with different Http Verb, the view would be able to handle both GET and POST request. -
MultiValueDictKeyError at /login/ "u'username'"
I am trying to build a web api for a login page. I keep getting this error. Although i have seen similar and related issues online, the solutions have been of help to me. What am i not doing right? error MultiValueDictKeyError at /login/ "u'username'" login @csrf_exempt def my_view(request): user = request.POST['username'] passcode = request.POST['password'] user = authenticate(request, username=user, password = passcode) if user is not None: login(request, user) return HttpResponse("User logged in") else: return HttpResponse("User not found") -
What's the purpose of the kwargs parameter in url() function?
The Django's url() function has three parameters: url(regex, view, kwargs=None, name=None) I'm trying to understand the use of the kwargs parameter. Is there any practical example of its functionality? -
Django: outsource model properties with inheritance to a more general model
I have noticed, that I need a generalized model based on a specified model, following example should show what I mean: before: class TextResult(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) text = models.ForeignKey(Text) wpm = models.FloatField(default=0.0) accuracy = models.FloatField(default=1.0) after: class TypingResult(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, default=1) wpm = models.FloatField(default=0.0) accuracy = models.FloatField(default=1.0) class TextResult(TypingResult): text = models.ForeignKey(Text) Though there is already some data in the original model, so it is necessary to migrate the data to the new modelstructure -
Python WebDriver FireFox Questions
I'm trying to work on a google scraper with firefox in python and I've ran into some issues when trying to execute from selenium import webdriver from selenium.webdriver.support.ui import Select, WebDriverWait from selenium.common.exceptions import NoSuchFrameException from selenium.webdriver.common.keys import Keys binary = FirefoxBinary('/usr/bin/firefox') browser = webdriver.Firefox(firefox_binary=binary) ..... br = webdriver.Firefox(executable_path="geckodriver") And this is my terminal output when I try to run the script: Traceback (most recent call last): File "firefox-google.py", line 22, in browser = webdriver.Firefox(firefox_binary=binary) File "/home/dave/.local/lib/python2.7/site-packages/selenium/webdriver/firefox/webdriver.py", line 142, in init self.service.start() File "/home/dave/.local/lib/python2.7/site-packages/selenium/webdriver/common/service.py", line 74, in start stdout=self.log_file, stderr=self.log_file) File "/home/dave/.local/lib/python2.7/site-packages/gevent/subprocess.py", line 586, in init reraise(*exc_info) File "/home/dave/.local/lib/python2.7/site-packages/gevent/subprocess.py", line 555, in init restore_signals, start_new_session) File "/home/dave/.local/lib/python2.7/site-packages/gevent/subprocess.py", line 1313, in _execute_child raise child_exception OSError: [Errno 8] Exec format error "OSError: [Errno 8]" My shebang doesnt seem to be the issue as ive tried #!/usr/bin/env python2, and #! /usr/bin/python. My binary path for firefox is correct and I included geckodriver to my path. Not sure what the issue is (kind of a noob) any help is appreciated, can post the full source if needed. -
Django Ajax GET request
i'm very very new to jquery and ajax and right now i've already built a django forum-app whereby on the homescreen, the left side displays the list of forumposts and the right side is blank. Because i'm new to AJAX, i've built my django app in such a way that whenever I click on any of the forumposts displayed on the left, it will redirect me into a details page which shows the content of that post. However, I want to improve the user experience by using AJAX such that whenever I click on any forumpost on the left, the blank space on the right will be updated and display the contents of that specific post. But i'm not quite sure how to begin because i'm new to jquery/ajax. Can somebody help me? Thank you! -
display form errors in Django template
I'm trying to implement Invitation from one user to another user for a company.On the company detail page user has a input field to input username OR email address of other user to invite. Invite works perfect but when user type a wrong username OR email how can I display proper error message? Thanks in advance! Here's my code files: My Template : detail.html <div class="soc_icons"> <h4> Invite Someone! </h4> <form action="" method="POST"> {% csrf_token %} {% bootstrap_field form.email_or_username layout='horizontal' %} <button type="submit" class="btn btn-primary" Value="Invite">Invite!</button> </form> </div> My view: company.py: class Detail(LoginRequiredMixin, generic.FormView): form_class = forms.CompanyInviteForm template_name = 'companies/detail.html' def get_success_url(self): self.get_object() return reverse('groups:companies:detail', kwargs={ 'slug': self.object.slug}) def get_queryset(self): return self.request.user.companies.all() def get_object(self): self.object = self.request.user.companies.get( slug=self.kwargs.get('slug') ) return self.object def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['object'] = self.get_object() return context def form_valid(self, form): response = super().form_valid(form) models.CompanyInvite.objects.create( from_user=self.request.user, to_user=form.invitee, company=self.get_object() ) return response -
How to add heroku custom domain for .tech domains?
I have recently purchased a custom .tech domain, and want to use it for my heroku application. I have done heroku domains:add www.example.tech and I thought that I had properly configured my DNS settings on the back end of the .tech website settings. However, whenever I try to access the website www.example.tech, it returns null. If anyone has experience with .tech domains, any help would be appreciated! Note: When I run host example.tech then it returns: www.example.tech has address 123.456.789.101 www.example.tech is an alias for example.tech.herokudns.com. Does this mean that I'm doing something right? Why isn't the webpage loading anything? Thanks! Davis -
How to send latitud and longitud to django server using AJAX
I am using django, and I need to send the latitud and longitud using AJAX every time I click on an element. This is what I have in my template: {% block js %} <script> var latitud; var longitud; if ("geolocation" in navigator) { navigator.geolocation.getCurrentPosition( function (position) { console.log('Position has been set successfully'); latitud = position.coords.latitude; longitud = position.coords.longitude; }, function (error) { console.log('Position could not be obtained.') }); } var csrftoken = "{{ csrf_token }}"; function csrfSafeMethod(method) { // these HTTP methods do not require CSRF protection return (/^(GET|HEAD|OPTIONS|TRACE)$/.test(method)); } $.ajaxSetup({ beforeSend: function(xhr, settings) { if (!csrfSafeMethod(settings.type) && !this.crossDomain) { xhr.setRequestHeader("X-CSRFToken", csrftoken); } } }); $.ajax( { type: "POST", dataType: 'json', url: {% url 'pledges:home' %}, data: JSON.stringify(dataToSend), success: function (msg) { console.log('Succeeded!'); }, error: function (err) { console.log('Error!'); } }); }); </script> {% endblock %} However, when I try to get the value of latitud in my view, I am getting an error as it was not sent: KeyError: 'latitude' This is the code I have in my view: @login_required def home(request): request_body = json.loads(request.body.decode('utf-8')) print(request_body['latitude']) # mode code return render(request, 'pledges/home.html', context) How can I achieve this, I know that getting the latitud and the longitud is … -
Django/Bootstrap modal won't appear on page load
I'm trying to make a modal pop up when my page loads and nothing is appearing. I have tested this code outside of the {% if request.GET.logout %} and it still does not work. I am also certain that these blocks are being executed. {% if request.GET.logout %} {% block head-extras %} <script type="text/javascript"> $(document).ready(function(){ $('#logout-modal').modal('show'); }); </script> {% endblock %} <div class="modal" id="logout-modal"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p>Modal body text goes here.</p> </div> </div> </div> </div> {% endif %} Edit: This only works if I put <script src="{% static 'js/jquery-3.2.1.slim.min.js' %}"></script> above the script for the $(document).ready. Is there a way to not have to do this? Bootstrap recommends that I should load the jquery before the closing body tag. -
Sphinx adding background image
I'm new to Sphinx docs generator and I want to add a background image to the website. How can I handle that ? I tried to put the bg image to the static folder and tried adding it to the css but it still doesn't appear. -
Django Competition testing
def test_form_valid(self): form = ScraperForm(data={'url': 'http://www.lorem.ipsum/'}) self.assertTrue(form.is_valid()) I was trying a competition and can't figure out what ScapperForm is supposed to return -
Django removing field when passing request.data to serializer
I'm sending a PUT request with a list of images in a multipart/form-data request. Django receives the request in its entirety in my view, however is removing the data in the serializer. Any ideas as to why this might be? In the view: request.data == <QueryDict: {u'images': [<InMemoryUploadedFile: i0.jpg (image/jpeg)>, <InMemoryUploadedFile: i1.jpg (image/jpeg)>]}> In the serializer: validated_data == {u'images': [] } -
Access RelatedManager for a model created by multi-table inheritance
Summary: Is it possible to access a model sub-classed via multi-table inheritance via a relatedmanager on a related model instance? Details: Assuming the following model definitions.. class City(models.Model): ... class Place(models.Model): city = models.ForeignKey(City) class Restaurant(Place): ... I'd like to be able to access all restaurants in the city of Portland like this: portland = City.objects.get(id=1) portland.restaurant_set.all() However restaurant_set or similiar doesn't seem to be an exposed RelatedManager on City, only place_set is exposed. Is there a way to expose restaurant_set, restaurants, or similar as a related manager when accessing a model instance of City? I've also tried created a custom manager for Restaurant, like this: class RestaurantManager(models.Manager): use_for_related_fields = True class Restaurant(Place): objects = RestaurantManager() However it doesn't seem to get me any closer to what I want. Apologies in advance as this is just pseudo-code, not the actual models I'm using in my project/app. It's possible I've introduced an error here not in my actual code base, and will happily clarify and update if so. -
Django m2m_changed signal with admin
Say I have a model: class Category(models.Model): keywords = ManyToManyField('Keyword') Let's say a Django admin that manage the keywords relationship within the Category model. And I have a signal to do some stuff once the relationship changes as below: @receiver(m2m_changed, sender=Category.keywords.through) def reload_category_keyword_mapping(sender, instance, action, **kwargs): # post_remove is not fired in admin due to the way the admin works # 1. clears the relationships first # 2. then adds the relationship back, typical user-interaction workflow. if action == 'post_add': do_stuff() ... As I commented in the signal, typical workflow is it fires pre_clear, post_clear, pre_add then post_add. Now, there are a few gotcha: If I clears the relationship and hit save, post_add action is not fired, nor post_delete (see comment in signal method), but I still want to execute do_stuff() Based on problem 1, if I add if action == 'post_clear', then do_stuff() will execute twice, if I still have exiting keywords relationship. Is there a elegant way to solve this problem(without introducing new fields, eg. timestamps) allows me to only execute do_stuff() only once when keywords relationship changed? -
Django Ordering by Descending Order is glitched
So I have made a leaderboard in Django. It does most stuff Great except something it's drunk. That's not normal! 70 Is higher than 540 and 200! It should be in 3rd Place not 1st! Why is that happening and how can I fix it. I'm ordering the leaderboard using the Total or totalpoints in Descending order using this: participants = Participant.objects.order_by('-totalpoints') This didn't happen when 70 was missing. Now when it's there it glitches. Also the Total points is added from all the challenges and if there was a problem eithher an ASCII or something else it would have crashed. Any Help is going to be appreciated thank you! -
how to iterate and access each values in django template?
I have a dictionary with following data: { "redirects": [ {"status":"301","url":"/ca/products/marketing-cloud/"}, {"status":"301","url":"https://www.example.com/ca/products/marketing-cloud/"}, {"status":"301","url":"/ca/products/marketing-cloud/overview/"} ] } How can I iterate through it so I can access value of status,url ? I am new to python and django. Please help to solve it. Thank you. -
Heroku Django Admin 403 Forbidden
I have a Django app almost up and running on Heroku, the last thing I need is to log into the admin page and make a few changes to the content. Unfortunately, as soon as I enter my credentials it throws a 403 Forbidden error and mentions CSRF tokens. I set up my admin page like in the Django tutorial so there shouldn't be any weird settings or anything, and I'm using django.middleware.csrf.CsrfViewMiddleware in MIDDLEWARE in settings.py. Can anyone give me any pointers for setting up the admin page correctly with Heroku? UPDATE: I'm no longer getting the 403 Forbidden error (although I'm not quite sure what I changed to make that happen) but now Chrome is telling me the page is not secure and won't let me submit my credentials to log in. I haven't set up any SSL settings, mostly because I'm not sure how. Could this have something to do with that? And if so how do I set up SSL with Heroku and Django? -
datetime and timezone: utc conversion. Am I doing it right?
I'm in France. UTC+02:00 If I try on my PC : print(timezone.now()) print(make_aware(datetime.now())) I get this: 2017-05-24 20:46:02.426011+00:00 2017-05-24 22:46:02.426011+02:00 In which format should I write the datetime? Here's my mixin I wrote for all my forms and I'm not sure if I did the right thing. The idea behind this is: I 'convert' all datetimes I get to UTC+00:00 (== UTC) and I write them, and when I have to display them, I call make_aware() so it takes the language of the client browser and use the UTC+xx:xx of the browser. # from django.utils.datetime_safe import datetime as datetime_safe class DateUtilsMixin(object): @staticmethod def make_date_aware(d): # make d "aware" if type(d) is str: return make_aware( datetime_safe.combine(parse_date(d), time(0, 0, 0)), timezone=pytz.timezone('UTC')) elif type(d) is datetime_date: return make_aware( datetime_safe.combine(d, time(0, 0, 0)), timezone=pytz.timezone('UTC')) return d Am I doing the right stuff, and if not, what should I change to be sure to display the date time to the right timezone, using the client's language? -
Django - Inheriting particular ManyToManyField for each child class
Here is what I would like to do; be able to inherit a ManyToManyField from an abstract class and get this ManyToManyField specific to each child with its own intermediate table. Is it possible ? because with this code i got errors... thank you. class Place(models.Model): name = models.CharField(max_length=30) class Mother(models.model): places = models.ManyToManyField(Place, through='%(class)s_Place', related="%(app_label)s_%(class)s_related_place" class Meta: abstract = True class Child1(Mother): pass class Child2(Mother): pass class Child1_Place(models.Model): place = models.ForeignKey(Place) child = models.ForeignKey(Child1) class Child2_Place(models.Model): place = models.ForeignKey(Place) child = models.ForeignKey(Child2)