Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Filtering with Django-Taggit: Is it possible to filter for model entries that include all tags?
Food.objects.filter(tags__name__in=["Tag 1","Tag 2","Tag 3"]).distinct() More precisely, if I want to filter for Food(s) where Food(s) has at least all three tags (not just one or two of the three, but could have more than the three), is there a modification to the filter provided in docs that achieves this result? http://django-taggit.readthedocs.io/en/latest/api.html -
Django app not populating data from admin - Heroku
I am trying to deploy my first django app to heroku. Everything is fine, but my app is not populating data from admin. When I check admin page of app it has data, but same does not reflect on app. What could be the issue. Its been hours I m fiddling with this. -
moving items of list up and down
Let's say we have a list of items. And, we want to allow users to control their order by clicking (down-arrow) to lower the order of item one level. And, doing the same to set the order one level higher. views.py def item_up(request, item_id): item = get_object_or_404(Item, id=item_id) swap_order = item.order - 1 swap = get_object_or_404(Item, order=swap_order item.order += 1000 item.save() swap.order += 1 item.order -= 1001 swap.save() item.save() return redirect(request.META['HTTP_REFERER']) def item_down(request, item_id): item = get_object_or_404(Item, id=item_id) swap_order = item.order + 1 swap = get_object_or_404(Item, order=swap_order) item.order -= 1000 item.save() swap.order -= 1 item.order += 1001 swap.save() item.save() return redirect(request.META['HTTP_REFERER']) this way is working except when I have only two items it shows me an error. No Item matches the given query. Any Idea? -
How to display list of all staff users in a drop down method?
I want to create a field in a form for superuser. This field should have a list of all the staff users in a drop down manner so that superuser can select one of them to assign him/her a task. How should I create the drop down list? So far, I can display the users like this: from django.contrib.auth.models import User users = User.objects.all() -
Django - order by
I need to sort my objects to use it in my template. Now it is something like: sites = Site.objects.all().order_by('-date', '-group')[:10] Result is for example: today group2 today group1 yesterday group2 yesterday group1 three days ago group2 four days ago group2 I need: today group2 yesterday group2 three days ago group2 four days ago group2 today group1 yesterday group1 I simply need 10 newest sites ordered by group. I would like to use it in my template (two sites in group2 first and 8 with group 2 or 1 next). Thanks for any advice. -
Use of "flags" in django template
I want to use a flag in Django template This is my code <ul class="list-group"> {% for device in device_list %} {% if room.RoomID == device.RoomID.RoomID %} <!-- Flag ++ HERE--> <a href="{% url 'device_update' device.id %}" class="list-group-item"> {{device.Name}} <span class="glyphicon glyphicon-pencil pull-right"> </span> </a> {% endif %} {% endfor %} </ul> So after this for loop i will check if the flag is 0, do something ( the flag only increments if the IF Statement is true at least once ) Any suggestions ? -
linking updateview form with template form in django
I want to have CreateView and UpdateView form on the same page but update form is displayed only when edit button is pressed which is also on the same page but the problem is when edit button is pressed it is redirected to update view(ie same page) if the URL of updateView is linked to the button and if I don't link the updateView to the button then the form is not auto-filed to be update. what is its solution? class stock_add_view(CreateView): model = part_stock fields = ['part_id','entry_date','supplier','amount','remaining'] success_url = reverse_lazy('parts:part_list') class stock_update_view(UpdateView): model = part_stock fields = ['part_id','entry_date','supplier','amount','remaining'] success_url = reverse_lazy('parts:part_list') template_name = 'part_detail.html' URL pattern url(r'^add_stock$',views.stock_add_view.as_view(),name='stock_add_view'), url(r'^update_stock/(?P<pk>\d+)/$',views.stock_update_view.as_view(),name='stock_update_view'), Template: part_detail.html <script type="text/javascript"> $(function () { $('.edit_btn').on('click',pop_up); function pop_up() { alert("hi") $('#update_form').show(); } }) </script> <div>//add form <form method="post" action="{% url 'parts:stock_add_view'%}"> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form> </div> <div style="display: none;" id="update_form">//update form <form method="post" action="{% url 'parts:stock_update_view' stock.id%}"> {% csrf_token %} {{ form.as_p }} <input type="submit"> </form> </div> //edit button <a href=""> <button type="button" class="edit_btn" data-id="{{ stock.id }}">Edit</button></a> -
Is there any way to simulate django collectstatic command during development?
I'm working on React App and after that I want to make a bundle.js file and place it in assets/bundles/ folder. I'm using django-webpack-loader Here's my settings.py file: INSTALLED_APPS = ( ... 'webpack_loader', ) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATICFILES_DIRS = ( os.path.join(BASE_DIR, 'assets'), ) STATIC_URL = '/media/static/' WEBPACK_LOADER = { 'DEFAULT': { 'BUNDLE_DIR_NAME': 'bundles/', 'STATS_FILE': os.path.join(BASE_DIR, 'webpack-stats.json'), } } Here's my template.html: <div id="container"></div> {% load render_bundle from webpack_loader %} {% render_bundle 'main' %} The error I get is: GET example.com/media/static/bundles/bundle.js 404 (Not Found) If I run python manage.py collectstatic It will move bundle.js from assets/bundles/ to media/static/bundles. But I don't want to run it every time I'm changing my bundle. In the django-webpack-loader documentation collectstatic command is not run but the bundle.js still can be accessed as though it's in static folder. But actually it's located in assets. -
Django commits to database before transaction ends
I am using Django 1.10 with Postgres database and django-rest-framework. I debug my code and wherever I have some_entity.save(), I immediately see the changes in database. The thing is that I have ATOMIC_REQUESTS = True and this would mean that nothing gets committed to the database until view successfully finishes. I am worried about the database integrity now- if later an exception occurs, nothing gets rolled back -
MIDDLEWARE_CLASSES is not set
(1_7.W001) MIDDLEWARE_CLASSES is not set. HINT: Django 1.7 changed the global defaults for the MIDDLEWARE_CLASSES. django.contrib.sessions.middleware.SessionMiddleware, django.contrib.auth.middleware.AuthenticationMiddleware, and django.contrib.messages.middleware.MessageMiddleware were removed from the defaults. If your project needs these middleware then you should configure this setting. got this error when run in the terminal -
How to exclude unrelated search results from django-haystack and Elasticsearch?
I'm trying to search for products based on their keywords. My haystack index looks like the below: class ProductIndex(indexes.SearchIndex, indexes.Indexable): name= indexes.CharField(model_attr='name') text = indexes.CharField(document=True) # contains keywords associated with the product In this case, the field "text" contains a group of keywords associated with the product. For instance, here is a sample product index: name: "Tide Detergent" text: "laundry household shopping cleaning supplies" When I search for laundry, Tide Detergent appears on the search, but so do other irrelevant results, such as products that have lawn or laugh in the text. So it looks like elasticsearch is searching not just for laundry but variations of the word also. Here is what my search query looks like: qs = SearchQuerySet().models(Product).filter(content__exact='laundry') My question is: how can I force haystack or elasticsearch to search strictly for my input keyword and ignore variations of them? In other words, how can ensure that haystack searches for only laundry and exclude any other terms? -
Django in subdirectory - admin site is not working
I have deployed my Django project on subdirectory on server (dns_name_of_my_page/notes). My app in this project is accessible via dns_name_of_my_page/notes/app/. Unfortunately admin site is not working if whole Django project is in subdirectory 'notes' in public_html on hosting server. When I enter to admin site (dns_name_of_my_page/notes/admin/) there is redirect to URL without the name of the subdirectory (dns_name_of_my_page/adminlogin/?next=//admin/), which is not acceptable. It should be rather dns_name_of_my_page/notes/adminlogin/?next=/notes/admin/ Here is my configuration of URLs in project: urlpatterns = [ url(r'^/?app/?', include('app.urls')), url(r'^/?$', views.index, name='index'), url(r'^/?admin/?', admin.site.urls), ] Here is my configuration of URLs in my app: urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^(?P<num>[0-9]+)/?', views.num, name='num'), ] I have tried to set FORCE_SCRIPT_NAME = '/notes/' or SUB_SITE = "/notes/" in settings.py but it did't help me. Have you ever had this kind of problem with running Django app in subdirectory ? -
Deploying on Heroku dockerized Angular 4, Django and postgresql - Process exited with status 127, error code=H10 desc="App crashed"
I am trying to deploy on Heroku my project in Docker with Angular 4 frontend, Django backend and postgresql database. At this moment my files look as shown below. I am note sure if this is done properly? I pushed it using heroku container:push web --app myproject but it doesn't work (Logs). I noticed that in logs there is Process exited with status 127. I have found here 127 Return code from $? that Value 127 is returned by /bin/sh when the given command is not found within your PATH system variable and it is not a built-in shell command. In other words, the system doesn't understand your command, because it doesn't know where to find the binary you're trying to call. Besides, when I was trying different commands I very often were getting error like /bin/sh: 1 not found what I described in this post. To sum up, it seems to me that it may be root of the problem. Any suggestions how can I solve it? Logs: 2017-07-08T13:19:48.882112+00:00 heroku[web.1]: Process exited with status 0 2017-07-08T13:20:40.336825+00:00 heroku[run.9745]: Awaiting client 2017-07-08T13:20:40.395900+00:00 heroku[run.9745]: Starting process with command `docker-compose up` 2017-07-08T13:20:40.542168+00:00 heroku[run.9745]: State changed from starting to up 2017-07-08T13:20:45.727667+00:00 heroku[run.9745]: State changed … -
no ReverseMatch exception url
I have to url's on my Inspiration tab with two views. My first url is without an addition parameter in regex and my second is with an additional parameter. When I go to the one with the additional parameter everything is fine but when I go to the first one with no additional parameter I got a no reversematch exception. I think it's something with my url. Can somebody help me out? -
displaying other form inside DetailView in django
I have the detail view of "part" in views.py class part_detail_view(DetailView): model = part_list context_object_name = 'part_detail' template_name = 'part_detail.html' def get_context_data(self, **kwargs): context = super(part_detail_view, self).get_context_data(**kwargs) context['my_list'] = populate_nav_bar() return context but inside this URL I also want to display another form "CreateView" of the stock model so that from the same page I can display the form to add stock of the part and add the stock. This was done easily in function based view but I am not sure how to do this in class based view. -
Getting error while using parameterised like query in Python
I am getting the following error while trying to use like query for sqlite3 db using python. Error: Request Method: POST Request URL: http://127.0.0.1:8000/search/ Django Version: 1.11.2 Exception Type: ProgrammingError Exception Value:Incorrect number of bindings supplied. The current statement uses 1, and there are 3 supplied. I am explaining my query below. rname = request.POST.get('rname') keyword = '%' + rname + '%' cursor.execute("SELECT * FROM booking_meeting WHERE room_name LIKE ? ",(keyword)) Here I need to fetch value from table as per keyword. Please help me to resolve this error. -
Image not displayed from static
I am using a csv file to display an image on my django template. The csv file is like id| Name | image 1 | wine1 | images\download1.jpg i have kept the image in the static file my wine_list.html is as {% for wine in wine_list %} <div> <h4><a href="{% url 'reviews:wine_detail' wine.id %}"> {{ wine.name}}</a><br> {% if wine.description != "nan" %} <h4>{{ wine.description }}</h4> {% else %} <h1> No Description available {% endif %} <h3>'{{ wine.images.url }}'</h3> <br> <a> <img src="{% static '{{ wine.images.url }}' %}" height="200"></a> the name and description shows fine, and the wine.images.url prints images/download.jpg shouldn't the image be printed ? my image folder is in my static, when i print it like this <a> <img src="{% static 'images/download.jpg' %}" height="200"></a> it does display the image. -
Could not get json value while fetching all data from table using python
I am facing one problem. I need to display the db table data in a tabular format but I could not find the data in JSON format using python. I am explaining my code below. def view_book(request): """ This function is used for disply all the data """ conn = sqlite3.connect("db.sqlite3") cursor = conn.cursor() cursor.execute("SELECT * FROM booking_meeting ORDER BY id desc") all_value = cursor.fetchall() root = [] json_output=json.dumps(all_value) print(json_output) for book in json_output: root.append( {'lname': book.location_name, 'roomname': book.room_name, 'seat': book.no_seat, 'project': book.projector, 'video': book.video, 'from_date': book.from_date, 'to_date': book.to_date}) return render(request, 'booking/view_book.html', {'people': root}) Here I am getting the following error. Error: Request Method: GET Request URL: http://127.0.0.1:8000/view_book/ Django Version: 1.11.2 Exception Type: AttributeError Exception Value: 'str' object has no attribute 'location_name' Here I need to append all data into JSON format so that i will be able to display it in table.Please help me. -
What does "poll" in django mean?
In Django doc it is said Creation of a basic poll application will consist of two parts: A public site that lets people view polls and vote in them. An admin site that lets you add, change, and delete polls. I couldn't find any clear description of a poll. So what does it mean? -
502 Bad Gateway django error
I have a big problem with my project and I am searching for o solution.Hope that you are gonna help me somehow!The idea is , that I have made a droplet at Digital-Ocean for my Django app.The virtual machine is Ubuntu 14.4 and I've downloaded also Putty & Winscp. When I open Putty and try to go on the link ( http://138.68.18.142/ ) it gives me a Bad Gateway 502 error."nginx/1.4.6 Ubuntu".What should I do? I have also edited some files in Winscp , after watching a tutorial on youtube.I guess that edit I've made on Winscp , caused this error , but I don't know how to solve it.Please help me guys, I would appreciate so much!Thanks. Have a nice day! -
Cost of making an Instagram like application
I wish to make a small app like Instagram. The application usually provide the capability to comment on user posts and like them. Suppose here is the traffic on my website as follows: 1. 500 users per day 2. 10 post per day Think of it as an small application that may go viral. I wish to know about following queries. I am a django python lover. It is fine to make android application using python. I wish to know about celery queue. How will it cost me for this traffic on the app. How much servers do I need to have. Image processing enables to edit image just like ms paint. So, do how can I do that. What client libraries do I need to use for this app. I need to minimise the entire cost of application. So how much it can cost me. I wish if I do this by not spending 1 thousand per month. Is it possible?. What should I need to keep in mind if the website goes viral?. If I add these two major changes. Few machine algorithms that sense the users likes, comment on post. Few image processing algorithm Though, it totally … -
Django (v1.11.3) UnorderedObjectListWarning even though list is ordered
I keep running into Django's UnorderedObjectListWarning when trying to display model instances in a paginated view for search results. However, there is a default ordering defined in the models.py file: class Rfc(models.Model): class Meta: verbose_name='RFC' verbose_name_plural='RFCs' ordering=['number'] The actual search happens in views.py and is defined as follows: # parse GET parameters search_term = request.GET.get('q', '') category = request.GET.get('c', 'cs') page = request.GET.get('p', 1) ... results_rfc = Rfc.objects.filter( Q(title__icontains=search_term) | Q(number__icontains=search_term) ) if category=='cs': active_tab = 'cs' results = results_cs else: active_tab = 'rfc' results = results_rfc paginator = Paginator(results, 15) However, I cannot seem to make it work, even when explicitly telling Django to order_by('number') in the filter function above. The result is always: UnorderedObjectListWarning: Pagination may yield inconsistent results with an unordered object_list: <class 'directory.models.Rfc'> QuerySet. paginator = Paginator(results, 15) What baffles me even more is that this warning is not displayed when executing above code in manage.py shell. Clearly, I am missing something here. Any ideas? -
django {% if user.groups == 'FC' %} doens't work
I'm making a website using django. {% if user.groups == 'FC' %} doesn't work in my template.I have groups like that. For example, one of my users(username is 'hong) belongs to 'FC' group as you see below. But, {% if user.groups == 'FC' %} <li><a href="{% url 'register' %}">register form</a></li> <li><a href="{% url 'mypage' %}">fc's my page</a></li> {% else %} <li><a href="{% url 'PT_mypage' %}">fitness' my page</a></li> {% endif %} if user.groups == ' ' doesn't work. How I check the users' group? I have to distinguish the users by groups. Any help will be helpful to me, thanks! -
Last seen a user in django
How can i show the time of last seen(be online)of user in django? Is there any default function or library to import it to do that? Or if there any code inn github tell me please **Note : ** when a user close page or disconnect the time update -
Django - IntegrityError: NOT NULL constraint failed:
I am trying to add ContactNumber to my model. The migration worked However, why am I getting this error while trying to createsuperuser. Could anybody please explain. My model: class MyUser(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), max_length=254, unique=True) contact_number = models.IntegerField(_('contact number'), validators=RegexValidator(r'^\+?1?\d{9,10}$'), unique=True, null=True, blank=True) .... The traceback: Traceback (most recent call last): File "manage.py", line 22, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/management/__init__.py", line 363, in execute_from_command_line utility.execute() File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/management/__init__.py", line 355, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/management/base.py", line 283, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/contrib/auth/management/commands/createsuperuser.py", line 63, in execute return super(Command, self).execute(*args, **options) File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/core/management/base.py", line 330, in execute output = self.handle(*args, **options) File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/contrib/auth/management/commands/createsuperuser.py", line 183, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) File "/home/surajit/website/PubNet/user_profile/manager.py", line 31, in create_superuser **extra_fields) File "/home/surajit/website/PubNet/user_profile/manager.py", line 22, in _create_user user.save(using=self._db) File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/contrib/auth/base_user.py", line 80, in save super(AbstractBaseUser, self).save(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/base.py", line 806, in save force_update=force_update, update_fields=update_fields) File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/base.py", line 836, in save_base updated = self._save_table(raw, cls, force_insert, force_update, using, update_fields) File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/base.py", line 922, in _save_table result = self._do_insert(cls._base_manager, using, fields, update_pk, raw) File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/base.py", line 961, in _do_insert using=using, raw=raw) File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/manager.py", line 85, in manager_method return getattr(self.get_queryset(), name)(*args, **kwargs) File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/query.py", line 1060, in _insert return query.get_compiler(using=using).execute_sql(return_id) File "/usr/local/lib/python2.7/dist-packages/Django-1.11-py2.7.egg/django/db/models/sql/compiler.py", line 1099, in execute_sql …