Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django filter related field
I have related models class Profile: # some fields # related model class Plan: profile = models.ForeignKey(Profile, related_name='plans') start = models.DateField() I want to be able to filter profile's plans. For example I want to get all the profiles, but only select the plans that haven't started yet. Is it possible to achieve such behavior? This code will not return Profiles that don't have plans in the future. And this is behavior is not what I'm looking for. I want to get all the profiles and filter their plans. Profile.objects.filter(plans__start__gte=now()) Also it will return all the plans for Profile even if some of them started already. -
Changing my username field from CharField to ForeignKey
I have been told that using ForeignKey(User) for a username field is recommended so I am trying to implement that now. But I am having trouble transitioning from my current Charfield() to a ForeignKey() field. My code below shows how my current CharField() is being used to assist in an ajax call. It currently works by clicking on a username, which gets the HTML of that username clicked and then can .get() any profile by searching the CharField() like this profile = Profile.objects.get(username=username_clicked). By the way, the HTML from that username clicked is from another Charfield(), author, which is a field in my comment model for when someone makes a comment. So the ajax call opens up a small profile box with a few details of the user clicked. Here's my code: profile model class Profile(models.Model): username = models.CharField(max_length=32, default='AnonymousUser') age = models.IntegerField(default=0) points = models.IntegerField(default=0) def __str__(self): return self.username js $('a.username').on('click', function() { var username = $(this).html(); var url = "/raise_profile/"; $.ajax({ type: 'GET', url: url, data: { username_clicked: username, csrfmiddlewaretoken: $("input[name='csrfmiddlewaretoken']").val() }, success: function (data) { $('.profile_username').html(data.username); $('.profile_age').html(data.age); $('.profile_points').html(data.points); } }) }); view def raise_profile(request): username_clicked = request.GET.get('username_clicked') if request.is_ajax(): profile = Profile.objects.get(username=username_clicked) profileAge = profile.age profileUsername = … -
Jquery append value to Django choicefield
I have a form which looks like this: CROP_CHOICES = ( ('', 'Choose..'), ) class CropMonitoringPlantHeightForm(forms.Form): Crop = forms.ChoiceField(choices = CROP_CHOICES, widget = forms.Select(attrs = { 'readonly': 'True', 'class': 'form-control seleckpicker' })) plot = forms.ModelChoiceField(queryset = Plot.objects.all(), widget = Select(attrs = { 'disabled': 'True', 'class': 'form-control seleckpicker' }), empty_label = "Choose Plot") So what I want is when a user on "template.html" select plot, then crop names related to that plot appended to Crop choice field; Hence i did this: var options = '<option value="">Choose crop..</option>'; crops = plotmanagement_info[1]; for (var i = 0; i < crops.length; i++) { options += '<option value="' + crops[i] + '">' + crops[i] + '</option>'; } $("#id_Crop").html(options); $("#id_Crop option:selected").attr('selected', 'selected'); Values are appended to crop choice field; Problem: When i try to submit my form i get this error message: Select a valid choice. XXX is not one of the available choices. How can append value to Django choicefield using query...? Thanks in advance -
Use dj-stripe v1.0.0 to constrain views based on content
I have a website containing courses, which I want to provide paid subscriptions to. For example, a student could pay $20/month for Maths and $20/month for Physics. Depending on which course(s) they've paid for, they should be able to access content. Otherwise they should get redirected to the payment page. I'm trying out the dev branch (v1.0.0) of dj-stripe to process payments through Stripe, which can handle multiple subscriptions. However, according to the docs, it can only constrain The entire site (through middleware), or Specific views (through decorators) Is there a sensible way to use the view decorator (2nd option) to constrain specific views depending on content? (e.g. Maths and Physics use the same views, but display different course content and should only allow users to access if they've paid) -
Django, reuse select_related/prefetch_related on reverse related manager?
I can see select_related decreases # of queries. However, when I run the same query multiple times, I expect to see the first query gets reused but it's not in the following setup. class Foo(models.Model): pass class Bar(models.Model): foo = models.ForeignKey(Foo, related_name='bars') blog = models.ForeignKey('blg.blog') foo = Foo.objects.create() bar1 = Bar.objects.create(foo=foo) bar2 = Bar.objects.create(foo=foo) foo.bars.select_related('blog') foo.bars.select_related('blog') # <= here, it runs the query again How can I tell django to reuse the first DB query on the second run? -
Django serialize model instance and queryset together
So; I'm trying to serialize django queryset and django model instance together so that i can use their values in my template.html as follow: model.py class PlotManagement(models.Model): farm = models.ForeignKey(Farm,verbose_name='FieldID') plotID = models.ForeignKey(Plot,verbose_name='PlotID') crop = models.ManyToManyField(Crop,verbose_name='Crop Name') cropping_system = models.CharField('Cropping System',max_length=20) function.py(where i serialize) def plotmanagement_info(request,farm,plot): plotmanagement_instance = PlotManagement.objects.get(plotID__pk=plot,farm=farm) plot_cropping_system = plotmanagement_instance.cropping_system crops = plotmanagement_instance.crop.all() plotmanagement_info = [plot_cropping_system,crops] return HttpResponse(json.dumps(plotmanagement_info),content_type="application/json") The error that I'm getting is: [<Crop: Bell pepper>, <Crop: Head cabbage>] is not JSON serializable Is there way to serialize manytomany queryset with string model instance >>>type(plot_cropping_system) >>><class 'str'> >>> type(crops) <class 'django.db.models.query.QuerySet'> -
Cannot fix TypeError: cannot concatenate 'str' and 'NoneType' objects
I tried few solved questions on stackoverflow but couldn't make it work. Can someone kindly help me to fix this. I am using Flask for one of my project and this is the error I am getting. Following is the code and traceback. The code is related to line 12 in sqlutils.py. import hashlib import os import oursql import uuid from flask import Flask from flask_sqlalchemy import SQLAlchemy from mainapp import app app.config['SQLALCHEMY_DATABASE_URI'] = 'mysql+oursql://'+os.environ.get('DB_USR') \ + ':' + os.environ.get('DB_PASSWD')+'@'\ + os.environ.get('DB_HOST') + '/school_new' db = SQLAlchemy(app) Traceback: Traceback (most recent call last): File "run.py", line 3, in <module> from mainapp import app File "/home/osboxes/school/mainapp-web/mainapp/__init__.py", line 85, in <module> import views File "/home/osboxes/school/mainapp-web/mainapp/views.py", line 8, in <module> from mainapp.students.availability_students import add_availability, delete_availability, get_availabilities_by_username, \ File "/home/osboxes/school/mainapp-web/mainapp/students/availability_students.py", line 3, in <module> from .sqlutils import build_where, build_set, get_connection File "/home/osboxes/school/mainapp-web/mainapp/students/sqlutils.py", line 12, in <module> + os.environ.get('DB_HOST') + '/school_new' TypeError: cannot concatenate 'str' and 'NoneType' objects -
Aggregate grouped annotation
I'd like to sum all the event durations per day. This is my model: class Event(models.Model): start = models.DateTimeField() end = models.DateTimeField() Sample data: import datetime from random import randint for i in range(0, 1000): start = datetime.datetime( year=2016, month=1, day=randint(1, 10), hour=randint(0, 23), minute=randint(0, 59), second=randint(0, 59) ) end = start + datetime.timedelta(seconds=randint(30, 1000)) Event.objects.create(start=start, end=end) I can get the event count per day like so: (I know extra is bad, but I'm using 1.9 at the moment. When I upgrade I'll move to using TruncDate) Event.objects.extra({'date': 'date(start)'}).order_by('date').values('date').annotate(count=Count('id')) [{'count': 131, 'date': datetime.date(2016, 1, 1)}, {'count': 95, 'date': datetime.date(2016, 1, 2)}, {'count': 99, 'date': datetime.date(2016, 1, 3)}, {'count': 85, 'date': datetime.date(2016, 1, 4)}, {'count': 87, 'date': datetime.date(2016, 1, 5)}, {'count': 94, 'date': datetime.date(2016, 1, 6)}, {'count': 97, 'date': datetime.date(2016, 1, 7)}, {'count': 111, 'date': datetime.date(2016, 1, 8)}, {'count': 97, 'date': datetime.date(2016, 1, 9)}, {'count': 104, 'date': datetime.date(2016, 1, 10)}] I can annotate to add the duration: In [3]: Event.objects.annotate(duration=F('end') - F('start')).first().duration Out[3]: datetime.timedelta(0, 470) But I can't figure out how to sum this annotation the same way I can count events. I've tried the following but I get a KeyError on 'duration'. Event.objects.annotate(duration=F('end') - F('start')).extra({'date': 'date(start)'}).order_by('date').values('date').annotate(total_duration=Sum('duration')) And If I add … -
Tools to test out a cron job on a Django project
In employing that answer, I've created a cron job on a Django project. In fact, I've implemented a code that will allow to send an automatic email to each client for their birthday. My problem is located when I want to test out the code. Could anyone be able to tell me what I have to do to test this code? What sort of tools are there to do that kind of testing? Thanks in advance! -
Compose decorators applied to class-based views
I have a hierarchy of permission checks and views that need to be protected by them. For example, consider these two checks. def has_profile(user): return user.profile is not None def is_a_sorcerer(user): return user.profile.category == 'sorcerer' Note that it only makes sense to call is_a_sorcerer if the user has a profile. Some views should be accessible to anyone with a profile, some views restricted further to only sorcerers. class ProfileView(View): @method_decorator(user_passes_test(has_profile)) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) class SorcererView(ProfileView): @method_decorator(user_passes_test(is_a_sorcerer)) def dispatch(self, *args, **kwargs): return super().dispatch(*args, **kwargs) However, note that due to inheritance, is_a_sorcerer will be called before has_profile and error out. How to compose these decorators cleanly? I would still like to keep the permission checks as functions so that they can be applied to function-based views. -
Convert version (x.x.x.x) to int
How do I convert a string which is holding a version in this format: 55.2.2883.95 to integer? I am working on modifying open source omaha server and it stores the input version number as big int type in postgresSQL. For example, if the input version string is 55.2.2883.95 then it's corresponding value in the db is stored as 60481918402655. Thanks -
How is Django apps.py supposed to be used?
I'm using django 1.10.5 It seems that the apps.py file in app1 is not imported unless I explicitely set default_app_config = 'app1.apps.App1Config' in __init__ for that module. Yet, in the docs I'm reading "New applications should avoid default_app_config. Instead they should require the dotted path to the appropriate AppConfig subclass to be configured explicitly in INSTALLED_APPS." I'm reading that as including the module in INSTALLED_APPS like INSTALLED_APPS = ( '...', 'app1', ) And I do have that. Maybe I'm confused by the language "dotted path to the appropriate AppConfig subclass" and maybe there's more to it than listing the main module? My specific use is that I want to import handlers.py so it will be included in the application because it has some signal receivers that need to be listening. To do that, I followed the advice in the docs which says "In practice, signal handlers are usually defined in a signals submodule of the application they relate to. Signal receivers are connected in the ready() method of your application configuration class. If you’re using the receiver() decorator, simply import the signals submodule inside ready()." # apps.py from django.apps import AppConfig class App1Config(AppConfig): name = 'app1' def ready(self): import app1.handlers … -
Django - inline formset only saves last instance
I have the following code: models.py class Profile(models.Model): first_name = models.CharField(max_length=100) last_name = models.CharField(max_length=100) created_date = models.DateTimeField(default=timezone.now) class FamilyMember(models.Model): profile = models.ForeignKey(Profile) name = models.CharField(max_length=100) relationship = models.CharField(max_length=100) class Friend(models.Model): profile = models.ForeignKey(Profile) name = models.CharField(max_length=100) forms.py class ProfileForm(ModelForm): class Meta: model = Profile class FamilyMemberForm(ModelForm): class Meta: model = FamilyMember class FriendForm(ModelForm): class Meta: model = Friend FamilyMemberFormSet = inlineformset_factory(Profile, FamilyMember, form=FamilyMemberForm, extra=1) FriendFormSet = inlineformset_factory(Profile, Friend, form=FriendForm, extra=1) views.py class ProfileCreate(CreateView): model = Profile fields = ['first_name', 'last_name'] class ProfileFamilyMemberCreate(CreateView): model = Profile fields = ['first_name', 'last_name'] success_url = reverse_lazy('profile-list') def get_context_data(self, **kwargs): data = super(ProfileFamilyMemberCreate, self).get_context_data(**kwargs) if self.request.POST: data['familymembers'] = FamilyMemberFormSet(self.request.POST) data['friends'] = FriendFormSet(self.request.POST) else: data['familymembers'] = FamilyMemberFormSet() data['friends'] = FriendFormSet() return data def form_valid(self, form): context = self.get_context_data() familymembers = context['familymembers'] friends = context['friends'] with transaction.atomic(): self.object = form.save() if familymembers.is_valid() and friends.is_valid(): familymembers.instance = self.object friends.instance = self.object familymembers.save() friends.save() return super(ProfileFamilyMemberCreate, self).form_valid(form) profile_add.html <form action="" method="post">{% csrf_token %} {{ form.as_p }} <table class="table"> {{ familymembers.management_form }} {% for form in familymembers.forms %} {% if forloop.first %} <thead> <tr> {% for field in form.visible_fields %} <th>{{ field.label|capfirst }}</th> {% endfor %} </tr> </thead> {% endif %} <tr class="{% cycle row1,row2 %} formset_row1"> {% for field … -
Why is nginx accepting requests with a Host header that doesn't match server_name?
I have a site set up this way: nginx as a proxy server, proxying requests tu a gunicorn instance serving a Django site through a UNIX socket. This is my nginx configuration: server { listen 80; server_name api.mysite.com; location /static/ { alias /webapps/mysite/static/; autoindex off; } location / { include proxy_params; proxy_pass http://unix:/webapps/mysite/mysite.sock; } } Is my understanding that nginx, when receiving a request, matches the Host header against the server_name parameter of the server block and, if it matches, it serves it. However, nginx seems to be trying to serve (passing the request to my Django server) request with a Host header different than api.mysite.com. Django has a setting named ALLOWED_HOSTS (in my case set to ['api.mysite.com']) that performs further checking of the Host header and raises an error if the request Host header doesn't match, which shouldn't happen because nginx is supposedly already filtering this. The thing is that I'm seeing errors raised by Django which look like this: Invalid HTTP_HOST header: '/webapps/mysite/mysite.sock:'. The domain name provided is not valid according to RFC 1034/1035. Invalid HTTP_HOST header: 'testp1.piwo.pila.pl'. You may need to add 'testp1.piwo.pila.pl' to ALLOWED_HOSTS. Invalid HTTP_HOST header: 'xxx.xxx.xxx.xxx' (The real IP of my server). You may … -
Can't run scrapy command to run spider on heroku cloud
I'm trying to get the scrapy command to run when I type "heroku run scrapy crawl amazing" on the top level of the project as the spider is in my directory webscraper_git/web scraper/spiders even after I run the command under the webscraper_git/web scraper/spiders where the spider(amazing) it doesn't work. I just get bash: scrapy: command not found. I have Scrapy in my requirements.txt file as well as a scrapy.cfg file. I can run scrapy locally just fine. -
Download a local file using django?
I have this project and I've been trying to download a file that is storaged in a local folder: 'C:/Users/Roberto/Desktop/Media/' Looking for similar questions I've found that I have to modify the settings 'MEDIA_ROOT' This is the code that I'm using for the download: <tbody> {% if archivos %} {% for archivo in archivos %} <tr> <td>{{ archivo.nombre }}</td> <td>{{ archivo.transferido }} </td> <td>{{ archivo.fecha_creacion}}</td> <td>{{ archivo.observaciones }}</td> <td><a href= "C:/Users/Roberto/Desktop/Media/{{archivo.documento}}" download ="{{archivo.nombre}}">Descargar</a> </td> <td>{{ archivo.estado}}</td> </tr> {% endfor %} {% else %} <h1>No existen archivos registrados</h1> {% endif %} </tbody> This is my setting code: MEDIA_ROOT = 'C:/Users/Roberto/Desktop/Media/' MEDIA_URL = 'Media/' This is the error that I'm getting: Error: Network Error I'm using oracle as DB just for storage the directory, and Django 1.10 Please help me... -
Python django Invalid Syntax Error
I am getting the invalid syntax error in my urls.py. The error is in the first url() in the below code. Can someone help me plz? from django.conf.urls import url from . import views app_name = 'music' urlpatterns = [ url(r'^$', views.IndexView.as_view(), name='index'), url(r'^(?P<pk>[0-9]+)/$', views.DetailView.as_view(), name='detail'), ] And this is the view in my views.py: from django.views import generic from .models import Album class IndexView(generic.ListView): template_name = 'music/index.html' context_object_name = 'all_albums' def get_queryset(self): return Album.objects.all() class DetailView(generic.DetailView): model = Album template_name = 'music/detail.html' I have checked online but still can't understand what's the problem. -
How to get view datas to another view?
I have a website where I would like to display the product name the user purchased after he was redirected from the checkout to the thank you page. The problem is that I don't get how I could send a data from a view to another without creating a form in the template. here is two example of views from checkout_payment to checkout_confirmation pages: def checkout_payment(request): customer_id = request.user.profile.stripe_id if request.method == 'POST': try: gig = Gig.objects.get(id=request.POST.get('gig_id')) except Gig.DoesNotExist: return redirect(reverse('purchase_confirmation_detail')) return redirect(reverse('purchase_error_detail')) def checkout_confirmation(request): #how can I get the purchased gig datas ? return render(request, 'purchase/confirmation.html', {}) models.py Gig contains : user, title, price fields. urls.py : name=purchase_confirmation_detail Is there a way to get the last purchased datas avoiding using a form or the urls to get the product informations ? -
Django form.py not updating
I have been going through the Django forms 'tutorial'. Once I had read through the tutorial, I tried modifying it to suit my needs and customize it to learn it Django forms well. I discovered whenever I modified the form, the website would not update. I assume its an error with my code, but I have not been able to find it. # views.py def contact(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = ContactForm(request.POST) # check whether it's valid: if form.is_valid(): # process the data in form.cleaned_data as required # ... # redirect to a new URL: return HttpResponseRedirect('/message_recived/') # forms.py from django import forms class ContactForm(forms.Form): name = forms.CharField(label='Name', max_length=100) email = forms.EmailField(label='Email', max_length=100) message = forms.CharField(label='Message', max_length=500) # models.py from django.db import models class Contact(models.Model): name = models.CharField(max_length=100) email = models.CharField(max_length=100) message = models.CharField(max_length=500) and here is the contact.html template: #contact.html {% extends "BlogHome/headerAndFooter.html" %} {% block content %} <script> document.title = "Pike Dzurny - Contact" </script> <form action="/message_recived/" method="post"> {% csrf_token %} {{ form }} <input type="submit" value="Submit" /> </form> {% … -
Extracting audio using pafy
In my django project I am using youtube's api to search videos based on the query provided by the user. After that I am using pafy to get different details of that video. Inside the loop when I try to extract the data such as the audio of the specific video, pafy has to create a video instance from the given url and when I measured the time inside the loop, it takes almost 1-1.10 seconds for each video. In total, the page in the browser takes 28-29 seconds to load How can i reduce the time and get the urls in a less time? search_response = youtube.search().list( q=searched_query, part="id,snippet", maxResults=25 ).execute() for search_result in search_response.get("items", []): if search_result["id"]["kind"] == "youtube#video": test_url = "https://www.youtube.com/watch?v="+search_result["id"]["videoId"] video = pafy.new(test_url) bestaudio = video.getbestaudio() audio_url = bestaudio.url audio_urls.append(audio_url) -
Django 1.9.5: FieldError for reverse lookup fields occasionally
I'm getting a frustrating intermittent error in Django, when attempting to run the objects.all() for a Queryset that is prefetching. There is an issue where occasionally the model._meta seems to be missing fields, between instantiation of a queryset and running an iteration through it. It's almost as if the queryset's prefetch doesn't actually get run in time for the iteration of the list of objects. In this example, data.service_log is simply a queryset with some prefetched items called servicelog. When I run the queryset in the shell, I can look at all the fields in the self.names_to_path(lookup_splitted, self.get_meta()) method on the queryset. They are all there, specifically the "servicelog." Notice this Traceback for this error it says that "servicelog" is not an available field, yet it lists it in the list of fields to choose from. This seems to be a Django bug, but I can't be sure because I can't explain or isolate the behavior. I can't possibly be the only person getting this error. It seems to be in django/db/models/sql/query.py in the names_to_paths() method. Here's the code that is failing to resolve: query.py names_to_paths(): field = None try: **field = opts.get_field(name)** except FieldDoesNotExist: if name in self.annotation_select: field … -
How to do arithmetic in Django? [duplicate]
This question already has an answer here: How do I do exponentiation in python? 3 answers is it possible to do arithmetic in Django ? I've been trying and it is not allowing me to do so ? ive been trying to work out the following: A = P * (1 + ((R/100) / 12))^(12 * Y) -
Dropdown not working Django
I am using Django for the second time, and I am trying to have a base html file for just the header that I can import in my other pages. The problem is the drop down part does not seem to be working. I can't find the problem in my code. maybe. Here is my code. <nav class="navbar navbar-inverse navbar-static-top example-8"> <div class="container"> <div class="navbar-header"> <button type="button" class="navbar-toggle collapsed" data-toggle="collapse" data-target="#navbar8"> <span class="sr-only">Toggle navigation</span> <span class="icon-bar"></span> <span class="icon-bar"></span> <span class="icon-bar"></span> </button> <a class="navbar-brand text-hide" href="#">Brand Text </a> </div> <div id="navbar8" class="navbar-collapse collapse"> <ul class="nav navbar-nav navbar-right"> <li class="active"><a href="#">Home</a></li> <li class="dropdown"> <a href="#" class="dropdown-toggle" data-toggle="dropdown" role="button" aria-expanded="false">Dropdown <span class="caret"></span></a> <ul class="dropdown-menu" role="menu"> <li><a href="#">Action</a></li> <li><a href="#">Another action</a></li> <li><a href="#">Something else here</a></li> <li class="divider"></li> <li class="dropdown-header">Nav header</li> <li><a href="#">Separated link</a></li> <li><a href="#">One more separated link</a></li> </ul> </li> </ul> </div> <!--/.nav-collapse --> </div> <!--/.container-fluid --> -
Django email: Get receiver in body
I am using EmailMultiAlternatives to send mail to a list of recipients. message = EmailMultiAlternatives( subject, text_template.render(context), from_email, to=recipient_list, cc=cc_list ) Is it possible to get the recipient of an email inside the body? Something that would look like in my email.html dear {{ recipient }} from afeld -
Django - static files (I delete it and they are stiil in my static folder)
I have simple javascript file in my static folder. I noticed I can't modify or delete this file. Django uses always the same file. This is part of my seetings.py: BASE_DIR = os.path.dirname(__file__) STATICFILES_DIRS = [STATIC_DIR, ] STATIC_URL = '/static/' In my /static/js/ i have sucategory.js file. I modified it but when I run my site i still have version before modifications. In my page source I see http://127.0.0.1:8000/static/js/subcategory.js path but it is still unmodified file. I tried refresh site, rerun my local server but it didn't work. I don't now what is going on,