Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django ordering by JSONField key
I have the following django model with a JSONField: class TestModel(models.Model): data = JSONField(default={}) And data field with struct bellow: { "a": 1, "b": 2, } How ordering queryset by one of the data fields? TestModel.objects.all().order_by("data__a") # error -
Streaming response over loop in Django
I want to send the response to the client as and when I received the data after crawling def index(request): urls=all_domain_urls(request.body) for url in urls: yield one_url_data() Is that possible ? -
How to do HTTP long polling with Django Channels
I'm trying to implement HTTP long polling for a web request, but can't seem to find a suitable example in the Channels documentation, everything is about Web Sockets. What I need to do when consuming the HTTP message is either: wait for a message on a Group that will be sent when a certain model is saved (using signals probably) wait for a timeout, if no message is received and then return something to the client. Right now I have the code that can be seen in the examples: def http_consumer(message): # Make standard HTTP response - access ASGI path attribute directly response = HttpResponse("Hello world! You asked for %s" % message.content['path']) # Encode that response into message format (ASGI) for chunk in AsgiHandler.encode_response(response): message.reply_channel.send(chunk) So I have to return something in this http_consumer that will indicate that I have nothing to send, for now, but I can't block here. Maybe I can just not return anything? And then I have to catch the new message on a specific Group, or reach the timeout, and send the response to the client. It seems that I will need to store the message.reply_channel somewhere so that I can later respond, but I'm β¦ -
Design - Users created websites within the main website (Python/Django)
I am asking for advice regarding design and technologies/frameworks which will enable me to create following website within reasonable amount of time: I would like to create a website which will enable the users to maintain their own small websites within in and add content (articles/news) in accordance with specific schema. Every user should have place to publish her/his articles which could be visit by other visitors. Moreover, there have to be a main page which will show the latest articles created by the users and which will offer additional functionalities based on the users content. I have some experience in programming in Python and Django, so I prefer to use them in this project. Any help appreciate. -
How to perfom_create when the objet is created in the admin site. Django RestFramework
I have a perform_create for an object, which creates another object. class DocumentDetailSampleViewSet(viewsets.ModelViewSet): queryset = DocumentDetailSample.objects.all() serializer_class = DocumentDetailSampleSerializer def perform_create(self, serializer): doc_detail_sample = serializer.save() query_set = User.objects.all() ids = query_set.values_list('id', flat=True) for i in ids: doc_detail = DocumentDetail() doc_detail.details_sample = doc_detail_sample doc_detail.user_id_id = str(i) doc_detail.save() As you can see, when I create a DocumentDetailSample a DocumentDetail is also created. It works nicely when I make a "POST". My problem is that DocumentDetailSamples can also be created in the Admin Site. So... When it's created in the Admin site, the perform_create doesn't work anymore and the DocumentDetail is not created. What could I do? I want to create the DocumentDetail also right after the "admin" DocumentDetailSample creation. -
AngularJs, Django RESTful and Restangular: Consuming an array of hyperlinks
I'm having trouble configuring restangular to consume a list of api urls in my response object. Currently, my object response looks like: { cabinet: { folders: ['http://localhost:8000/api/folder/1', 'http://localhost:8000/api/folder/2', 'http://localhost:8000/api/folder/3'] } } but i want it to return the folder objects { cabinet: { folders: [{ files: ['http://localhost:8000/api/file/1' 'http://localhost:8000/api/file/2'] }, { files: ['http://localhost:8000/api/file/3'] }, { files: ['http://localhost:8000/api/file/4'] }, ] } } (and then eventually the file objects inside the folder objects): { cabinet: { folders: [{ files: [{},{}] }, { files: [{}] }, { files: [{}] }, ] } } How can I configure restangular through addResponseInterceptor or other means to consume the array of nested hyperlinks -
Django TabularInline, only have readonly_fields but my FK objects is still showing up and editable
I'm creating a read-only Tabular Inline in the Admin and I can't get rid of this extra dropdown for StatusObject. As you can see I only have the 3 readonly_fields but an extra field is being displayed for TaskStatus.status and it's editable. Any idea why? I'm sure I'm overlooking something simple. class TaskStatusInline(admin.TabularInline): model = TaskStatus extra = 0 readonly_fields = [ 'status_name', "updated_by", 'timestamp' ] can_delete = False def has_add_permission(self, request, obj=None): return False def status_name(self, obj): return obj.status.name Models class TaskStatus(models.Model): class Meta: ordering = ['-timestamp'] status = models.ForeignKey('status') task = models.ForeignKey('Task', related_name="task_status") timestamp = models.DateTimeField(auto_now_add=True) updated_by = models.ForeignKey(settings.AUTH_USER_MODEL, null=True, blank=True) class Status(models.Model): class Meta: unique_together = ['status', 'substatus'] verbose_name_plural = "status" ordering = ['code'] name = models.CharField(max_length=50) status = models.CharField(max_length=25) substatus = models.CharField(max_length=25) code = models.IntegerField() -
django How can I get a weekly average queryset
I have two models that are linked. Here is a subset for simplicity: class Job(models.Model): event = models.OneToOneField(Event, on_delete=models.CASCADE, null=False, blank=False) completion_time = models.DateTimeField(db_index=True, null=True, blank=True) labor_price = models.FloatField(verbose_name='Final Labor Price', blank=True, null=True) and: class Event(models.Model): start_time = models.DateTimeField(db_index=True, null=True, blank=True) end_time = models.DateTimeField(db_index=True, null=True, blank=True) I need to get a few things, and I know they can be done in SQL, but I'm not sure how to do them in django. I need monthly and weekly averages for the labor_price of jobs. In other words, something like this, and I may have it wrong for what I'm doing, as I haven't tested it: SELECT `schedule_event.start_time`, AVG(`jobs_job.labor_price`) FROM jobs_job INNER JOIN schedule_event on jobs_job.event_id = schedule_event.id GROUP BY YEAR(`schedule_event.start_time`), MONTH(`schedule_event.start_time`) HAVING COUNT(`schedule_event.start_time`) = DAY(LAST_DAY(`schedule_event.start_time`)); I also need to get the average hourly labor price for the week, but I'm not quite sure how that would work at the moment. It would be a query that would do something like average(sum(labor_price/(completion_time - event__start_time))) on a given filter of dates. -
pass object variable to ' form.is_valid(): ' function in django
I'm working on a bulk update functionality in django. I have a table that shows the data in my database, and the user selects the objects they would like to edit. Once selected, they click a "Bulk Update" button and it takes them to a django ModelForm. The partial view for this page is such : def BulkUpdate(request): c = {} c.update(csrf(request)) if request.method == "POST": pks = request.POST.getlist("selection") selected_objects = mymodel.objects.filter(pk__in=pks) form = BulkUpdateForm(request.POST) print (selected_objects) if form.is_valid(): gender = form.data['gender'] print (gender) print (selected_objects) return render(request, 'bulkUpdate.html', {'form': form }) The first print (selected_objects) successfully prints all objects that were selected from the prior template within on QuerySet. However the second print (selected_objects) returns a blank QuerySet for each object that was selected. For example, if two objects are selected my terminal will print <QuerySet [<boggarts: boggarts object>, <boggarts: boggarts object>]> but upon submitting a valid form it will print <QuerySet []> <QuerySet []> My main question is how can I get those two objects into my form.is_valid() function. I'd like for my variable selected_objects to be printed the same way in both calls. Any help or advice is amazing. Thank you for your time. -
Django models, How to retrieve a property of a foreign key object
I have a class like this class Product(models.Model): name = models.CharField() another class class Properties(models.Model): description = models.CharField() product = models.ForeignKey(Product) in the str function of the properties class I want to use the object product and its atributes. def __str__(self): p = Product.objects.get(Product) return p.name Somehow it doesnt work, If I just return the 'Product' it shows so it is the object itself, how can I access the atributes then? -
Missing CSRF token when hitting password_reset endpoint
The setup is django 1.10 DRF, using url('^', include('django.contrib.auth.urls')), for authentication. I'm upgrading from django 1.8 to 1.10. The issue is that hitting the password_reset endpoint, with postman for instance, at http://localhost:4200/v1/password_reset/ requires a CSRF token in the cookie, which I do not have. What am I missing? I tried comparing the login workflow to the password_reset workflow. Both views have the decorator @csrf_protect. But when hitting the login endpoint, in middleware/csrf.py, the login view has the csrf_exempt flag on. Any ideas as to what I'm missing or how I could troubleshoot further? -
javascript blockUI is not working in firefox when submit the form
I add jquery.blockUI.js to my html page.and i used it in the script.my html page is: <form class = "form-horizontal" role = "form" id="form" method = "POST" > <button type="submit" class="btn btn-default btn_red" id="btnSubmit">Submit</button> </form> {% block customjs %} <script src="js/jquery.blockUI.js"></script> <script type="text/javascript"> $(document).ajaxStop($.unblockUI); $(document).ready(function() { $("#form").submit(function(){$.blockUI({ message: '<h4><img src="/image/gears.gif" />Please wait...</h4>' }); }); </script> {% endblock %} This is not working firefox 50.1.0 version.when i use this into the submit block it will not work. and I tried the onclick methon in button. <button type="submit" class="btn btn-default btn_red" id="btnSubmit" onclick="testing()">Submit</button> <script> function testing(){ $.blockUI({ message: '<h4><img src="/image/gears.gif" />Please wait...</h4>' }); } It is not Worked.Finally I tried this also, $("#btnSubmit").click(function(){$.blockUI({ message: '<h4><img src="/image/gears.gif" />Please wait...</h4>' }); }); This is also not working in firefox.but this will worked in chrome.So please give me a solution how to run this on firefox.I am creating a python django project.so I can't continue my project without getting this solution. Thanks -
GROUP BY in django ORM with synthetic attributes
Transforming my problem to a simpler domain, suppose I have inherited a django app with a data model representing test grades as letters ("A+", "A", "A-", "B+", etc), and I want to report grade averages as percentages, where {"A+": 100, "A": 95, ...}. toy model: class TestGrade(models.Model): student = ForeignKey(Student) letter_grade = CharField() course = ForeignKey(Course) (assume that changing the model and doing a migration - the sensible solution - is off the table, perhaps because we want to have the flexibility to apply different mappings of letter grade to numeric score) To report these out, I get the grades for a given course using the obvious query, and then apply a case statement based on the mapping above, something like grades.annotate(score=Case(When(letter_grade="A+", then=Value(100)), When(letter_grade="A", then=Value(95)), ... default=Value(0), output_field=IntegerField))) Now, I'd like to do a GROUP BY on students and report out their average grade. Unfortunately the standard djangonic way to do a GROUP BY, grades.values("student_id").annotate(Avg('score')) dies horribly with KeyError: 'score' grades.values("student_id", "score").annotate(Avg('score')) does not die horribly, but of course it groups by the tuple of id and score, which is not what I want. Is there a way to group by student_id and annotate with the average of a synthetic β¦ -
Django true one-to-many not many-to-one
Is there a way to create a foreign key field referencing multiple objects and not the other way around. I want author referencing multiple books not multiple books referencing one author. I know I can create many-to-many field but it seems wasteful to me. -
How to set scope parameter to read_write on stripe using allauth?
I was wondering how I could provide the scope parameter set to read_write when an user subscribes through Stripe connect using Django-allauth? I'm in development mode and when I create an account and try to make a charge on another user's product I get this error : Cannot transfer to a destination that is connected with read_only scope. I've come across this in the documentation : The Stripe endpoint needs to at least receive two parameters: response_type, with a value of code. Your client_id. Youβll likely also want to provide the scope. This parameter dictates what your platform will be able to do on behalf of the connected account. The options are read_write and read_only, with read_only being the default. But I have no idea on how I could set the scope to read_write ? Anyone faced this issue ? -
When/where to use property tags of django models
I have model with a property that returns true or false if the start date is the current date. I want to update the is_started field to True if instance.started equals True. class Advert(models.Model): location = models.CharField(max_length=100) is_started = models.BooleanField(default=False) start_date = models.DateField() @property def started(self): today = str(datetime.date.today()) start_date = str(self.start_date) if today == start_date: return True return False My question now is where to I check for this condition. I don't know if check for this condition and update the is_started field in my views of check in the front end and send an api request to update if the condition id true. What's the best way to go about this? -
Django Admin Save Override TabularInline Values
I need to update the Item model's total_qty_on_hand and total_qty_on_order from the value entered into the ItemLocation tabular inline when saving the Item. My code: # models.py class Item(TimeStampedModel): ... model_fields ... total_qty_on_hand = models.PositiveSmallIntegerField(default=0, null=True, blank=True) total_qty_on_order = models.PositiveSmallIntegerField(default=0, null=True, blank=True) class Location(models.Model): location_name = models.CharField(max_length=50, null=False, blank=False) ... other model_fields ... class ItemLocation(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) location = models.ForeignKey(Location, on_delete=models.CASCADE) qty_on_hand = models.PositiveIntegerField() qty_on_order = models.PositiveIntegerField() # admin.py class ItemLocationInline(admin.TabularInline): model = ItemLocation verbose_name_plural = 'Items By Location' extra = 3 can_delete = True show_change_link = True @admin.register(Item) class ItemAdmin(admin.ModelAdmin): fieldsets = (..fields..) inlines = [ItemLocationInline, UnitPriceInLine] readonly_fields = ('id',) def get_form(self, request, obj=None, **kwargs): self.item_id = None if obj: self.item_id = obj.id return super(ItemAdmin, self).get_form(request, obj, **kwargs) def save_model(self, request, obj, form, change): totals = ItemLocation.objects.filter( item_id=self.item_id ).aggregate(total_qty_on_hand=Sum('qty_on_hand'), total_qty_on_order=Sum('qty_on_order')) obj.total_qty_on_hand = totals['total_qty_on_hand'] obj.total_qty_on_order = totals['total_qty_on_order'] obj.save() class Meta: verbose_name = 'Item' verbose_name_plural = 'Items' ordering = ('-id',) Instead of grabbing the form values from the tabular inline ItemLocation, form fields, this is calculating the ItemLocation fields qty_on_hand and qty_on_order pre-save, which results in incorrect values being saved to the Item's total_qty_on_hand and total_qty_on_order. of course, if I save the instance again, it corrects because the ItemLocation β¦ -
retrieve the model name for audit
Im building an audit app and i need to retrieve the model name. the thing is that i dont know the names of the models from the audit model is there a way to refer to a generic model and get that name? i already made a user log in/out model that saves the information in strings and i want to do something similar. @receiver(user_logged_out) def LogoutWatch(request,*args,**kwargs): Log = AuditoriaLog() Log.fecha = datetime.datetime.now() Log.usuario = request.user.usuario Log.nombre_u = str(request.user.get_full_name()) Log.cedula_u = str(request.user.usuario.cedula) Log.actividad = "Cierre de Sesion" Log.save() if i can get the model name there is a django function that stores the model in a dict, and then i can connect with the post save signal to get what i want. -
how to convert the foreign key to value
I want to query a table with foreign key. Is it possible to replace the foreign key to its value and convert it to dictionary? Model.py class Category(models.Model): name = models.CharField(max_length=40) class Item(models.Model): name = models.CharField(max_length=50) category = models.ForeignKey(Category) Views.py dic = {} dic["data"] = list(Item.objects.all().values()) -
Tango with django - populate_rango.py
I'm trying to learn Django with the help of 'Tango with django' book. But when I'm used populate_rango.py script my output didn't quite hit the mark. Then I'm run script again and the result was much more close to the example but not same. My 3rd time running script crowned with success. The question is: Why on the my 3rd try result become as expected? populate_rango.py import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'tango_with_django_project.settings') import django django.setup() from rango.models import Category, Page def populate(): python_pages = [ {"title": "Official Python Tutorial", "url": "http://docs.python.org/2/tutorial/"}, {"title": "How to Think like a Computer Scientist", "url": "http://www.greenteapress.com/thinkpython/"}, {"title": "Learn Python in 10 Minutes", "url": "http://www.korokithakis.net/tutorials/python/"}] django_pages = [ {"title": "Official Django Tutorial", "url": "https://docs.djangoproject.com/en/1.9/intro/tutorial01/"}, {"title": "Django Rocks", "url": "http://www.djangorocks.com/"}, {"title": "How to Tango with Django", "url": "http://www.tangowithdjango.com/"}] other_pages = [ {"title": "Bottle", "url": "http://bottlepy.org/docs/dev/"}, {"title": "Flask", "url": "http://flask.pocoo.org"}] cats = {"Python": {"pages": python_pages}, "Django": {"pages": django_pages}, "Other Frameworks": {"pages": other_pages}} for cat, cat_data in cats.items(): c = add_cat(cat) for p in cat_data["pages"]: add_page(c, p["title"], p["url"]) # Print out the categories we have added. for c in Category.objects.all(): for p in Page.objects.filter(category=c): print("- {0} - {1}".format(str(c), str(p))) def add_page(cat, title, url, views=0): p = Page.objects.get_or_create(category=cat, title=title)[0] p.url = url β¦ -
Django Loop .save() time issues
I have the following code and everything does what it supposed to, each loop can varies in the amount of time for it to run. I've narrowed it down to the .save() function as the query on average takes .008 seconds to run per iteration. The .save() takes anywhere from .008 seconds to 1.13 seconds. When performing 113 iterations, 1.13 seconds starts to add up. Any suggestions to speed this up? The table size is up to 45,000 lines of data. views.py for mega, company, family, bed, sretail in beds: matt = FloorTracker.objects.get(showroom_number=strNum,mattress=bed) matt.brand = company matt.family = family matt.company = mega matt.suggested_retail = sretail matt.on_floor = 0 if request.POST.get('cb_' + bed) == None else 1 matt.in_comparison = 0 if request.POST.get('cb_' + bed + '_comparison') == None else 1 matt.in_vzone = 0 if request.POST.get('cb_' + bed + '_vzone') == None else 1 matt.size = "" if request.POST.get('sz_' + bed) == 'blank' or not request.POST.get('sz_' + bed) else request.POST.get('sz_' + bed) matt.underbed = "" if request.POST.get('ub_' + bed) == 'blank' or not request.POST.get('ub_' + bed) else request.POST.get('ub_' + bed) matt.lastupdate = str(timezone.now()) t0 = time.time() matt.save() t1 = time.time() total = t1-t0 print('query 1:', matt.mattress, total) -
Boostrap BS3 navbar Clic Dropdown-Submenu
I'm using Bootstrap BS3 in order to build my Django website. I'm writing dropdown-submenu which works on http://www.bootply.com/nZaxpxfiXz# But When I applied the same thing to my project, I get : I don't have the little arrow beside dropdown-menu title. This is my script : <!DOCTYPE html> <html> <head> {% load staticfiles %} {% load user_tags %} <title> DatasystemsEC - Accueil </title> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.1.1/jquery.min.js"></script> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> <script src="base.js" type="text/javascript"></script> <meta http-equiv="Content-Type" content="text/html; charset=utf-8" /> <link rel="stylesheet" type="text/css" href="{% static 'css/Base.css' %}"/> </head> <!-- #################### --> <!-- Upper navigation bar --> <!-- #################### --> <nav class="navbar navbar-inverse"> <div class="container-fluid"> <div class="navbar-header"> <a class="navbar-brand" href="http://www.datasystems.fr/"> DatasystemsEC </a> </div> <!-- Home tab --> <ul class="nav navbar-nav"> <li><a href="{% url "accueil" %}"> <span class="glyphicon glyphicon-home"></span> Accueil </a></li> <!-- Resume Tab with acts --> {% if user.is_authenticated %} <li class="dropdown"><a href="#" class="dropdown-toggle" data-toggle="dropdown">Actes Etat Civil <b class="caret"></b></a> <ul class="dropdown-menu"> <li class="dropdown dropdown-submenu"><a href="#" class="dropdown-toggle" data-toggle="dropdown"> <span class="glyphicon glyphicon-baby-formula"></span> Fiches Individuelles </a> <ul class="dropdown-menu"> <li><a href="#">Accueil Fiches Individuelles</a></li> <li><a href="#">CrΓ©ation Fiches Individuelles</a></li> <li><a href="#">Consultation Fiches Individuelles</a></li> <li><a href="#">Edition Fiches Individuelles</a></li> <li><a href="#">Suppression Fiches Individuelles</a></li> </ul> </li> <li class="dropdown dropdown-submenu"><a href="#" class="dropdown-toggle" data-toggle="dropdown"> <span class="glyphicon glyphicon-baby-formula"></span> Actes de β¦ -
How to join tables over multiple databases/schema in django orm?
I am new to django, and I have started the process of moving an existing API to Django. The current API has multiple databases. For example, table account is in database A, table notification is in database B etc. It is a legacy database on which the app is running, and as such, I cannot change the database. For explanations sake, the structure of both are - Account Table +-----+--------------+ | id | account_name | +-----+--------------+ | 123 | John | +-----+--------------+ | 124 | Henry | +-----+--------------+ | 126 | Vlad | +-----+--------------+ Notification Table +----+------------+-----------------------------------+ | id | account_id | notification_body | +----+------------+-----------------------------------+ | 1 | 123 | Someone sent you a message | +----+------------+-----------------------------------+ | 2 | 123 | Someone commented on your photo | +----+------------+-----------------------------------+ | 3 | 126 | Someone sent you a friend request | +----+------------+-----------------------------------+ In the above tables, notification.account_id is a foreign key with relation to account.id, which is the primary key in the account table. I want to join both the tables, the equivalent of the following SQL query. SELECT * FROM A.account AS acc JOIN B.notification ON noti ON noti.account_id = acc.id Django uses foreign key to join tables using β¦ -
Sphinx fails when generating documentation for Django project
I'm trying to automatically generate documentation for my Django project using Sphinx with the autodoc and napoleon extensions. Using sphinx-quickstart I've created the following structure: MyDjangoProject βββ __init__.py βββ config β βββ __init__.py β βββ settings.py β βββ urls.py β βββ wsgi.py βββ docs β βββ Makefile β βββ build β βββ source β βββ _static β βββ _templates β βββ conf.py β βββ index.rst βββ myfirstapp β βββ __init__.py β βββ models.py β βββ views.py βββ mysecondapp β βββ __init__.py β βββ models.py β βββ views.py ... I've customized docs/source/conf.py to reflect my project structure. import os import sys proj_folder = os.path.realpath( os.path.join(os.path.dirname(__file__), '../..')) sys.path.append(proj_folder) os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'config.settings') import django django.setup() extensions = ['sphinx.ext.autodoc', 'sphinx.ext.intersphinx', 'sphinx.ext.napoleon', 'sphinx.ext.viewcode'] # The rest of the default configuration... Then I go to the root of my project and run sphinx-apidoc -f -o docs/source .. This adds a .rst file for each module to docs/source. Finally I go to MyDjangoProject and run make html. This fails with an error for each module saying Traceback (most recent call last): File "/Users/Oskar/git/MyDjangoProject/venv/lib/python2.7/site-packages/sphinx/ext/autodoc.py", line 551, in import_object __import__(self.modname) ImportError: No module named MyDjangoProject.myfirstapp What am I doing wrong? -
How to get a name of uploaded file from cleaned_data?
I have this function for file handling: def handle_uploaded_file(f, person): with open(user_directory_path(person, f.name), 'w') as destination: for chunk in f.chunks(): destination.write(chunk) And I call this function in form save method: class CreateMessageForm(forms.Form): ... def save(self): ... for file in cleaned_data.get('files'): handle_uploaded_file(file, self.person) message.files.add(file) But after sending this form I have an AttributeError: 'bytes' object has no attribute 'name'. I don't understand what's wrong. In the docs uploadedfile object has this attribute.