Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why can't I use the def inside my class? Django
I have defined a function inside my class and calling it inside my class but the code just wouldn't go into my def why? I have something like this which works fine class editView(View): def get(self, request): # codes here data = { 'start': '2016-01-01', 'end': '2016-01-01', } if data['start'] > data['end']: error = { 'status': False } return JsonResponse(error) response = { 'status': True, } return JsonResponse(response) if I do it this way, my def wouldn't run though class editView(View): def get(self, request): # codes here data = { 'start': '2016-01-01', 'end': '2016-01-01', } self.check_time(data) response = { 'status': True, } return JsonResponse(response) def check_time(data): if data['start'] > data['end']: error = { 'status': False } return JsonResponse(error) Thanks in advance -
Converting a Query to Django ORM Code
I want to perform this query to get the id of all the groups that are associated with the table auth_group_permissions. select id from auth_group where id in (select group_id from auth_group_permissions group by group_id) -
What is the correct way to use different const data in local dev and production?
There are many things that are different in deployment and production. For example, in case of using Facebook API, I need to change id of application(because there are different id for testing and production) every time I push update to the app. I update only app, so what do usually django developers do in this case? Possibly saving a variable to settings.py and then getting it from there or creating separated file in virtual environment folder, which in my case at least is also separated ? -
serializer.data is missing some of the data
Context: I am having problem accessing fields which are validated by nested serializers. I have a very sample model as shown below. For 2 of the fields I have their specific serializers. When I try to access the data it returns all the fields except the one validated by the specific serializers. Models looks like this class Sampler(models.Model): sample_name = models.CharField(unique=True, max_length=100) sampling_by = JSONField(max_length=100) extractions = JSONField(max_length=100) max_samples = models.IntegerField(default=100) Serializers class ExtractionsSerializer(serializers.BaseSerializer): table_name = serializers.CharField() extraction_type = serializers.ChoiceField(["ABC"]) dependencies = serializers.ListField(child=RecursiveField(), allow_empty=True, required=False) class SamplingBySerializer(serializers.BaseSerializer): """ Validate sampling_by """ def to_internal_value(self, samples): methods = ["ABC"] sampling_not_supported = [sample for sample in samples if sample['by'] not in methods] if sampling_not_supported: raise ValidationError("{} not in {}".format(sampling_not_supported, methods)) class SamplerSerializer(serializers.ModelSerializer): extractions = ExtractionsSerializer() sampling_by = SamplingBySerializer() class Meta: model = Sampler fields = ('sample_name', 'database', 'schema', 'sampling_by', 'extractions', 'max_samples') Now I do data = { "database": "postgresql://..", "sampling_by":[{ "by":"ABC", "value": ["l32=turn_the"] }], "max_samples":3, "extractions" : [{ "table_name": "person", "extraction_type": "ABC" }] } sampler = SamplerSerializer(data=data) sampler.is_valid() sampler.data() => does not contain data of the nested fields. Like the `sampling_by` and `extractions`. Contains all other fields Any help would be appreciated! thanks -
How to configure wagtail to log admin actions
Our team at 18F is working on requirements to obtain an Authority to Operate (ATO). We use Wagtail for our CMS and we currently have the need to log Admin actions. Django should provide this functionality (and should write logs to the table django_admin_log). However it seems that Wagtail is not logging any Admin actions to that table. We really need this capability, is there a configuration we are missing to make this happen, or is a code change/modification needed. Thanks for any assistance. -
Configuring Apache to Serve Django Project as Virtual Host
I have a server where I host several sites/ applications. One of them is a Django-based app. All of these sites/apps have different domain names. Prior to the Django app, I had used virtual hosts successfully. At the moment, I am trying to re-configure Apache so it serves this Django app under its domain name. All I get is the Internal Server Error Here is my structure. 1) Inside the /etc/httpd/conf.d/vhosts.conf I have no entry pertaining to the Django app, only the existing sites and apps that are served using the basic LAMP stack. 2) /etc/httpd/conf.modules.d/10-wsgi.py: <IfModule !wsgi_module> LoadModule wsgi_module modules/mod_wsgi.so </IfModule> #WSGIScriptAlias /test_wsgi /var/www/vhosts/app_name/test_wsgi.py #WSGIScriptAlias / /var/www/vhosts/app_name/app_name/wsgi.py WSGIPythonPath /var/www/vhosts/app_name/:/var/www/vhosts/app_name/app_name-site/lib/python3.6/site-packages/ <VirtualHost *:80> # This is name based virtual hosting. So place an appropriate server name # here. Example: django.devsrv.local ServerName app_name.com # Insert the full path to the wsgi.py-file here WSGIScriptAlias / /var/www/vhosts/app_name/app_name/wsgi.py # PROCESS_NAME specifies a distinct name of this process # see: https://code.google.com/p/modwsgi/wiki/ConfigurationDirectives#WSGIDaemonProcess # PATH/TO/PROJECT_ROOT is the full path to your project's root directory, # containing your project files # PATH/TO/VIRTUALENV/ROOT: If you are using a virtualenv specify the full # path to its directory. # Generally you must specify the path to Python's site-packages. #WSGIDaemonProcess {{ project_name … -
Django Admin - get_form override
I'd like to override get_form method in my admin.py. I wrote this code: def get_form(self, request, obj=None, **kwargs): form = super(InactiveSiteAdmin, self).get_form(request, obj, **kwargs) form.base_fields['category'].widget.can_add_related = False form.base_fields['subcategory'].widget.can_add_related = False form.base_fields['category1'].widget.can_add_related = False ... ... form.base_fields['category'].widget.can_change_related = False return form Is it possible to override all fields in one line?: form.base_fields[ALL_FIELDS].widget.can_add_related = False -
Create a special tuple with queryset and loop condition
If I execute some commands in the Django's interactive shell, I got In [12]: Perception.objects.all() Out[12]: <QuerySet [<Perception: Perception #0000001>, <Perception: Perception #0000002>, <Perception: Perception #0000003>, <Perception: Perception #0000004>, <Perception: Perception #0000005>, <Perception: Perception #0000006>]> In [13]: perception1 = Perception.objects.get(pk=1) In [14]: perception1.loan.request.customer.user.last_name Out[14]: u'Kshlerin' In [15]: perception1.loan.request.customer.user.first_name Out[15]: u'Dwight' From those information, I would like to create a tuple. For instance, (('fullname1', _('Full name 1')), ..., ('fullnamen', _('Full name n'))), where `fullname` is simply `first_name + last_name`. Could anyone have an idea how I could do such thing? -
Developing django-cms dropdown menus.
I'm new to django and django-cms. I read the official docs and tried to find any other info on the internet, that could guide me through making dropdown menus in django cms. But unfortunately for me,the official docs are really raw (i dont get it at all whats about the menus) and on the internet theres nothing sensible enough. Please explain me or give a step by step guide on this topic. At this moment the menu is working and the only code that i have for that is a pair of "ul's" and this {% show_menu 0 100 100 100 %} inside them. -
{{object.image.url}} and {{object.image.path}} show as unknown in template where as {{object.image]} shows the path [Django]
I dont know what is going on but this is bothering me a lot. As written in the question .url returns unknown in template. but when i try Model.objects.get(username=1) and print the returned object chained with .url (like object.url) it works and it gives the /media/url/url.png -
How To style a Django formset for fileField
I have this formset. instance = get_object_or_404(Post, user = request.user, slug = slug ) files = file.objects.all().filter(Post=instance) FormSet = modelformset_factory(file, fields=('file',), can_delete=True) formset=FormSet(request.POST or None, request.FILES or None, queryset=files) models.py: class file(models.Model): file = models.FileField(upload_to = upload_location, blank = True, null = True) Post = models.ForeignKey(Post, blank = True, null = True) timestamp = models.DateTimeField(auto_now=False, auto_now_add=True, blank = True, null = True) def filename(self): f = self.file.name f1 = f.split('/', 3)[-1] return f1 def __unicode__(self): return self.file.name def __str__(self): return self.file.name thats how i used it in my template: {{ formset.management_form }} {% for form in formset %} {{form.file}} {{form.DELETE.label}} {{form.DELETE}} {% endfor %} and it shows like this in my browser: i tried every this but i could not able to to get rid of currently and i literally do not know how to style this. please help me guys. -
Using django permissions in template tags
I'm currently checking permissions in my templates to decide wether or not i want to display a particular link. This works very well for my base.html that is extending in my normal templates: base.html {% if perms.myapp.can_add %} #display link {% endif %} my template {% extends "riskass/base.html" %} {% block content %} # do stuff # {% endblock %} BUT i also use template tags for repetitive view, and the same permission check don't seem to work in them. Does anybody have an idea ? my template {% extends "riskass/base.html" %} {% load show_item%} {% block content %} # do stuff # {% endblock %} templatetags/show_item.py from django import template register = template.Library() @register.inclusion_tag('myapp/show_item.html') def show_item(ratings): return {'items': item} myapp/show_item.html {% for rating in ratings %} # display stuff: this works ... # check permissions: {% if perms.myapp.can_add %} #display other link: doesn't do anything {% endif %} -
How to configure my ajax/views function to return a dictionary
So I have the following html with an ajax request: <script> $("#search_button").on("click", function(){ var start_date = $("input[name=\"startdate\"]").val(); var end_date = $("input[name=\"enddate\"]").val(); var machine_id = $("#machine_id").val(); // console.log(start_date); // console.log(end_date); // console.log(machine_id); $.ajax({ url: ('/reports/machine_search'), type: 'POST', data: {'start_date': start_date, 'end_date': end_date, 'machine_id': machine_id}, success: function(data) { console.log(data); } }); }) </script> This is my url.py file with the respective url '/reports/machine_search': from django.conf.urls import url from . import views from django.views.decorators.csrf import csrf_exempt urlpatterns = [ url(r'^$', views.home, name='home'), url(r'^dashboard', views.dashboard, name='dashboard'), url(r'^login', views.login, name='login'), url(r'reports', views.reports, name='reports'), url(r'^logout/$', views.logout_view, name='logout'), url(r'^reports/machine_search', csrf_exempt(views.machine_search), name='machine_search'), url(r'^test', views.my_view) ] and then the respective views file: @login_required @csrf_exempt def machine_search(request): test = request.data['start_date'] print(test) run_response = {'test1': 'placeholder1', 'test2': 'placeholder2'} return JsonResponse(run_response) My problem is, that for the time being I simply want the ajax request to return the dictionary that is created in my views function. However, in my success line in ajax, where I console.log the response, in my console I am receiving the entire html of current page where I am making my ajax request. What or where am I going wrong? I simply want my request to return a dictionary from the views function and be able to access … -
Correct usage of django AbstractBaseUser class
I'm trying to move beyond tutorial-level knowledge and create my own user class by extending the AbstractBaseUser meta class, but I am having trouble finding an example that actually shows how to interact with this type of model via the API. Here's my model: from __future__ import unicode_literals from django.db import models from django.utils.translation import ugettext as _ class Country(models.Model): iso3166 = models.CharField(_("country ISO 3166"), max_length=3, default="840", primary_key=True) name = models.CharField(_("country name"), max_length=40, default="USA") def __unicode__(self): return self.name class MyUser(AbstractBaseUser): postal_code = models.CharField(_("zip code"), max_length=5, blank=True, default='') country = models.ForeignKey(Country)REQUIRED_FIELDS = ['country'] And here I am trying to interact with it via the shell: from myapp.models import MyUser, Country from django.utils.translation import ugettext as _ c = Country(iso3166="840",name=_("United States of America")) c.save() q = Country.objects.get(iso3166="840") g = MyUser(username="bob",password="pass1",first_name="Robert",last_name="Smith",email="bob@here.net",country=q) Which works fine up until the line where I define g, whence I get an error: TypeError: 'username' is an invalid keyword argument for this function I get what the error is saying and don't mind it, but I'm not sure what the correct syntax is for creating a new MyUser object. -
Django, Django REST Framework, Internet Explorer and CSRF token missing or incorrect
We have a Django App using REST Framework. It is a nginx, redis, celery, gunicorn and PostgreSQL setup. There is only one App server. Our ajax calls use this function : $.ajaxSetup({ beforeSend: function (jqXHR, settings) { ... jqXHR.setRequestHeader("X-CSRFToken", secureCheck.reqCSRFToken()); Calls are sent to this : @api_view(['POST']) def save(request): ..... return HttpResponse(json.dumps(save_results_and_errors, cls=DjangoJSONEncoder), 'application/json') We never got any kind of error related to CSRF except for some people, one out of six, using Internet Explorer (version 9 or 11). The "save" function keeps returning an error {"detail":"CSRF Failed: CSRF token missing or incorrect."}. Clearing IE history, cache and cookies did not worked. The only way to solve this was to restart the computer (???!!). How can i track down this behavior ? We do not have any iframe in any web page. Nothing in our log files is related to this issue. Does anybody have a clue on this ? -
in Django, how to handle get() when there's no data
i have this line in Django: data['Sponsor'] = models.Family.objects.get(Dependent=data['member']) I know for a fact, there's either one record or no records. but while filter() returns a , get() appears to error out. I just need the one record if there's one. How do I use get() to act like filter()? Thanks. -
Django admin custom widget issue
Hi I've started my adventure with django last week but I've problems with defining custom admin widget, more precisely with posting changed data from my custom widget back to database - widget is rendering just like I am expecting it but nothing happens on submitting whole form. I would appriciate some help with figuring out what am I doing wrong and how to do it proper. Here`s my code: widget template: <br/> <br/> <br/> {% for record in records %} <div> <label>Opis usterki:</label> <input type="text" value="{{record.Description}}" /> {% if record.Resolved %} <input type="checkbox" checked="checked"> {% else %} <input type="checkbox"> {% endif %} </div> <br/> {% endfor %} admin.py from django.contrib import admin from .forms import * from .models import * class VehicleAdmin(admin.ModelAdmin): list_display = ['PlateNumber','Vin'] form = ManageVehicleForm class RepairAdmin(admin.ModelAdmin): list_display = ['CarArrivalDate', 'Vehicle', 'Customer'] search_fields = ['Vehicle__Brand', 'Vehicle__Model', 'Vehicle__PlateNumber'] form = ManageRepairForm class FaultAdmin(admin.ModelAdmin): form=ManageFaultForm # Register your models here. admin.site.register(Vehicle,VehicleAdmin) admin.site.register(Customer) admin.site.register(Fault,FaultAdmin) admin.site.register(Repair,RepairAdmin) models.py from django.db import models from .enums import * class Customer(models.Model): Name = models.CharField(max_length=255) Email = models.EmailField() Phone = models.CharField(max_length=20) Password = models.CharField(max_length=255, null=True) RegistrationDate = models.DateField() def __str__(self): return "{0} {1} {2}".format(self.Name, self.Email, self.Phone) class Vehicle(models.Model): PlateNumber = models.CharField(max_length=20) Vin = models.CharField(max_length=20) Model = … -
How to save image to database after resizing it on Django?
I'm trying to resize a file while the image is uploaded, but I'm have some issue trying to save it into my model's ImageField. Here is my models.py : try: from PIL import Image, ImageOps except ImportError: import Image import ImageOps class IMGResize(models.Model): image = models.ImageField(upload_to='images', blank=True) def save(self, *args, **kwargs): if self.image: img = Image.open(self.image) #<PIL.JpegImagePlugin.JpegImageFile image mode=RGB size=980x490 at 0x59E4B38> imageresize = img.resize((200, 200), Image.ANTIALIAS) #<PIL.Image.Image image mode=RGB size=200x200 at 0x4D5F630> imageresize.save('newname.jpg', 'JPEG', quality=75) #not being saved here to my models super(IMGResize, self).save(*args, **kwargs) How can I resolve this so I can save the resized image into my model ? -
Django 1.8: Join latest entry to foreign key
Assume I have a simple model (borrowed from django docs): class Author(models.Model): name = models.CharField(max_length=100) class Book(models.Model): name = models.CharField(max_length=300) author = models.ForeignKey(Author) pubdate = models.DateField() I want to get a list of authors and their latest book, where it's possible that the author has no books. I can do this with a raw query, but can it be done efficiently within the confines of the OR (ie without hitting the database repeatedly)? The best I've come up with is: for a in Author.objects.prefetch_related('author_set'): a.author_set.latest('pubdate') This results in an additional query per author. It seems latest cannot be determined with the prefetched queryset. Appreciate any direction. -
AttributeError: 'list' object has no attribute 'update'
I have the error AttributeError: 'list' object has no attribute 'update' in the class : class PerceptionFullname(admin.SimpleListFilter): title = _('full name') parameter_name = 'full_name' def lookups(self, request, model_admin): return ( ('error',_('By error')), ('fullname',_('By fullname')) ) def queryset(self, request, queryset): queryset = queryset.order_by('created') perceptions = [] loans = [] for perception in queryset: if perception.loan.pk not in loans: loans.update(perception.loan.pk) perceptions.add(perception.pk) return queryset.filter(pk__in=perception) Question : How could I fix this issue? I tried to solve it, but without success. -
How to show Redis sorted set elements in a webpage
I'm working on a project which simulates a simple twitter-like social media using Redis as DB, and it includes python-to handle redis- and django framework. I have a function which is suppose to return the last 30 posts of a person's timeline, which goes like this: def get_status_messages(conn, uid, timeline='home:', page=1, count=30): statuses = conn.zrevrange('%s%s'%(timeline, uid), (page-1)*count, page*count-1) pipeline = conn.pipeline(True) for id in statuses: pipeline.hgetall('status:%s'%id) return filter(None, pipeline.execute()) the list of timeline posts is stored in a sorted set which saves post id and post time stamp and sorts the list by the latter. And each status post is saved as a hash which has a unique id. timeline zset has the name 'profile:xxx' with xxx being the author's id, and each post has the name 'status:yyy' with yyy being the post's unique id. Im trying to show these posts in a html page, and here goes my home 'view' which represents timeline: def home(request): id = request.session.get('member_id') prof=get_status_messages(conn, id, timeline='home:', page=1, count=30) fp = open('template/home.html') t = Template(fp.read()) fp.close() html = t.render(Context({'item_list': prof.iteritems()})) return HttpResponse(html) And finally in the html file for timeline, we have this: <html> <head> <title>homePage</title> </head> <body> <ol> {% for key, value in item_list … -
Django uploading multiple images connected to a model
Ive been trying to make this for two days now. I have created website that is capable of uploading one image file, but i would like to be able to upload more of them, that are connected to the same main model. This is what i have for one picture upload: forms.py: from django import forms from .models import Exam class ExamForm(forms.ModelForm): class Meta: model = Exam fields = ['exam_number', 'exam_file'] widgets = { 'exam_number': forms.NumberInput( attrs={'id': 'exam_number', 'required': True,}) } Models.py: from django.db import models from django.contrib.auth.models import User from django.template.defaultfilters import slugify from datetime import datetime from django.core.validators import MaxValueValidator, MinValueValidator class Exam(models.Model): exam_number = models.PositiveIntegerField(validators=[MaxValueValidator(6),MinValueValidator(1)]) exam_path = models.CharField(max_length=255) exam_file = models.ImageField() #i want to be able to upload more of these exam_date = models.DateTimeField(auto_now_add=True) exam_user = models.ForeignKey(User, null=True) def __str__(self): return self.exam_path def __int__(self): return self.exam_number views.py: def create_exam(request, letnik_id, classes_id, subject_id): response_data = {} if subject_id in SUBJECTS: path = letnik_id + '/' + classes_id + '/' + subject_id form = ExamForm(request.POST or None, request.FILES or None) if form.is_valid(): exam = form.save(commit=False) exam.exam_user = request.user exam.exam_path = path exam.exam_file = request.FILES['exam_file'] file_type = exam.exam_file.url.split('.')[-1] file_type = file_type.lower() if file_type not in IMAGE_FILE_TYPES: context = { 'error_message': … -
Virtualenv is not being activated from supervisord AWS Elasticbeanstalk
I am trying to deploy my Django Channels app to elastic beanstalk and to start daphne and workers on deployment I have a supervisord script that gets copied and restarted during deployment. Some odd behavior is happening detailed below. This is my channels.config file that gets run during deployment container_commands: 01_copy_supervisord_conf: command: "cp .ebextensions/supervisord/supervisord.conf /opt/python/etc/supervisord.conf" 02_reload_supervisord: command: "supervisorctl -c /opt/python/etc/supervisord.conf reload" When I just have this in my supervisord.conf [unix_http_server] file=/opt/python/run/supervisor.sock ; (the path to the socket file) ;chmod=0700 ; socket file mode (default 0700) ;chown=nobody:nogroup ; socket file uid:gid owner [supervisord] logfile=/opt/python/log/supervisord.log ; (main log file;default $CWD/supervisord.log) logfile_maxbytes=10MB ; (max main logfile bytes b4 rotation;default 50MB) logfile_backups=10 ; (num of main logfile rotation backups;default 10) loglevel=info ; (log level;default info; others: debug,warn,trace) pidfile=/opt/python/run/supervisord.pid ; (supervisord pidfile;default supervisord.pid) minfds=1024 ; (min. avail startup file descriptors;default 1024) minprocs=200 ; (min. avail process descriptors;default 200) directory=/opt/python/current/app ; (default is not to cd during start) ;nocleanup=true ; (don't clean up tempfiles at start;default false) [rpcinterface:supervisor] supervisor.rpcinterface_factory = supervisor.rpcinterface:make_main_rpcinterface [supervisorctl] serverurl=unix:///opt/python/run/supervisor.sock [program:httpd] command=/opt/python/bin/httpdlaunch numprocs=1 directory=/opt/python/current/app autostart=true autorestart=unexpected startsecs=1 ; number of secs prog must stay running (def. 1) startretries=3 ; max # of serial start failures (default 3) exitcodes=0,2 ; 'expected' exit codes for … -
Django 1.7: Can I use prefetch_related() to fetch an ForeignKey without a related_name?
I am trying to display Items to a page with the least amount of database hits as possible (there are a lot of Items). Suppose my models look like this: Class Item(models.Model): name = models.CharField(max_length=50, unique=True) Class ItemAttribute(models.Model): item = models.ForeignKey(Item) name = models.ForeignKey(ItemAttributeName) Class ItemAttributeName(models.Model): name = models.CharField(max_length=50, unique=True) Notice there is no related name. Items have a list of attributes, a good related_name I could use would be item_attributes. But for this question I am not doing that. I was wondering if there is a way to query a list of Items and their attributes so I can determine if the item is used or new. Item.ItemAttribute.ItemAttributeName.name = "USED" would (should) look like Item.item_attributes[0].name.name = "USED" Something like that, you get the gist. Is it possible to query the attributes name used prefetch_related()? I mean I know _related is in the name so this may seem like a dumb question but I was wondering if it's possible. The obvious answer is to stop being an idiot and add a related_name and totally remove the ItemAttributeName model because it doesn't make sense to even exist but don't worry about that right now. -
How do I copy a directory from one container to another container in Docker Compose?
I have two docker-compose services nginx and django, and in my command shell script I perform a gulp task which builds my static files. After the build process is complete, I want to perform a copy command to copy those files to the nginx container, but I'm not sure what command to use. docker-compose.yml django: build: context: . dockerfile: ./compose/django/Dockerfile user: django depends_on: - postgres - redis command: /gunicorn.sh env_file: .env nginx: build: ./compose/nginx depends_on: - django ports: - "0.0.0.0:80:80" gunicorn.sh #!/bin/sh gulp build python manage.py migrate /usr/local/bin/gunicorn config.wsgi -w 4 -b 0.0.0.0:5000 --chdir=/app I'm guessing I could use scp within gunicorn.sh, but i'm not sure how I would reference the nginx service's IP address.