Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Remove Response Class Django Swagger
I am trying to hide the Response Class (Model and Model Schema) from API docs,I am writing via Django REST Swagger 0.3.10. Thanks! I want to hide them in certain APIView where i don't use serializer -
Pyinstaller Error for Djnago project
I have created one project in django.I have created installer for it using pyinstaller.If I run project using python manage.py runserver then project is running fine without any error,but I am not able to run it through installer. I am getting error while running installer. C:\The_Incredibles\Pyinstaller Story\test_proj>.\dist\demo\demo.exe runserver Unhandled exception in thread started by <function check_errors.<locals>.wrapper at 0x03A15978> Traceback (most recent call last): File "site-packages\django-1.10.4-py3.5.egg\django\utils\autoreload.py", line 226, in wrapper File "site-packages\django-1.10.4-py3.5.egg\django\core\management\commands\ru nserver.py", line 113, in inner_run File "site-packages\django-1.10.4-py3.5.egg\django\utils\autoreload.py", line 249, in raise_last_exception File "site-packages\django-1.10.4-py3.5.egg\django\utils\six.py", line 685, in reraise File "site-packages\django-1.10.4-py3.5.egg\django\utils\autoreload.py", line 226, in wrapper File "site-packages\django-1.10.4-py3.5.egg\django\__init__.py", line 27, in s etup File "site-packages\django-1.10.4-py3.5.egg\django\apps\registry.py", line 85, in populate File "site-packages\django-1.10.4-py3.5.egg\django\apps\config.py", line 116, in create File "importlib\__init__.py", line 126, in import_module File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 956, in _find_and_load_unlocked ImportError: No module named 'django.contrib.admin.apps' -
Multiple Login instances CSRF Token Missing django
I have a working django auth system. I have opened two tabs on which my login page is loaded. I logged into the website on one of the tabs. When I try to login using a different account, it raises csrf token missing exception. -
Django migrations - default entries (inserting rows in tables as part of migration)
Background: I'm dealing with quite complex django application and I'm looking for a way to make my life a little bit easier. One of the models (tables) serves as source of "options" for most "select lists" in the system (simple field <-> dictionary construct). It should always be populated with the default values and/or extenden when the there are new entries provided with a new version of the system. I manage it all now manually so: I run migrations for the main app Unload the dictionary tables from the dev enviroment Insert them manually into the enviroment I'm currently upgrading I migrate the rest of the apps which may contain refferences to the dictionary tables All of this because of default values provided in ForeignKeys. Actual Question: Is it possible to add table entries (table content) to the makemigrations process for particular tables?? -
In django, values(*field) doesn't give all values of ForeignKey field with sliced queryset
self.model.objects.filter(pk=2)[:1].values(*fields) self.model.objects.filter(pk=2).values(*fields) Why can't the first one return all values of Foreign key field, but the second one works as expectation? -
how to access/modify django model fields before validating its form in Listview
I have a model Course that has the following attr: class Course(models.Model): user= models.ForeignKey( User, on_delete=models.CASCADE, ) # email= models.EmailField(default=user.email) courseName= models.CharField(max_length=20, blank=False) class Meta: unique_together= ('user','courseName',) def __str__(self): return self.courseName I have created a form where I want the user to enter just the courseName and after they POST it, I will add the requested user in the model as well. This is my form which is getting passed on to the template via my ListView forms.py class CourseForm(forms.ModelForm): class Meta: model= Course fields = ['courseName'] **Here is my views.py where I am struggling with ** class CoursesListView(ListView, FormMixin): model = Course form_class = CourseForm template_name = "userApp/courseList.html" def get_queryset(self): return Course.objects.filter(user__exact=self.request.user) def get_context_data(self,*args,**kwargs): context= super(CoursesListView,self).get_context_data(*args, **kwargs) context['courseForm'] = self.form_class return context def post(self,request, *args, **kwargs): form = self.form_class(request.POST) user = User.objects.get(username__exact=self.request.user) **I want to add the user to my model.user field here** return self.get(redirect, *args, **kwargs) def get(self,request, *args, **kwargs): self.object=None self.form = self.get_form(self.form_class) return ListView.get(self, request, *args, **kwargs) So basically my question is how can I add the user in my model before calling form.is_valid(). -
Forbidden access, CSRF token missing or incorrect
I'm trying to create an ajax function, however I have two issues. Which I think is odd since I'm following another application I have where it works just fine. This is my function. What I'd like use is {% url 'kar:shoppingCartAdd' %} instead of a hardcoded URL. But it'll give me a 404 not found. The hard coded URL will give this from the console. Forbidden (CSRF token missing or incorrect.): /Karklude/shoppingCartAdd/5 [27/Dec/2016 09:35:32] "POST /Karklude/shoppingCartAdd/5 HTTP/1.1" 403 2274 $(".addToCart").click(function() { $.ajax({ url : "shoppingCartAdd/", type : "POST", data : { csrfmiddlewaretoken : '{{ csrf_token }}', 'number' : 5, }, success : function(data) { console.log(data); }, error : function() { console.log('error'); } }); }); url and view function urlpatterns = [ url(r'^shoppingCartAdd/$', views.shoppingCartAdd, name='shoppingCartAdd') ] def shoppingCartAdd(request, number): print(number) //Do some magic return JsonResponse({}) -
Django: static image file should be stored in git repository when using AWS cloudfront and S3?
I developed my Django project with AWS cloudfront and S3. I wonder whether static image file(not media file) should be stored in git repository. I think that if I run collectstatic --settings="production.settings all static files seems to be uploaded on my S3. If so, I think that I don't need to store all static image files in git repository. Am I right? -
Dynamically import url in Django gives 'str' object is not callable
I'm trying to write some code to dynamically import "plugin-like" application in my django project. I'm using Django 1.10 I subclassed the django.apps.AppConfig class and used it to mark the plugins: from django.apps import AppConfig class AutomationAppConfig(AppConfig): def get_url(self): return self.name then, in my project main urls.py I added this code after the main "static" urlpatterns initializazion: ... from slae.util import AutomationAppConfig from django.apps import apps for module in iter(apps.get_app_configs()): if isinstance(module, AutomationAppConfig): url = module.get_url() urlpatterns.append(url(r'^%s/' % url, include('%s.urls' % module.name), name = module.name)) but it gives the following error when the server (re)loads ... File "/cygdrive/d/workspaces/non-ide/slae/slae/urls.py", line 47, in <module> urlpatterns.append(url(r'^%s/' % url, include('%s.urls' % module.name), name = module.name)) TypeError: 'str' object is not callable What I don't understand is that using this code instead it works fine: from slae.util import AutomationAppConfig from . import settings from django.utils.module_loading import import_string import inspect for app in settings.INSTALLED_APPS: try: module = import_string(app) except: pass else: if inspect.isclass(module) and issubclass(module, AutomationAppConfig): urlpatterns.append(url(r'^%s/' % module.name, include('%s.urls' % module.name), name = module.name)) What am I missing? -
I am delete object of model with pk=1, but new object have pk=2
I am delete post in admin panel, put pk of new post equal 2, not 1. Why? What am i do wrong? That's example of my model. class Post(models.Model): author = models.ForeignKey('auth.User') category = models.ForeignKey(Categories) title = models.CharField(max_length=200,verbose_name='Заголовок') text = models.TextField(verbose_name='Текст') created_date = models.DateTimeField(verbose_name='Время создания',default=timezone.now) published_date = models.DateTimeField(verbose_name='Время публикации',blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def approved_commentimages(self): return self.comments.filter(approved_comment=True) def __str__(self): return self.title -
Django: Get user's input in textarea and display them on page
What is a way to get input from textarea and display them onto my webpage immediately after submit? -
How to set default css classes for all built-in form widgets in Django
Short version: is it possible to define a set of default css classes that Django should use whenever rendering a form ? Long version: The context is as follows: I would like to use the css classes defined in the w3.css framework for all my forms (http://www.w3schools.com/w3css/default.asp). I have seen that it is possible to do that in Django at form class definition or at form rendering, but it requires in both cases an explicit declaration of all the form fields. That means that I loose all the benefit of automatic form generation for ModelForms. I would like something as follows instead: Define somewhere (e.g. in the settings file) a default mapping between form fields / widgets and css classes, e.g. 'textinput': 'my_default_css_class_for_text_inputs' By default, for all automatic generation and rendering of forms, the default css classes defined in (1) are used, with no or minimal modification of the existing form classes For specific forms, I can overload the defaults with other values As far as I've understood, such behaviour is not possible in django. The crispy-forms package seems to go in that direction, but it seems to do much more than just that, and I am not sure that … -
How to filter data by time on django?
I have some problem for filter data in django with time, i want filter select option pagi will show data time from 00:00 to 10:00, if select option siang will show data from 10:01 to 18:00, if select option malam it will show data from 18:00 to 23:59, I have code template/index.html like this: <!DOCTYPE html> <head> <html> <meta charset="utf-8"> <title>This Is Latihan</title> </head> <body> <div id="form"> <form action="{% url insert %}" method="POST">{% csrf_token %} Nama Maskapai : <input type="text" name="airline" id="airline" value="{{ airline }}"></input> </br> Waktu Berangkat : <input type="text" name="time" id="time" value="{{ time }}"></input> </br> <input type="submit" name="save" value="save"> </form> </div> <table id="table" border="1"> <tr> <th align="center" width=30px>No.</th> <th align="center" width=150px>Maskapai</th> <th align="center" width=70px>Waktu</th> <th align="center" width=230px colspan="4">Action</th> </tr> {% for i in maskapai %} <tr> <td align="center" width=30px>{{ forloop.counter }}</td> <td width=150px>{{ i.airline }}</td> <td width=70px> {{ i.time }}</td> <form action="{% url action %}" method="POST">{% csrf_token %} <td width=230px colspan="4"> <input type="hidden" name="index" value= "{{ forloop.counter0 }}" /> <input type="hidden" name="time" value= "{{ i.time }}" /> <input type="submit" name="delete" value="delete"> <input type="submit" name="up" value="up"> <input type="submit" name="down" value="down"> </td> </form> </tr> {% endfor %} </table> <form action="{% url filter %}" method="POST">{% csrf_token %} <select name="maskap"> <option value="all">-Pilih … -
Making dictioanry by two list
I have two list l1 = ['cat','dog'] l2= [1,2] Now i want to make i dictionary like this dict { {'name':cat,'id'=1}{'name':dog,'id'=2}} I am usin zip but not fulfilling my requirement -
Django Swagger example code
i am documenting api usin django swagger 0.3.5 and i am seeing that in examples there is a space for Example Value, try : here how can i create the same in my swagger view? -
Pass GET parameters through django's render() shortcut
I have a date filter that I am passing through several django views: views.py def event_list(request): date_query = request.GET.get("date", str(default_event_date())) d = datetime.strptime(date_query, "%Y-%m-%d").date() # do stuff... return render(request, "events/event_list.html", context) But I would like to carry forward the GET parameters through the render(). I've found this answer for how to do this using reverse(), but render() doesn't take a url directly. I suspect I need to add it back in to the request that is passed, but I'm not sure how to do this. -
Django multi-table inheritance affects the 'pk' property of the child model
I discovered a possible issue with "multilayer" model inheritance in Django. I take advantage of multi-table inheritance by defining a base model class, subclassing it and sometimes further subclassing the resulting model. Example: settings.py (diff from Django 1.8 default): ROOT_URLCONF = 'my_app.urls' WSGI_APPLICATION = 'my_app.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'dj_db', 'USER': 'happy', 'PASSWORD': 'camper', 'HOST': '127.0.0.1', } } TIME_ZONE = 'Pacific/Auckland' INSTALLED_APPS += ( 'my_app', ) models.py: from django.db import models from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ import uuid class Base(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) date_changed = models.DateTimeField(_('added/modified'), auto_now=True, editable=False) enabled = models.BooleanField(_('enabled'), default=True) class MyMate(Base): user = models.ForeignKey(User, editable=False) # fields for first and last names, etc. nick = models.CharField(_("Nick"), max_length=75, editable=True, blank=False, unique=True, help_text=_("Mate's nickname")) def __unicode__(self): return unicode(self.nick).encode('utf-8') class Meta: verbose_name = _('Mate') verbose_name_plural = _('Mates') class ReBase(Base): place = models.CharField(max_length=260, editable=False) def __unicode__(self): return unicode(self.place).encode('utf-8') class MyWorkmate(ReBase): class Meta: verbose_name = _('Workmate') verbose_name_plural = _('Workmates') class MyClassmate(ReBase): class Meta: verbose_name = _('Classmate') verbose_name_plural = _('Classmates') Ignore the possible performance problems of such a solution (this is just an example). admin.py: from django.contrib import admin from django.utils.translation import ugettext_lazy as _ from my_app.models import MyMate, MyWorkmate @admin.register(MyMate) class … -
How can I convert django project to exe?
I tried to convert django project into exe using pyinstaller,But I am not able to convert it.mysite is my django project following command i tried pyinstaller --name=mysite mysite/manage.py. after executing above command build ,dist and mysite.spec created but dist does not contain mysite.exe root@ayachp-ind:~/mysite_demo# pyinstaller --name=mysite mysite/manage.py 24 INFO: PyInstaller: 3.2 24 INFO: Python: 2.7.6 24 INFO: Platform: Linux-3.5.0-39-generic-x86_64-with-Ubuntu-14.04-trusty 25 INFO: wrote /root/mysite_demo/mysite.spec 30 INFO: UPX is not available. 31 INFO: Extending PYTHONPATH with paths ['/root/mysite_demo/mysite', '/root/mysite_demo'] 31 INFO: checking Analysis 31 INFO: Building Analysis because out00-Analysis.toc is non existent 31 INFO: Initializing module dependency graph... 33 INFO: Initializing module graph hooks... 147 INFO: running Analysis out00-Analysis.toc 165 INFO: Caching module hooks... 168 INFO: Analyzing /root/mysite_demo/mysite/manage.py 7765 INFO: Processing pre-find module path hook distutils 9195 INFO: Loading module hooks... 9195 INFO: Loading module hook "hook-distutils.py"... 9196 INFO: Loading module hook "hook-django.core.management.py"... 12362 INFO: Processing pre-safe import module hook _xmlplus 14241 INFO: Excluding import 'IPython' 14242 WARNING: Removing import django.core.management.commands.shell from module IPython 14243 WARNING: Removing import django.core.management.commands.shell from module IPython.IPShell 14243 WARNING: Removing import django.core.management.commands.shell from module IPython.start_ipython 14244 INFO: Import to be excluded not found: 'Tkinter' 14244 INFO: Import to be excluded not found: 'matplotlib' 14245 INFO: Loading module … -
Django: how can I check whether any one of forms, stackedInlineforms has changed in admin?
admin.py class ItemInline(AdminImageMixin, admin.StackedInline): model = Item extra = 0 fields = ( 'variation', 'ordered_original_unit_price', 'width', 'height', 'quantity', 'ordered_sale_percent', 'total_price', 'image1', 'image2', ) form = ItemImageAdminForm class PaymentInline(admin.StackedInline): model = Payment extra = 0 fields = ( 'pay_method', 'bank', 'account_owner', 'due_date', 'cash_receipt', 'cash_receipt_for', 'cash_receipt_method', 'cash_receipt_of' ) form = PaymentAdminForm class WorkScheduleInline(admin.StackedInline): model = WorkSchedule extra = 0 min_num = 1 fields = ( 'work_date', 'work_time', ) form = WorkScheduleAdminForm class OrderAdmin(BaseAdmin): class Media: js = ( 'https://code.jquery.com/jquery-2.2.3.min.js', 'js/order_admin.js', ) inlines = [WorkScheduleInline, PaymentInline, ItemInline, ] form = OrderAdminForm As you can see above, OrderAdmin has three inlineAdmins which has its own custom form. What I want to do is : If any of field change detected among the forms, send message to client. What I've tried is to insert has_change() method inside of each form's is_valid() method and send message according to its result. It might seem look good, but problem is that if there were changes in field of each 4 forms, then it sends four messages instead of only one message. How can I deal with it so that I do only one task(send message) if changes detected? -
Django Swagger Different HTTP methods for different API
Iam documenting API using swagger for django ,but i notice that there are GET,POST,PATCH,DELETE methods for some api eventhough i have specified in django code only GET method ,how can i remove unsupported http methods for these API swagger version 0.3.5 -
Django: How to get some of all rows related to a single row
I have 2 models. serviceinvoice and invoiceitems. invoiceitems model is linked to serviceinvoice with a foreignkey. Now for a single invoice how to i get total discount amount. Annotate does not work since its for a single row only. Models.py class serviceinvoice(models.Model): user=models.ForeignKey(settings.AUTH_USER_MODEL,related_name='invoice') invoice_number=models.CharField(max_length=100) invoice_date = models.DateField() invoice_receivable=models.ForeignKey(Receivables,related_name='invreceivable') company_det=models.ForeignKey(Organisation,related_name='companydetails') sale=models.FloatField() Due=models.FloatField() sale_ledger=models.ForeignKey(ledgermodel,related_name='sale_gl',null=True) cash_ledger=models.ForeignKey(ledgermodel,related_name='cash_gl',null=True) taxable_value=models.FloatField() Notes=models.CharField(max_length=750,blank=True,null=True) type=models.CharField(max_length=20,default="invoice") documents = models.FileField(upload_to=document_storing,null=True,blank=True) created = models.DateTimeField(auto_now_add=True) updated = models.DateTimeField(auto_now=True) class Meta: unique_together = (("company_det", "invoice_number","type"),) ordering=('-id',) get_latest_by = "invoice_number" def __str__(self): return str(self.invoice_number) class serviceinvoiceitems(models.Model): user=models.ForeignKey(settings.AUTH_USER_MODEL,related_name='serviceinvoiceitem') company=models.ForeignKey(Organisation,related_name='sitemcomp') invoice_number=models.ForeignKey(serviceinvoice,related_name='serviceitems1') Product=models.ForeignKey(productmodel,related_name='serviceproduct') UOM=models.ForeignKey(productmodel,related_name='serviceuom') Quantity=models.FloatField() Rate=models.FloatField() discount = models.BooleanField(default=False) discount_amount = models.FloatField(null=True,blank=True,default=0) Amount=models.FloatField() discription=models.CharField(max_length=500,blank=True,null=True) def __str__(self): return self.invoice_number I am trying in view: invoice_detailmain = serviceinvoice.objects.get(pk=pk) dis_value_total = Sum('invoice_detailmain__serviceitems1__discount_amount') Its not giving the sum of discount_amount. What is the solution and how to show it in template? -
How to serve static files in Django without using collectstatic?
Though using collectstatic is a convenient way to serve static files by keeping them in a single place, I find it more meaningful to leave the static files in their relevant places where apps reside. Provide the code snippet for serving static files directly. -
Deploy Django API application with AWS Lambda
Is it a way / tutorial how to deploy / convert Existing Django Application (I am using django-rest-famework) for APIs to be available via API Gateway and executed by AWS Lambda functions? I see package zappa, however I want to avoid it.... -
Django url_pattern for *.mp3
I am trying to serve some audio files as static files and trying to refrain from using collectstatic. What would be the url_pattern for serving files that ending with .mp3 ? url(r"^static/............mp3", views.serve_mp3) I have already implemented a function based view called serve_mp3 -
How to connect many-to-many field for 4 objects?
My Models.py class MovieDetails(models.Model): moviename = models.CharField(max_length=200) movieid = models.CharField(primary_key=True, max_length=100) def __str__(self): return self.movieid class TheaterBase(models.Model): theatername = models.CharField(max_length=500) theaterid = models.CharField(primary_key=True, max_length=100) def __str__(self): return self.theaterid class TheaterShowTimings(models.Model): showname = models.CharField(max_length=100) showtime = models.TimeField() # stores only time theatershowtimingsid = models.CharField(primary_key=True, max_length=100) linkmovieactivedays = models.ManyToManyField('MovieActiveDays', through='ActiveShowTimings') def __str__(self): return self.theatershowtimingsid class MovieActiveDays(models.Model): date = models.DateField() # stores single only date moviedetails = models.ForeignKey(MovieDetails, on_delete=models.CASCADE) theaterbase = models.ForeignKey(TheaterBase, on_delete=models.CASCADE) activedayid = models.CharField(primary_key=True, max_length=100) linkshowtimings = models.ManyToManyField('TheaterShowTimings', through='ActiveShowTimings') def __str__(self): return self.activedayid class ActiveShowTimings(models.Model): TheaterShowTimings = models.ForeignKey(TheaterShowTimings, on_delete=models.CASCADE) MovieActiveDays = models.ForeignKey(MovieActiveDays, on_delete=models.CASCADE) activeshowid = models.CharField(primary_key=True, max_length=100) def __str__(self): return self.activeshowid In My Views.py: today_movies_list = list(MovieDetails.objects.raw( 'select distinct * from Book_MovieDetails where movieid IN' '(select moviedetails_id from Book_MovieActiveDays where activedayid IN' '(select MovieActiveDays_id from Book_ActiveShowTimings where theaterbase_id = %s and TheaterShowTimings_id IN' '(select theatershowtimingsid from Book_TheaterShowTimings where showname = %s)))', (url_list[0], url_list[1]) )) The above query is Working Fine. But I want to convert it into a django query set. How to achieve this. Note: In the views.py, I used 4 Models to retrieve data. Any Help is appreciated. Thanks in advance