Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to deploy Django app VPS using Apache2?
I'v followed this tutorial which is recommended by various tutorial to deploy Django. https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-ubuntu-14-04 This is the content of my 000-default.conf file .. <VirtualHost *:80> # The ServerName directive sets the request scheme, hostname and port that # the server uses to identify itself. This is used when creating # redirection URLs. In the context of virtual hosts, the ServerName # specifies what hostname must appear in the request's Host: header to # match this virtual host. For the default virtual host (this file) this # value is not decisive as it is used as a last resort host regardless. # However, you must set it for any further virtual host explicitly. #ServerName www.example.com Alias /static /home/myproject/static <Directory /home/myproject/static> Require all granted </Directory> <Directory /home/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/myproject:/home/myproject/myprojectenv/lib/python2.7/site-packages WSGIProcessGroup myproject WSGIScriptAlias / /home/myproject/myproject/wsgi.py ServerAdmin webmaster@localhost DocumentRoot /var/www/html # Available loglevels: trace8, ..., trace1, debug, info, notice, warn, # error, crit, alert, emerg. # It is also possible to configure the loglevel for particular # modules, e.g. #LogLevel info ssl:warn ErrorLog /home/error.log CustomLog /home/access.log combined # For most configuration files from conf-available/, which are # enabled or disabled at a global level, it is … -
Allow user modify only objects created by this user
Is there a way in Django to give user access to admin privileges by allow only editing of objects that were created by this particular user? For example I want to give the user permission to create other users but I don't want to allow them to modify users created by admin or other users with this privileges. I'm using django-admin so the question is in context of it. -
Dynamic filter in Django
In my app, I have a form. Depending of the form, one or many filters could be configured by the user. In my view, I have for exemple : querry= Test.objects.filter(filter1=request.post['filter1'], filter2=request.post['filter2'], filter3=request.post['filter3']) So, sometimes filter1, filter2 or filter3 could not exist. If any filters doesn't exist, I just want to ignore the filter. I could do a script with many "IF" conditions but may be there is a smart solution ? Thanks for your help ! -
How to reduce SQL queries in Django using prefetch_related?
I am trying to optimize a Django project (vers. 1.8.6) in which each page shows 100 companies and their data at once. I noticed that an unnecessary amount of SQL queries (especially with contact.get_order_count) are performed within the index.html snippet below: index.html: {% for company in company_list %} <tr> <td>{{ company.name }}</td> <td>{{ company.get_order_count }}</td> <td>{{ company.get_order_sum|floatformat:2 }}</td> <td><input type="checkbox" name="select{{company.pk}}" id=""></td> </tr> {% for contact in company.contacts.all %} <tr> <td>&nbsp;</td> <td>{{ contact.first_name }} {{ contact.last_name }}</td> <td>Orders: {{ contact.get_order_count }}</td> <td></td> </tr> {% endfor %} {% endfor %} The problem seems to lie in constant SQL queries to other tables using foreign keys. I looked up how to solve this and found out that prefetch_related() seems to be the solution. However, I keep getting a TemplateSyntaxError about being unable the parse the prefetch, no matter what parameter I use. What is the proper prefetch syntax, or is there any other way to optimize this that I missed? I've included relevant snippets of model.py below in case it's relevant. I got prefetch_related to work in the defined methods, but it doesn't change the performance or query amount. model.py: class Company(models.Model): name = models.CharField(max_length=150) def get_order_count(self): return self.orders.count() def get_order_sum(self): return … -
django admin actions adding css
how i can add class to django admin action select box with bootstrap? action select box or set the default form input in django admin with bootstrap class, so when i create new model and render it to admin site, the form show the input with bootstrap class without modify it before this is my model class ArtikelAdmin(admin.ModelAdmin): def gambar_tag(self, obj): return u'<img src="/%s" width="200" height="auto"/>' % obj.gambar.url gambar_tag.allow_tags = True list_display = ('judul', 'kategori') list_filter = ('judul', 'tanggal', 'kategori') search_fields = ['judul'] form = ArtikelAdminForm -
How to limit Choices for ForeignKey field in Django CreateView?
I have a model structure along those lines: # models.py class Foo(models.Model): ... class Bar(models.Model): foo = models.ForeignKey(Foo) ... class Baz(models.Model): bar = models.ForeignKey(Bar) ... Now, on the DetailView for Foo instances, I have a link to create Baz instances that belong to the Foo instance (via one of its Bar instances). That Link points to the following CreateView: class BazCreateView(CreateView): model = Baz fields = ['bar', ...] As the Baz Instance to be created shall belong to one of foo's Bar instances, I'd like to limit the choices for that field to the Bar instances belonging to foo. So far, I've found ForeignKey.limit_choices_to which seems to be for use in the Model and This question which is 9 years old and thus probably has an outdated answer. If it isn't outdated I'd like some advice on how to access the form object mentioned in the accepted answer and how to pass the Bar id to the CreateView. -
How to Use get_absolute_url() with a foreign key object in Django template
Am relatively new to django and I have searched for this problem but couldn't find a solution. Forgive me if the solution is obvious but I just can't seem to get it right. So, this is the issue. I have two models Parishioner and Community. Parishioner has a many-to-one relationship with Community. On the parishioner_detail page, I am trying to display the community name as a link to the community_detail page. I feel I am not using the get_absolute_url() method correctly. Any help would be appreciated. Models: from django.db import models from django.core.urlresolvers import reverse class Community(models.Model): name = models.CharField(max_length=41) description = models.TextField() leader = models.CharField(max_length=41) email = models.EmailField() phone_number = models.CharField(max_length=20) slug = models.SlugField(max_length=31, unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('people_community_detail', kwargs={'slug': self.slug}) class Parishioner(models.Model): name = models.CharField(max_length=41) date_of_birth = models.DateField('date of birth', blank=True) email = models.EmailField() phone_number = models.CharField(max_length=20) start_date = models.DateField('date posted') societies = models.ManyToManyField(Society, blank=True, related_name='parishoners') communities = models.ForeignKey(Community, blank=True, related_name='parishoners') sacraments = models.ManyToManyField(Sacrament, blank=True, related_name='parishoners') slug = models.SlugField(max_length=31, unique=True) def __str__(self): return self.name def get_absolute_url(self): return reverse('people_parishioner_detail', kwargs={'slug': self.slug}) class meta: ordering = ['name'] verbose_name_plural = "parishioners" Views: from django.shortcuts import get_object_or_404, render, redirect from .models import Society, Community, Sacrament, Festival, Parishioner def … -
Django Rest Framework Model Serializer
experimenting with django+drf. trying to parse the below json data to create a new product with variants in the database using serializers. how do i validate the incoming json data and then map it to my model classes and save them to the database. the attributes 'Size' and 'Color' are stored in a separate table and their ids are referenced in the product_variant table { "title": "third product", "description": "third product description", "sku": "TP3", "price": "1290.50", "category": 1, "variants": [{ "value": "XS", "sku": "TP3XS", "attribute": "Size" }, { "value": "BLK", "sku": "TP3BLK", "attribute": "Color" }] } below are the serializers and the models that i am using in my app Serializers: class CategorySerializer(serializers.ModelSerializer): class Meta: model = Category fields = ('id', 'name') class ProductAttributeSerializer(serializers.ModelSerializer): class Meta: model = ProductAttribute fields = ['attribute_name'] def __unicode__(self): return '%s' % self.attribute_name class ProductVariantSerializer(serializers.ModelSerializer): attribute = ProductAttributeSerializer() class Meta: model = ProductVariant fields = ('id', 'value', 'sku', 'attribute') class ProductSerializer(serializers.ModelSerializer): variants = ProductVariantSerializer(many=True) class Meta: model = Product fields = ('id', 'title', 'description', 'sku', 'price', 'category', 'variants') Models: class Category(models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=45, blank=True, null=True) active = models.IntegerField(blank=True, null=True) class Meta: managed = False db_table = 'category' class DjangoMigrations(models.Model): app = … -
Remove old permissions in django
In my Django site there are some permissions entries linked to applications that I've removed. For example I have permissions entries linked to "Dashboard" and "Jet" applications. How can you remove them? -
Django Rest Framework: Generate a unique obfuscated ID from ID field
I'm currently learning how to build an API for my company. I haven't been doing this for very long at all so I'm basically a junior developer at this point. Following some tutorials, I got my API up and running on a very basic level using class based views. Previously, I had 'id' as one of the fields for several of my serializers. My manager didn't like this, and he pointed out it would reveal potentially sensitive information about our business (if you get customer_id = 13 for your JSON, then you can infer there are 12 other customers, if you get job_id = 5433 then you can infer there are 5432 other jobs, etc). I'm trying to figure out how to add "id" to my serializers' fields without revealing such information, to help with the lookup_args and the urls. Previously, a customer's URL on the API would have been www.example.com/api/customer/5, 5 being the "pk" in the database, and would return JSON data for that customer. I'm not sure how to go about using the pk but obfuscating it somehow. Customer model on models.py class Customer(models.Model): company_name = models.CharField(max_length=100) contact_name = models.CharField(max_length=100) contact_email = models.CharField(max_length=100) user = models.OneToOneField(User) @staticmethod def … -
Adding time limits in celery base task class
I've a class like below. from celery import Task from mycroft.core.alerts import slack_error class MycroftTask(Task): abstract = True def on_failure(self, exc, task_id, args, kwargs, einfo): #dosomething Now I'm extending this class to every other classes. Now I want to add a hard time limit and soft time limit. I've tried below way will this work. from celery import Task from mycroft.core.alerts import slack_error class MycroftTask(Task): abstract = True def __init__(self): self.time_limit = settings.CELERY_TIME_LIMIT self.soft_time_limit = settings.CELERY_SOFT_TIME_LIMIT def on_failure(self, exc, task_id, args, kwargs, einfo): -
'NoReverseMatch at' django mistake
Mistake appeared when I added url to another app. I added <a class="navbar-brand" href="{% url 'posts:listofposts' %}">Home</a> My root.urls: urlpatterns = [ url(r'^', include('posts.urls', namespace= 'posts')) ] posts.urls: urlpatterns = [ url(r'^create/', create_post , name='create_post'), url(r'^(?P<slug>[-\w]+)/edit/$', update_post, name = 'update_post'), url(r'^category/(?P<slug>[-\w]+)/$', category, name='category'), url(r'^(?P<slug>[-\w]+)/$', detail, name = 'detail'), url(r'^$', listofposts , name='listofposts'), ] and my view in post.views: def listofposts(request, category_slug = None): html = 'base.html' Category_all = Category.objects.all() query_set_list = Post.objects.all() query = request.GET.get("q") if query: query_set_list = query_set_list.filter(title__icontains=query) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = Post.filter(category=category) context = { "title" : 'Записки', "list" : query_set_list, 'category_all' : Category_all, } return render(request, html, context) def detail(request, slug): Category_all = Category.objects.all() html = 'post_detail.html' query_set = Post.objects.all() instance = get_object_or_404(Post, slug = slug) context = { "title" : instance.title, "instance" : instance, "list": query_set, 'category_all' : Category_all, } return render(request, html, context) And I got the next mistake Exception Value: Reverse for 'detail' not found. 'detail' is not a valid view function or pattern name. <a href="{{ x.get_absolute_url }}"><p>{{ x.title }}</p></a> Everything worked fine untill I added url link to another app. If I delete url link to another view everithing will be okay. Thx a lot if you … -
Django REST Framework AutoSchema parameters list in ViewSet action
I want to generate swagger (OpenAPI) schema for my DRF project. How can I add query parameters specification to the generated schema? Take a look at FileViewSet.list method. Here request.GET parameter project should be documented, but automatic schema generation misses it. Here is example api project: # views.py class FileSerializer(serializers.ModelSerializer): class Meta: model = File fields = ('name', 'id', 'project') class FileViewSet(viewsets.ModelViewSet): queryset = File.objects.all() serializer_class = FileSerializer def list(self, request): project = request.GET.get("project", None) qs = self.get_queryset().filter(project=project) router = routers.DefaultRouter(trailing_slash=False) router.register(r'^file$', FileViewSet) # OpenAPI Schema generation class SwaggerRenderer(renderers.BaseRenderer): media_type = 'application/openapi+json' format = 'swagger' def render(self, data, media_type=None, renderer_context=None): codec = OpenAPICodec() return codec.dump(data) schema_view = get_schema_view( title='API', public=True, renderer_classes=[SwaggerRenderer], authentication_classes=[], permission_classes=[AllowAny], patterns=router.urls, ) api_urls = router.urls + [url(r'^schema$', schema_view, name="schema")] And then inluding api_urls in the urls.py: # urls .py from .views import api_urls urlpatterns = [ url(r'^v1/', include(api_urls, namespace="v1")), ] -
Issue with timezones in Django Application
I am working on leave system in which manager has employees from different countries and I am displaying who is out of office today.But all the leaves stored in database are in UTC.At now I am comparing today=datetime.datetime.now(pytz.utc).date() with DateField in Database leave_today=leave.objects.filter(status='A',start_date__lte=today, end_date__gte=today,employee_id=request.user.username) With the above query written in views I am fetching who are Out of office. But I now I want to display according to employee time zones. So I can query today as today=datetime.datetime.now(pytz.timezone('Asia/Calcutta')).date() But start_date and end_date in leave_today query are in UTC.How can I change respective start_date and end_date to their timezone within the query of employee and compare it? -
Download pandas generated csv from django response
I'm trying to convert json into csv. Csv file is generate but now I want to return this file with django HttpResponse. Here is my views @is_login_valid def convert_json_to_csv(request): params = request.GET response = HttpResponse(content_type='text/csv') response['Content-Disposition'] = 'attachment; filename=filename.csv' response = get_data_from_server(params.get('graph_id')) df = pd.io.json.json_normalize(response['data']) df.to_csv('data.csv') return response How I pass this csv file to django response without saving file. -
Django local server error
I started learning django and just deployed my first app when this showed up. Any suggestions would be useful. (https://i.stack.imgur.com/GgMjG.png) -
How can I associate story_author name with request.user?
My first problem is once I save a story, the story.author will not associate with request.user. So it brings to another problem, I have to add story_author from user list, and then select an author for the story manually. Here is my damin looks like models.py class StoryAuthor(models.Model): """ Model representing a author. """ user = models.ForeignKey(User, on_delete=models.SET_NULL, null=True) def get_absolute_url(self): """ Returns the url to access a particular story_author instance. """ return reverse('stories_by_author', args=[str(self.id)]) def __str__(self): """ String for representing the Model object. """ return self.user.username class Story(models.Model): author = models.ForeignKey(StoryAuthor,related_name='stories',null=True) sb_thing = models.CharField(max_length=30,null=True) sb_story = models.CharField(max_length=30,null=True) sb_name = models.CharField(max_length=30,null=True) views.py def story_new(request): if request.method == "POST": form = StoryForm(request.POST) #form.StoryAuthor = request.user if form.is_valid(): story = form.save(commit=False) StoryAuthor = request.user story.published_date = timezone.now() story.save() return redirect('story_detail', pk=story.pk) else: form = StoryForm() return render(request, 'story/story_create.html', {'form': form}) -
Django Model - Charfield with choices from a row in another model?
I have created a settings table in Django as per the below:- class Settings(models.Model): name = models.CharField(max_length=200) class Meta: verbose_name = "Settings" verbose_name_plural = "Settings" def __str__(self): return self.name class SettingChoices(models.Model): setting = models.ForeignKey(Settings, on_delete=models.PROTECT) choice = models.CharField(max_length=200) class Meta: verbose_name = "Setting Choices" verbose_name_plural = "Setting Choices" def __str__(self): return '{0} - {1}'.format(self.setting, self.choice) and a sample use of this would be:- Setting = Circuit Type: Choices: DSL 4G Fibre then in another model I want to be able to reference this as set of choices class Circuits(models.Model): site_data = models.ForeignKey(SiteData, verbose_name="Site", on_delete=models.PROTECT) order_no = models.CharField(max_length=200, verbose_name="Order No") expected_install_date = models.DateField() install_date = models.DateField(blank=True, null=True) circuit_type = models.CharField(max_length=100, choices=*** here I would get model settings - Circuit Type - Choices ***) currently I use a list in settings.py but its not fluid, I need my users to be able to alter these settings not for me to manually edit a list in settings.py and push changes each time I attempted the below: functions.py def settings_circuit_types(): from home.models import SettingChoices type_data = SettingChoices.objects.filter(setting__name='CIRCUIT_TYPES') circuit_types = [] for c in type_data: circuit_types.append(c.choice) return circuit_types models.py from app.functions import settings_circuit_types CIRCUIT_CHOICES = settings_circuit_types() ... circuit_type = models.CharField(max_length=100, choices= CIRCUIT_CHOICES) but this has … -
Django management command without working db connection
I have a number of projects that use the following configuration model: settings.py includes default configuration and config specifications, mainly used for development purposes. The default settings (including db settings) can be overridden by external configuration files, usually defined by admins for the various environments they manage. In order to ease the admins, I have written a management command and packaged separately, which adds the option to create example configuration files based on the default configuration in settings.py Trying to run the command without the possibility for successful db connection, however, raises django.db.utils.OperationalError. How can I make the command work without db connection, as it does not need one and normally when the command is needed, most probably the db connection is not configured properly. settings.DATABASES != {} as there are the default db settings. Django 1.10.6, Python 3.5.3 -
How to dynamically and conditionally add a list of fields to a queryset in Django?
I want to be able to dynamically add computed fields to my django model from the view. What I have: Foo = Bar.objects.all() FooList = ['E','F','G'] The current output is something like: A | B | C 1 | 1 | 1 2 | 5 | 6 The goal is: A | B | C | E | F | G 1 | 1 | 1 | - | 0 | 5 2 | 5 | 6 | 1 | - | 8 The trouble is that not all values of E, F, G have a value, so filter won't work here. I think I have to combine conditional annotation and dictionary unpacking, so something like: for FL in FooList: Foo = Foo.annotate(**{FL: Sum(When(some_Barvar=FL, then='Other_Barvar'))}) The trouble is, when I add an output_field, it cannot resolve it, and when I do not I get a syntax error near WHEN. I am not sure what I am doing wrong. From the documentation I think it is possible to use a dynamic value for then, in my case that being 'Other_BarVar', but I cannot seem to get it to work in conjuncture with Sum. Anyone have an idea of what I'm doing … -
Django collecting static from virtualenv app on apache wgsi
I'm using autocomplete-light 3 in Django project. I publish production with an virtualenv. Autocomplete-light come with some static file in. I added in settings: STATICFILES_DIRS = ( os.path.join(BASE_DIR, "static"), '/......../........../myapp/static', '/home/myuser/.virtualenv/prd_vrt/lib/python2.7/site-packages/dal/static', '/home/myuser/.virtualenv/prd_vrt/lib/python2.7/site-packages/dal_select2/static', ) but it was not enough to publish the static files. If I include the file in my static folder it works. I don't think this is the best solution ( not easy maintenance). May I add some permission to apache? Or what is the best way to archive this situation? -
Multiple django model values depend on choice field value
My Django model has a pricing_plan choice field. There are 12 fields whose value depends on the pricing_plan value. class Organisation(models.Model): PRICING_CHOICES = ( ('basic', 'Basic'), ('team', 'Team'), ('super', 'Super') ) # some fields... pricing_plan = models.CharField(max_length=50, default='basic') max_host_accounts = models.IntegerField(default=1) max_admin_accounts = models.IntegerField(default=1) max_guests = models.IntegerField(default=10) # more fields whose value depends on pricing_plan value For every different pricing_plan these fields get specific values. In code that could be described like: if pricing_plan == 'basic': max_host_accounts = 1 max_admin_accounts = 1 max_guests = 10 ... elif pricing_plan == 'team': max_host_accounts = 10 max_admin_accounts = 3 max_guests = 25 ... However, there might be more pricing plans in the future and more options and I am afraid that an if/elif/else statement will be huge and not-easily readable. What would be the best/idiomatic way to implement that in a Django model? Use more CHOICE tuples with constant values for every pricing plan? Use Enum classes with constant values for every pricing plan? Use Organisation as parent class and create subclasses like: . class BasicOrganisation(Organisation): max_host_accounts = models.IntegerField(default=1) max_admin_accounts = models.IntegerField(default=1) max_guests = models.IntegerField(default=10) class TeamOrganisation(Organisation): max_host_accounts = models.IntegerField(default=10) max_admin_accounts = models.IntegerField(default=3) max_guests = models.IntegerField(default=25) Anything else? -
How I select any elements with same id in javascript in django
I have a table in Django where all the answers of a test are stored, but when I select them to compare with the response provided by the user, all the answers are the same as the first question. I know this has to do with getElementsById, which only selects the first element. But how do I select all elements of the same id in HTML? {% for resposta in questao.resposta_set.all %} <input type="hidden" id="resposta" name="resposta" value="{{resposta.resposta}}"> <script type="text/javascript"> function mostrarSel(){ if (getRadioValor('opcao_escolhida') == document.getElementById("resposta").value){ alert('Resposta Correta'); } else{ alert('Resposta Incorreta'); } } function getRadioValor(name){ var rads = document.getElementsByName(name); for(var i = 0; i < rads.length; i++){ if(rads[i].checked){ return rads[i].value; } } return null; } </script> {% endfor %} -
How to improve time of python code with database queries
I have some database queries in Django 1.11 which takes about 40 seconds and I want to improve the speed, but my ideas are going out. I want to create a Chart with 6 graphs with the data without having to wait 40 seconds. This is The Model: from django.db import models class MinutenReserveLastYear(models.Model): datum = models.DateField() produkt = models.CharField(max_length=100) grenz_lp = models.FloatField() mittl_lp = models.FloatField() class Meta: indexes = [ models.Index(fields=['datum', 'produkt']), ] I make an Ajax request to get the Data: var neg_last_year = $.ajax({ method: "POST", url: "/prognose/minutenreserve/data/", data: { "produkt": "NEG", "zeitraum": "last_year" }, dataType: "json", context: this }); The view function to get the Data from database: def minutenreserve_data(request): if request.method == "POST": produkt_group = request.POST.get("produkt") zeitraum = request.POST.get("zeitraum") datum_list = {} grenz_lp = {} mittl_lp = {} if zeitraum == "last_year": if produkt_group == "NEG": produkt_list = ["NEG_00_04", "NEG_04_08", "NEG_08_12", "NEG_12_16", "NEG_16_20", "NEG_20_24"] dataset = MinutenReserveLastYear.objects last_year = datetime.date.fromtimestamp(datetime.datetime.timestamp( datetime.datetime.now() - datetime.timedelta(weeks=52))).year days = (datetime.date(last_year, 12, 31) - datetime.date(last_year, 1, 1)).days for j in range(6): grenz_lp[j] = [] mittl_lp[j] = [] datum_list[j] = [] produkt = produkt_list[j] for i in range(days+1): datum = datetime.date(last_year, 1, 1) + datetime.timedelta(days=i) datum_list[j] += [datum.strftime('%d.%m.%Y')] grenz_lp[j] += [dataset.filter(datum=datum, … -
How can I ensure changes to my Celery countdown wont break anything?
I have a number of celery tasks in my Django application that are currently being tested synchronously using CELERY_ALWAYS_EAGER. However this option means that I can't test that changes to the countdown value in apply_async won't break anything. How can I test that nothing else in my application was depending on the longer countdown now that I suspect I no longer need it? I'm using Django 1.10 and Celery 3.1 with Python 3.5.