Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Channels 2.0: call consumer via ChannelNameRouter from view
I am trying to upgrade my code from django-channels 1.1.8 to 2.0.0 So, I just want to perform a very simple async background task, and can not figure out why it does not print anything: routing.py from channels.routing import ProtocolTypeRouter, ChannelNameRouter from tasks.consumers import LongTask application = ProtocolTypeRouter({ 'channel': ChannelNameRouter({ 'long-task': LongTask }), }) consumers.py from channels.consumer import SyncConsumer class LongTask(SyncConsumer): def long_task(self, message): print(message) views.py def perform_long_task(request): channel_layer.send('long-task', { 'type': "long.task", 'text': 'Hey!' }) I guess something wrong here channel_layer.send('long-task', {...}) Big thx -
python ,django how to add paginator in python
Total No. of Transaction for the Current Month New User</th>--> Date User Vehicle Type Vehicle No Pump Company Pump Name Pump City Pump State Fuel Type Fuel Price Fuel Liters Total Amount Fuel Bill </tr> </thead> <tbody> {% for items in mmf_total_trans_today %} <tr> <!--<td width="20%">{{items.mmf_new_user}}</td>--> <td width="20%">{{items.date_updated}}</td> <td width="20%">{{items.user}}</td> <td width="20%">{{items.vehicle.vehicle_category}}</td> <td width="20%">{{items.registration_certificate}}</td> <td width="20%">{{items.company_ro}}</td> <td width="20%">{{items.fuel_station}}</td> <td width="20%">{{items.pump.city}}</td> <td width="20%">{{items.pump.indianstate}}</td> <td width="20%">{{items.fuel_type}}</td> <td width="20%">{{items.fuel_price}}</td> <td width="20%">{{items.fuel_total_litres}}</td> <td width="20%">{{items.fuel_total_price}}</td> <td width="20%">{{items.fuel_bill_upload}}</td> </tr> {% endfor %} <div class="pagination"> <span class="step-links"> {% if users.has_previous %} <a href="?page={{ users.previous_page_number }}">previous</a> {% endif %} <!-- Showing the page numbers in Html Page --> <span class="current"> Page {{ users.number }} of {{ users.paginator.num_pages }}. </span> {% if users.has_next %} <a href="?page={{ users.next_page_number }}">next</a> {% endif %} </span> </div> </tbody> </table> </div> in Models i have added paginator = Paginator(mmf_total_trans_today, 10) -
Fetching Data from multiple table in django
how i perform join query.. i want to fire query which act like.. "select s.nm,s1.sub from Student s,Subject s1"; here i show what i tried in django but doesn't work my model.py file is from django.db import models class Student(models.Model): sid = models.BigIntegerField(primary_key=True) nm = models.CharField(max_length=20, blank=True, null=True) id = models.ForeignKey('Subject', models.DO_NOTHING, db_column='id', blank=True, null=True) class Meta: managed = False db_table = 'student' class Subject(models.Model): id = models.IntegerField(primary_key=True) # AutoField? sub = models.CharField(max_length=30, blank=True, null=True) class Meta: managed = False db_table = 'subject' view.py from django.http.response import HttpResponse from django.core import serializers from App.models import Student, Subject # Create your views here. def fun(request): # obj1=Subject.objects.all() obj=Student.objects.filter(Subject.objects.all()).all() js=serializers.serialize("json",obj) return HttpResponse(js) but it doesn't solution.. please help me as soon as possible... fdhgjdfhjchnb ]ghnfghnghnghngf dhg hnfghnfghngfh hgfhhnldhnglhnklhn hkndhfgk fhknkghnkfgjh hnflkkhnhnhngfh hgfnh.gnjnml;fxmgnx; -
Django ORM get respective choices value instead of field value
In Django ORM, is there any way that you can directly get the respective choices value instead of the field value in the resulting Queryset. Example: port = models.CharField( max_length=5, choices=( ('21', 'FTP'), ('22', 'SSH'), (...), .. ) ) After the ORM Querying, I need the port name (not the number) in the Queryset itself. > myModel.objects.filter(...).values() > [{"id": 1, "port": "FTP"}, {"id": 2, "port": "SSH"}, {...}, ...] -
How to override (filter based on particular condition) Django admin filter choices?
My models Django are: class Brand(models.Model): name = models.CharField(max_length=200) class StanardProduct(models.Model): brand = models.ForeignKey(Brand) class VendorProduct(models.Model): standard_product = models.ForeignKey(StanardProduct) My model admin is: class StandardProductModelAdmin(admin.ModelAdmin): list_filter [ 'brand' ] In the list filter for 'brand', I want to show only those brand choices that satisfy following two conditions: Brand name choice should be referenced by StandardProduct object StandardProduct object should be referenced by VendorProduct object Using "admin.RelatedOnlyFieldListFilter" in the filter satisfies only condition no. 1 - but not no. 2. I need a way that satisfies both the conditions. -
{% empty %} does not work in django template
if works correctly but empty does not work, here is my code: {% for answer in ans|slice:":3" %} {% for course in crs %} {% if answer.course_id == course.id %} <h4 class="w3-text-blue">{{answer.course}}</h4> {% endif %} {% empty %} <h1>empty</h1> {% endfor %} {% endfor %} -
Creating a notification inbox similar to StackOverflow's using django-notifications-hq
I'm able to get to a point where the notifications will appear in the dropdown, but I'm losing hair trying to figure out an efficient way to make each individual notification a hyperlink to anywhere else in the site. I'm attempting to implement the live-updater on django-notifications-hq. Following along with their example and method of filling in the notification list, I've come to the conclusion that I need to configure the notify.js file. I figure that I should anchor a hyperlink to the notifications. So here is a very minimal example of a configured return statement in the notify.js file that will allow each notification to return a hyperlink: ... return '<li><a href="/">' + message + '</a></li>'; }).join('') In an attempt to make this more dynamic so that each notification leads to its appropriate page, I thought maybe I can implement context processors to fill each page with notification data-- context_processors.py: def notifications_unread(request): try: profile = Profile.objects.get(user__username=request.user) return {'unread': profile.user.notifications.unread()} except Profile.DoesNotExist: return {} And to use these variables in the JS file, I'd first run them through Django templates, and then make them available as global variables like so-- landing/notifications.html: <script type="text/javascript"> var currentUser = '{{request.user}}'; var notifications = … -
Error psycopg2 in Django
I installed psycopg2 == 2.7.3.2 and PostgreSQL 10.1 When I run djnago, I get an error, but I do not know how to fix it. I ask for help, comrades. Failed to get real commands on module "gattaca": python process died with code 1: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/postgresql/base.py", line 21, in <module> import psycopg2 as Database File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psycopg2/__init__.py", line 50, in <module> from psycopg2._psycopg import ( # noqa ImportError: dlopen(/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psycopg2/_psycopg.cpython-35m-darwin.so, 2): Symbol not found: _PQbackendPID Referenced from: /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psycopg2/_psycopg.cpython-35m-darwin.so Expected in: flat namespace in /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/psycopg2/_psycopg.cpython-35m-darwin.so During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/Applications/PyCharm.app/Contents/helpers/pycharm/_jb_manage_tasks_provider.py", line 25, in <module> django.setup() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/__init__.py", line 27, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/registry.py", line 108, in populate app_config.import_models() File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/apps/config.py", line 202, in import_models self.models_module = import_module(models_module_name) File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/importlib/__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 986, in _gcd_import File "<frozen importlib._bootstrap>", line 969, in _find_and_load File "<frozen importlib._bootstrap>", line 958, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 673, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 665, in exec_module File "<frozen importlib._bootstrap>", line 222, in _call_with_frames_removed File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/auth/models.py", line 4, in <module> from django.contrib.auth.base_user import AbstractBaseUser, BaseUserManager File "/Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/contrib/auth/base_user.py", line 52, in <module> … -
How to access form data in `FormView.get_success_url()`
Currently, I have a form that looks like this: class SelectBoard(generic.FormView): form_class = forms.SelectBoard def form_valid(self, form): board_name = form.cleaned_data['name'] return redirect('leaderboard', board_name=board_name) However, it would be my preference to do the more idiomatic thing, and use get_success_url. Something like this: class SelectBoard(generic.FormView): form_class = forms.SelectBoard def get_success_url(self): form = ??? board_name = form.cleaned_data['name'] return reverse('leaderboard', board_name=board_name) However, the form is not passed to get_success_url, and unlike many other pieces of request context (like self.request, self.kwargs, or self.object (in DetailView)), the form is not attached as an attribute at any point in the standard FormView dispatch sequence. Is there any good way to access cleaned & validated form data in get_success_url (that is, without having to access self.request.POST or reconstruct the form from scratch)? -
save() prohibited to prevent data loss due to unsaved related object 'team'
When I create new team and trying to associate it to my User's Profile, I get this error is showing. I wanted a team that lot of members and only one creator(or admin of the team) and that creator is also member of the group. How can I associate team with User's Profile? Models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) steam_id = models.IntegerField(unique=True, null=True) steam_name = models.CharField(max_length=255, null=True, unique=True) profile_pic = models.ImageField(upload_to='profile_images', default='profile_images/default_user.png', blank=True) rank = models.IntegerField(default=1) matches = models.IntegerField(default=0) kda = models.IntegerField(default=0) team = models.ForeignKey(Team, related_name='players', on_delete=models.CASCADE, null=True) class Team(models.Model): creator = models.ForeignKey(User, related_name='teams', on_delete=models.CASCADE) name = models.CharField(max_length=20, unique=True) rank = models.IntegerField(default=0) Views.py class TeamsCreateView(generic.CreateView): model = Team form_class = TeamCreationForm def form_valid(self, form): form.instance.creator = self.request.user self.request.user.profile.team = form.instance print(form.instance) print(self.request.user.profile.team) self.request.user.profile.save() return super().form_valid(form) -
Pagination on scroll don't work after AJAX update?
I use pagination on scroll of django-el-pagination app in my project. I show list of documents to user. Every such document has edit button. When user click to edit button he can see edit form. After successful editing I update list by AJAX. Problem is that after AJAX update the list pagination don't work anymore. In browser console I notice this error: TypeError: fragment.trim is not a function | el-pagination.js:72:50 It seems to me that I need to update/refresh pagination script in crud.js file. I put activatePagination function inside crud.js file but it didn't help me. Can you help me to fix this problem? main_template.html: <div id="documents" class="dd"> <ol class="dd-list"> {% include page_template %} </ol> </div> {% block script %} {# START: AJAX request to endless pagination #} <script type="text/javascript"> function activatePagination(){ $.endlessPaginate({ paginateOnScroll: true, onCompleted: function(context, fragment) { activateTooltip(); } }); } activatePagination(); </script> {# END: AJAX request to endless pagination #} <script src="{% static 'js/documents/crud.js'%}"></script> {# CRUD JS #} {% endblock %} crud.js: $(function () { $("#document-modal").on("submit", ".document-edit-form", function(e) {e.preventDefault(); saveForm.call(this, "Data successfully updated");}); var saveForm = function(success_message) { var form = $(this); var formData = new FormData(form[0]); $.ajax({ url: form.attr("action"), data: formData, type: form.attr("method"), dataType: 'json', success: … -
save django many to many relationship with through to database
I am new to django. I have a model named Person. I want to have a many to many relationship called interests. Each person has interests, interest is what I am going to implement. Each person has two types of interest: main interest and normal interest. Here is what I have: class Person(models.Model): person = models.ForeignKey(Profile, on_delete=models.CASCADE, verbose_name=_("person ")) interest = models.ManyToManyField( InterestList, through='interestRelation', through_fields=('person', 'interest'), ) class InterestList(models.Model): class Meta: verbose_name = _("interest list") title = models.CharField(_('interest list'), max_length=30) class interestRelation(models.Model): class Meta: verbose_name = _("interests' relation") is_main = models.BooleanField(_('is main'), default=False) person = models.ForeignKey(Person, on_delete=models.CASCADE) interest = models.ForeignKey(InterestList, on_delete=models.CASCADE) InterestList class has a fixed number of predefined interests, about 15. My problem is in serilizer. I want to have a serilizer which get the json as: ['main_interests':[a,b,c,d], 'normal_interests': [e,f,g]] my serilizer is going to have these two fileds: class InterestActionSerializer(serializers.Serializer): main_interests = serializers.JSONField() normal_interests = serializers.JSONField() def take_action(self, terminal): // what is my issue how can I save these items to database and setting the is_main flag True when needed? -
Django custom user model with hbase
I m pretty new to Django. I m using Hbase as my backend, I want to create the basic user functionality and more provided by django, I m not able to find anything relevant to my problem. any guidance would be appreciated. Thanks. -
Static language to render images in loop - Upload through Django admin
I uploaded images with admin, but cannot render them in the template. What am I missing? Settings.py STATIC_URL = '/static/' STATIC_DIRS = { os.path.join(BASE_DIR, "static"), } MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') Models.py class Function(models.Model): name = models.CharField(max_length=50) fimage = models.ImageField(upload_to="images") def __unicode__(self): return "name{},id{}".format(self.name, self.id) HTML {% for function in functions %} <a href="function_page/{{function.id}}"> <img id=function_menu_pic src="{{MEDIA_URL}}{{function.fimage.url}}"></a> {% endfor %} Views.py def main(request): context = { "functions": Function.objects.all() } return render (request, 'project/main.html', context) Urls.py ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) When I upload the files they are going to a media file that is at the same level as manage.py. I'm not sure how the routing works from there. I'm getting this message for all the images: Not Found: /media/images/lpo.png [02/Feb/2018 09:54:01] "GET /media/images/1_ssOAG27.png HTTP/1.1" 404 2748 -
Django field name starting with a number
I'm wondering if it's possible to name a field starting with a number: class Stock(models.Model): ... 24h_volume = models.PositiveIntegerField() -
Update Django template without page refresh
I have Django code like this and i am getting connected device details dynamically and i am updating in template, I am getting what i want but i want refresh everytime to know whether any new devices or connected or not Here is My code class UserDashBoard(LoginRequiredMixin, TemplateView): def get_context_data(self, **kwargs): context = super(UserDashBoard, self).get_context_data(**kwargs) context['total_devices'] = get_device_mac_details(cmd='iw dev wlan0 station dump |grep Station |wc -l') return context Here is my template looks like <table class="table"> <tr> <th class="text-left">MAC Id</th> </tr> {% for device in total_devices %} <tr> <td class="text-left">{{ device }}</td> </tr> {% endfor %} </table> How can i get details without refreshing page -
Phantom Postman in Django App
I've encountered a strange problem in my django site-- the django-postman app is present but can't be edited nor deleted. I need to tweak the views but none of the changes work. I've even deleted the entire URLs and views and the postman app works fine. I thought there might be a duplicate directory that has all these files, but thats not it. What else could be the issue here? And what is a solution? -
Is pyenv or virtualenv enssential for Django?
For the first time, I made an environment for Django with virtualbox and vagrant (CentOS 7). But every tutorial I saw says I need to use pyenv or virtualenv. I think they are used to make a virtual environment for Django. But I don't know why I need to use pyenv or virtualenv. (For example, Cakephp3 doesn't need packages like pyenv or virtualenv.) And I was using virtualbox and vagrant, which are already virtual environment, so I think I was making virtual environment inside another virtual environment. I am not sure if this is meaningful. Maybe pyenv and virtualenv are not necessary if I am using virtual environment like virtualbox or vmware? Are they essential for Django? When I deploy Django in actual server, do I still need to use pyenv or virtualenv? -
Nginx default page showing. Cannot get app to display
first time Nginx user. Trying to connect Nginx to Gunicorn running a django app. The app is not actually written yet so once everything is configured, it would just display an under construction page. I can't seem to get the Nginx configuration correct to pass requests on to Gunicorn then to Django. Instead it always shows the Nginx default page. Greatly appreciate any help! Here is /etc/nginx/sites-available/: server { listen 80; #server_name <server IP>; server_name <mysite.com>; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/<my user acct>/<my app>/<my site>; } location / { include proxy_params; proxy_pass http://unix:/home/<my user acct>/<my app>/<my site>/<my site>.sock; } } Here is /etc/nginx/sites-available/default: ## # You should look at the following URL's in order to grasp a solid understanding # of Nginx configuration files in order to fully unleash the power of Nginx. # http://wiki.nginx.org/Pitfalls # http://wiki.nginx.org/QuickStart # http://wiki.nginx.org/Configuration # # Generally, you will want to move this file somewhere, and start with a clean # file but keep this around for reference. Or just disable in sites-enabled. # # Please see /usr/share/doc/nginx-doc/examples/ for more detailed examples. ## # Default server configuration # server { listen 80 default_server; listen [::]:80 default_server; … -
Django test setup not being used
I am using Django cookiecutter 1.11 for a project. Trying to write some basic tests for a model. But the setup method is not being used in the test cases. from django.test import TestCase from myapp.users.models import User from ..models import Book class ModelTests(TestCase): def setup(self): self.username = 'john' self.password = '123' self.user = User.objects.create(name=self.username, password=self.password ) def test_create_book(self): Book.objects.create(artist=self.user, title=“An Art Book“, category=“Art”, ) self.assertEquals(Book.objects.all().count(), 1) I get this error message after running manage.py test Book.objects.create(artist=self.user, AttributeError: 'ModelTests' object has no attribute 'user' But it works when I put the lines from setup into the test case. Did I miss something? -
Django Form Handling Recommendations?
Let's say I have models like question and answers, created forms for question(ModelForm) and answers(BaseInlineFormSet) doubt 1 now I want to create the view that displays question and answers forms with prev and next option, so users, admin can use next to add a new question and related answers, recommended approach? doubt 2 Is it possible to embed Question(ModelForm) and Answer(BaseInlineFormSet) into single formset? -
Json Fields search with django unexpected behavior
Hi guys Im seeing a behavior than i don't understand in django postgres json search. Im Using django 1.11 and django orm with psycopg2 driver. It goes as follows: The json in the model field looks like this. {"2018": [1, 2, 3]} If I use this query: models.mymodel.objects.filter(jsonfield__2018__contains=1) Out[97]: <QuerySet []> So as you can see i get an empty query. Then I tried to do this just for testing purposes. New Json: [ {"2018": [1, 2, 3]}] New Query: models.mymodel.objects.filter(jsonfield__0__2018__contains=1) Out[98]: <QuerySet []> It still gives me no response. Then I finally tried this. New Json: [ {"2018_1": [1, 2, 3]}] New Query: models.mymodel.objects.filter(jsonfield__0__2018_1__contains=1) Out[100]: <QuerySet [<MyModel: MyModel object>]> This one responds and I cannot wrap my head around it. Does anyone know why is this? -
Lost my app.sock file while setting up my Django server on Digital Ocean
In the mix of renaming files/moving files/directories between my server and my Bitbucket repo, the app.sock file was removed. How do I get it back? I was following this tutorial whilst setting up my server. Previously the server comprised of env (virtual environment), static, draft (my app), draft1.sock and manage.py - now it's the same but draft1 is renamed to olddraft and the sock file is gone. So how do I retain the sock file? -
Heroku cannot detect default language(python-3.6.4) even runtime.txt exists
I try to upload app and run on heroku source files are below. https://github.com/utahub/django_attend-managing-app/tree/heroku_check with command git push heroku heroku_check:master but even thought runtime.txt exists in Root Dir, Heroku does not detect defauld language. remote: Compressing source files... done. remote: Building source: remote: remote: ! No default language could be detected for this app. remote: HINT: This occurs when Heroku cannot detect the buildpack to use for this application automatically. remote: See https://devcenter.heroku.com/articles/buildpacks remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to uta-attend-managing-app. remote: I stacked with this problem for 2 days. Please tell me why this is happened. Thankyou in advance. -
Heroku H12 errors with Django
I have a Djano 1.8 application running on 6 Heroku dynos. Every once in a while, a request that is normally very fast (200ms) comes in and hits the Heroku router 30 second timeout. Then that dyno times out other follow-on requests, sometimes taking 25 minutes to stabilize and go back to serving requests without timing out. I'm using gunicorn with default web_concurrency (2 workers per dyno). I read Heroku's article on timeout behavior here, and am considering adding something like --timeout 20 to my gunicorn startup in the Procfile. That seems to be what they are recommending. Do you think that will solve the problem? From looking at the gunicorn documentation on the timeout setting it says: Workers silent for more than this many seconds are killed and restarted. But my workers aren't silent are they? They are trying to process requests but are hung and unable to for some reason. Do I understand that correctly?