Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Images gallery for Django
I'm new in Django world. I would like to create an image field in a model in wich if I want to add an image on a post(for example an header image) it's shown to me the list of image already used for other posts. If the image is not present already I can upload it. I think to a system like Wordpress media gallery. It's possible to create a similar system? Link for the study are appreciated. -
How to make type=“number” to positive numbers only using ember js
It was only preventing negative numbers from being entered from up/down arrows, whereas user can type negative number from keyboard. <div class="col-sm-2"> <label>Quantity</label><br> {{input type="number" value=quantity min="0" class="form-control- invoice"}} </div> -
Filter by user is not staff using Q in another model queryset
I have the following model: class APC(models.Model): user = models.ForeignKey(settings.AUTH_USER_MODEL, blank=True, null=True, related_name='apc', on_delete=models.SET_NULL) type= models.CharField(choices=TYPE_CHOICES, max_length=5, blank=True, null=True) I want to get APC objects that have one of two specific types, and user is not staff. I'm starting with: apcs = APC.objects.filter( ~Q(user is staff), Q(type=TYPE_CHOICES_A) | Q(type=TYPE_CHOICES_B) ) -
Django ORM select, concat, extract from data and order by
I'm having trouble performing a simple transformation with the django orm. Desired outcome should look like this: 2018-08 2018-07 2018-06 ... And is created with this sql: select distinct strftime('%Y',a."Buchung") || "-" || strftime('%m',a."Buchung") as YearMonth from hhdata_transaktion a order by 1 desc I need it for a ModelChoiceField as queryset, so I'm bound to the ORM here? My try from django.db.models.functions import TruncMonth, TruncYear Transaktion.objects .annotate(year=TruncYear('Buchung'), month=TruncMonth('Buchung')) .distinct() .order_by('-year', '-month') .values('year','month') returns: <QuerySet [{'year': datetime.date(2018, 1, 1), 'month': datetime.date(2018, 8, 1)}, {'year': datetime.date(2018, 1, 1), 'month': datetime.date(2018, 7, 1)}, {'year': datetime.date(2018, 1, 1), 'month': datetime.date(2018, 6, 1)}, {'year': datetime.date(2018, 1, 1), 'month': datetime.date(2018, 5, 1)}, {'year': datetime.date(2018, 1, 1), 'month': datetime.date(2018, 4, 1)}, {'year': datetime.date(2018, 1, 1), 'month': datetime.date(2018, 3, 1)}, {'year': datetime.date(2018, 1, 1), 'month': datetime.date(2018, 2, 1)}, {'year': datetime.date(2018, 1, 1), 'month': datetime.date(2018, 1, 1)}, {'year': datetime.date(2017, 1, 1), 'month': datetime.date(2017, 12, 1)}, {'year': datetime.date(2017, 1, 1), 'month': datetime.date(2017, 11, 1)}, {'year': datetime.date(2017, 1, 1), 'month': datetime.date(2017, 10, 1)}, {'year': datetime.date(2017, 1, 1), 'month': datetime.date(2017, 9, 1)}, {'year': datetime.date(2017, 1, 1), 'month': datetime.date(2017, 8, 1)}]> I have the feeling I'm miles away from the desired result.. -
How to create 'terms & conditions check box' in django?
I want to make a registration form like this, where user would type username,email,password,confirm password and check the terms and condition box to register his/herself. But i dont know how to create a model row for check box so that according to its input i would allow or disallow user to register. models.py class registeration(models.Model): username = models.CharField(max_length=100) email = models.EmailField() password = models.CharField(max_length=100) confirm_pasword = models.CharField(max_length=100) def __str__(self): return self.username -
are there any way to aggregate multiple API result into single API in Django Rest Framework?
I have following url set which return json API. Now I wonder are there any way to create another API which aggregate all of these API result and return to one ajax call from client side lets say,url(r'^api/allData/(?P<pk>\d+)$',allData.as_view()) Does anyone know how to prepare class in views.py to achieve this? urlpatterns = [ url(r'^api/envelope/(?P<pk>\d+)$',envelopeData.as_view(),name='api-envelope'), url(r'^api/glass/(?P<pk>\d+)$',glassData.as_view(),name='api-glass'), url(r'^api/opaque/(?P<pk>\d+)$',opaqueData.as_view(),name='api-opaque'), url(r'^api/plant/(?P<pk>\d+)$',plantData.as_view(),name='api-plant'), url(r'^api/fan/(?P<pk>\d+)$',fanData.as_view(),name='api-fan'), url(r'^api/pump/(?P<pk>\d+)$',pumpData.as_view(),name='api-pump'), url(r'^api/people/(?P<pk>\d+)$',peopleData.as_view(),name='api-people'), url(r'^api/light/(?P<pk>\d+)$',lightData.as_view(),name='api-light'), url(r'^api/smallpower/(?P<pk>\d+)$',spData.as_view(),name='api-sp'), ] -
How to add string to a ModelSerializer in Django REST
In my database, I store the file name of a particular image for an item. Let's say this is the model in models.py from django.db import models class Product(models.Model): sku = models.CharField(validators=[isalphanumeric], max_length=20, null=False, blank=False) image = models.CharField(max_length=20, blank=False, null=False) and then I have a serializer defined like so in serializers.py from rest_framework import serializers from app.models import Product class ProductSerializer(serializer.ModelSerializer): class Meta: model = Product fields = '__all__' what I want is to be able to add a string to the image of a Product that makes it into a string representing the relative link, something like: storage_location = '/assets/img' img_url = f'{storage_location}/{image}' The reason why I want to do this is because I want to be flexible with the urls rather than having the file name be a "file location" and then having to update the database each time I change how I arrange my images (I'm still not sure how to store them). How can I do that? -
Apache 2.4 giving error "Forbidden You don't have permission to access /static/ on this server" while deploying Django on Fedora
I am new to django and facing this forbidden error while deploying django on apache. I have tried almost all the solutions available on google but still didn't get over this issue. Currently I am using: Python3.6 Apache 2.4 Fedora 28 I also tried moving my project into /var/www but that also doesn't work for me. This is how my httpd.conf file looks. <VirtualHost *:80> ServerName rohit.com DocumentRoot /home/rohit/django_ionic/ ServerAdmin root@localhost Alias /static /home/rohit/django_ionic/drfx/static <Directory "/home/rohit/django_ionic/drfx/static"> Options Indexes FollowSymLinks Allow from all Require all granted </Directory> <Directory /home/rohit/django_ionic/drfx/drfx> Options Indexes FollowSymLinks Includes ExecCGI AllowOverride All Order allow,deny Allow from all Require all granted </Directory> WSGIDaemonProcess mysite1 python-path=/home/rohit/django_ionic/drfx:/usr/lib/python3.6/site-packages WSGIProcessGroup mysite1 WSGIScriptAlias / /home/rohit/django_ionic/drfx/drfx/wsgi.py WSGIApplicationGroup %{GLOBAL} <Directory /home/rohit/django_ionic/drfx/drfx/> <Files wsgi.py> Allow from all Require all granted </Files> </Directory> </VirtualHost> i have also given the chown permissions to my django file folder. One more issue is my user and group is apache and i have seen a alot of solutions using user and group as www-data:www-data. Is that realy making any difference as i have given permissions by using apache:apache. -
How to fix the parentheses problem in this python coding?
function generate_map(){ $(".error").hide(); var map_position = $('#map_position')[0].value; var map_distance = $('#map_distance')[0].value; var to_date = $('.date_to')[0].value; var from_date = $('.date_from')[0].value; if($("#rbRouteOnly").is(':checked')){ $.ajax({ type: 'POST', url: '/generateMap', data: JSON.stringify( { 'position': map_position, 'distance': map_distance, 'to_Date' : to_date, 'from_Date' : from_date, } ), contentType: "application/json; charset=utf-8", dataType:'json', error:function(error){ alert("error Occured please try again later"); }, success: function (res) { // var jsonresult =$.parseJSON(result) // error if((res.result).length == 0){ $('.graph_data_error').show(); $('#movement_category')[0].innerHTML = ""; }else{ console.log(res.result); var graph_data = res.result; var dps1 = [], dps2 = [], dps3 = [], dps4 = [], dps5 = [], dps6 = []; var chart = new CanvasJS.Chart("movement_category",{ title:{ text: "TIME vs. Movement category" }, axisX:{ title: "TIME SLOT" }, axisY:{ title: "% of Movement Category" }, toolTip: { shared: true }, data: [ { type: "stackedArea100", name: "In Vehicle", showInLegend: "true", yValueFormatString: "#,##0.##\"%\"", dataPoints: dps1 }, { type: "stackedArea100", name: "On Bicycle", showInLegend: "true", yValueFormatString: "#,##0.##\"%\"", dataPoints: dps2 }, { type: "stackedArea100", name: "On foot", showInLegend: "true", yValueFormatString: "#,##0.##\"%\"", dataPoints: dps3 }, { type: "stackedArea100", name: "Standstill", showInLegend: "true", yValueFormatString: "#,##0.##\"%\"", dataPoints: dps4 }, { type: "stackedArea100", name: "Tilting", showInLegend: "true", yValueFormatString: "#,##0.##\"%\"", dataPoints: dps5 }, { type: "stackedArea100", name: "Unknown", showInLegend: "true", yValueFormatString: "#,##0.##\"%\"", dataPoints: dps6 } … -
I want Django orm to find difference in days between current date and a date time field from dB table
The my SQL query shown in the below. I want Django orm for Below query. select greatest((30-ifnull(DATEDIFF(CURRENT_DATE(),disabled_on),0)),0) AS unblock_days from tbl_users; Note: 'disabled_on' datetime(6) DEFAULT NULL -
Django - how to pass a value from an existing HTML form to a list view
I have an existing HTML form (text field + button) but have no idea how to pass an input value to a list view. book/templates/home.html: <form class="form-inline my-2 my-lg-0" method="post">{% csrf_token %} <input style="font-size: 12px; width: 200px" class="form-control mr-sm-2" type="search" placeholder="Book Name" aria-label="Search"> <button class="btn btn-outline-primary my-2 my-sm-0" type="submit">Search</button> </form> Image of the form: book/views/SearchResultView: class SearchResultView(generic.ListView): template_name = 'book/search.html' model = Book paginate_by = 100 As in creation views and update views or any other edit views, there will be an attribute called form_class, but not for display views. What can I do to achieve the goal? -
Django Sql: no such function: Decimal
I have the following query RecipePosition.objects.all().filter(mass_quantity__gt=0) In Django, try to debug the file /lib/python3.6/site-packages/django/db/models/sql/compiler.py to know how the sql is formed. def execute_sql(self, result_type=MULTI, chunked_fetch=False, chunk_size=GET_ITERATOR_CHUNK_SIZE): """ Run the query against the database and return the result(s). The return value is a single data item if result_type is SINGLE, or an iterator over the results if the result_type is MULTI. result_type is either MULTI (use fetchmany() to retrieve all rows), SINGLE (only retrieve a single row), or None. In this last case, the cursor is returned if any query is executed, since it's used by subclasses such as InsertQuery). It's possible, however, that no query is needed, as the filters describe an empty set. In that case, None is returned, to avoid any unnecessary database interaction. """ result_type = result_type or NO_RESULTS try: sql, params = self.as_sql() if not sql: raise EmptyResultSet At the below statement i checked the sql and params: sql, params = self.as_sql() sql = SELECT "recipes_recipeposition"."id", "recipes_recipeposition"."name", "recipes_recipeposition"."quantity", FROM "recipes_recipeposition" WHERE "recipes_recipeposition"."quantity" > %s and params = <class 'tuple'>: (Decimal('0'),) I tried the sql in sqlite browser: SELECT "recipes_recipeposition"."id", "recipes_recipeposition"."name", "recipes_recipeposition"."quantity", FROM "recipes_recipeposition" WHERE "recipes_recipeposition"."quantity" > Decimal('0') then it says no such function: Decimal -
Django - Unable to retrieve data in database in dropdownlist
Hi, I really need help in this, tried for many days and still cannot do it. I am very new to django. I am unable to retrieve the data in mySQL database to display it in a dropdownlist. Can someone help me please? appreciate it! models.py class paper(models.Model): id = models.CharField(max_length=70, primary_key=True, null=False) year = models.TextField(null=True) month = models.TextField(null=True) number = models.IntegerField(null=True) def __str__(self): return str(self.id) Views.py def dropdown_list(request): paperS = paper.objects.all() pname = request.GET.get(['paper_id']) if request.method == 'GET': z = ["Nov 2017 - GCE O'Level Elementary Mathematics Paper 1", "Nov 2017 - GCE O'Level Elementary Mathematics Paper 2", "Nov 2016 - GCE O'Level Elementary Mathematics Paper 1", "Nov 2016 - GCE O'Level Elementary Mathematics Paper 2", "Nov 2015 - GCE O'Level Elementary Mathematics Paper 1", "Nov 2015 - GCE O'Level Elementary Mathematics Paper 2", "Nov 2014 - GCE O'Level Elementary Mathematics Paper 1", "Nov 2014 - GCE O'Level Elementary Mathematics Paper 2", "Nov 2013 - GCE O'Level Elementary Mathematics Paper 1", "Nov 2013 - GCE O'Level Elementary Mathematics Paper 2", "Nov 2012 - GCE O'Level Elementary Mathematics Paper 1", "Nov 2012 - GCE O'Level Elementary Mathematics Paper 2", "Nov 2011 - GCE O'Level Elementary Mathematics Paper 1", "Nov 2011 … -
Django - PageNotFound after login
Django 2.1 does not obey my configuration in settings. After logging in, I get the error: Page not found (404) Request Method: GET Request URL: http://localhost:8000/accounts/login/index.html settings.py: LOGIN_REDIRECT_URL = 'dashboard/index' Login URL: http://localhost:8000/accounts/login/ myproject/urls.py path('admin/', admin.site.urls), path('', TemplateView.as_view(template_name='index/index.html'), name='index'), path('accounts/', include('django.contrib.auth.urls')), path('dashboard/', include('dashboard.urls')), dashboard/urls.py urlpatterns = [ path('index/', views.dashboard_index, name='dashboard_index'), ] dashboard/views.py @login_required def dashboard_index(request): return render(request, 'dashboard/index.html', {}) Any idea? -
django - Update model form when files are uploaded
I am building a website with lots of Work objects. Works are grouped into Collections, and each of those class has its own database model (so, each Work has a foreign key referring to its Collection). I typically add a Collection of several Work objects all at once. The models look something like this: class Collection(models.Model): name = models.CharField(max_length=100, default=None) description = models.TextField(null=True, blank=True, default=None) class Work(models.Model): collection = models.ForeignKey(Collection, on_delete=models.CASCADE) name = models.CharField(max_length=100, default=None) description = models.TextField(null=True, blank=True, default=None) imagepath = models.ImageField(upload_to=get_work_filename, default=None) To simplify adding these to the website, I want to add both of them in one form. So, I'm trying to use a custom ModelAdmin and Model Form: class WorkInline(admin.StackedInline): model = Work class CollectionForm(forms.ModelForm): name = forms.CharField() description = forms.Textarea() pictures = forms.FileField(widget=forms.ClearableFileInput(attrs={'multiple': True})) class Meta: model = Collection fields = '__all__' class CollectionAdmin(admin.ModelAdmin): form = CollectionForm fieldsets = ( (None, { 'fields': ('name', 'abbrev', 'description', 'pictures',), }), ) inlines = [WorkInline] The idea is that I fill in the name and description of the Collection, and then upload a bunch of images as Works in that collection. Most of the fields in Work can be autofilled based on just the filename of the uploaded … -
Combine and manipulate querysets based on if object in one is not in another
For some reason I cannot figure out the best way to do this. I can merge them, get the difference, etc - but can't figure out how to merge both query sets based on values, and then assign a different value after they're merged. I have two QuerySets: query_set_a = Reports.objects.filter( agent=report.profile.agent_code, product='product_a', date__range=(report_range_start, report_range_end), prem_submitted__gt=0).order_by('date') query_set_b = Reports.objects.filter( agent=report.profile.agent_code, product='product_b', date__range=(report_range_start, report_range_end), prem_submitted__gt=0).order_by('date') If you consider the following: {% for each in query_set_a %} [{{ each.date|date:"m-d" }} - {{ each.activated }}], {% endfor %} {% for each in query_set_b %} [{{ each.date|date:"m-d" }} - {{ each.activated }}], {% endfor %} Which outputs correctly: query_set_1 output [08-01 - 2], [08-02 - 2], [08-03 - 1], [08-06 - 1], [08-07 - 1], [08-10 - 13], [08-13 - 2] query_set_2 output [08-01 - 21], [08-02 - 23], [08-03 - 18], [08-06 - 17], [08-07 - 5], [08-09 - 2], [08-10 - 30], [08-13 - 13], [08-15 - 4], How would I take values that are in query_set_2 output and add them to query_set_1, but set query_set_1.activated to null? Such that query_set_1 would look like: [08-01 - 2], [08-02 - 2], [08-03 - 1], [08-06 - 1], [08-07 - 1], [08-09 - null], … -
Django - Multiple databases and single Auth
I have a customer that is a supermarket. They have a lot of stores across the country and what I'm trying to achieve with Django is to use: 1) django-hosts to have different domains for each store; 2) Django routers to have different databases for each store; I have read this tutorial: https://strongarm.io/blog/multiple-databases-in-django/ And also I'm reading Django docs: https://docs.djangoproject.com/en/2.1/topics/db/multi-db/ The link above shows how to use multi dbs and creates an Auth Database, which is exactly what I need, but following the example, they create "replica" databases, which is not my case. That's because each store has their own data and I don't want "replicas". Assuming that all of my users can access (read and write) all of stores data and not only one, my questions is, am I doing it right? Or should I do something else to achieve this architecture? PS: It sounds like an "open question" but its not, I want to know the best way to achieve my scenario combining everything together :) -
Django 2 Create Model Programmatically
I'm looking to auto-register app and create a Django model within the app programmatically, upon using manage.py startapp newapp --template=quicktemplate. My thought process is as below, but I only got up to auto-register app. But then, the whole process feels too hacky, and I very much welcome any Django-approved way. I looked up for migrations.CreateModel API, but it's too complex for my novice understanding. In my project-wide settings.py, I scan for folders which are not non-app folders i.e. project-level folder called quick. Here, I auto-register any new folders as app into INSTALLED_APPS INSTALLED_APPS = [ ... # django contribs ] NON_APP_FOLDERS = ['quick', 'quicktemplate', 'media'] APP_LIST = [ app for app in next(os.walk('.'))[1] if app not in NON_APP_FOLDERS ] INSTALLED_APPS = INSTALLED_APPS + APP_LIST In my quicktemplate, I have created initial model, and also update apps.py for the model initialization. # quicktemplate/models.py # declare model that will be initialized once upon app creation from django.db import models class AppProfile (models.Model): name = models.CharField(max_length=100) ... # quicktemplate/__init__.py # to allow AppConfig ready() to be called default_app_config = '{{ app_name }}'.apps.'{{ camel_case_app_name }}' ... #quicktemplate/apps.py from django.apps import AppConfig class {{ camel_case_app_name }}Config(AppConfig): name = {{ app_name }} def ready(self): # NOT … -
Saving paragraphs using Factory Boy / Faker
factory.Faker("paragraphs", nb=3, ext_word_list=None) returns factory.faker.Faker object and when used on a text field, it's saving the actual list instead of joined as paragraphs! I am getting this in DB: ['Course step statement human special relationship step. Shake boy expert. Support argue officer school.', 'Work stay visit range any still. Both job blue over since.', 'Truth food tree risk. Forward attention grow stand listen also few. Sea process else commercial minute.'] Any idea how to save it as a string? -
One ListView blocks the otherone
I'm working on a app, and the app has two different ListViews, one of them for posts the other is for news. Here are the Views: class NewsListView(ListView): context_object_name = 'news' model = models.News template_name = 'posts/news_list.html' def get_queryset(self): return News.objects.all() class PostsListView(ListView): context_object_name = 'posts' model = models.Posts template_name = 'posts/posts_list.html' def get_queryset(self): return Posts.objects.all() Here is the apps urls.py: urlpatterns=[ url(r'^$',views.NewsListView.as_view(),name='news'), url(r'^$',views.PostsListView.as_view(),name='posts'),] And here is the projects urls.py: urlpatterns = [ url(r'^$',views.IndexView.as_view(),name='index'), path('admin/', admin.site.urls), url(r'^posts/',include('posts.urls',namespace='posts')),] My problem i that for some reason only one List works, always the one which is is the first one in the apps urls.py. How can i solve this problem? Thanks for your help!!! -
Django ForeignKey in same table about same attribute in different table
I have one model in my project. class users(models.Model): match_user = models.ForeignKey(User,on_delete=models.CASCADE) matched_user = models.CharField(max_length=25) Imagine that: match_user is 'Mete' and matched_user is 'Gizem'. Also match_user is 'Gizem' and matched_user is 'Mete' I have 2 table line: id match_user matched_user __ __________ ____________ 1 mete gizem 2 gizem mete Now if ı want delete mete, only first row deleted. But I want to delete 2 rows.Actually I want to two foreign key about same location in different table. How I can? is it possible. İf it is not a possible, is there any solution for my want. Also I tried some different ways like that: match_user = models.ForeignKey(User,related_name="username"on_delete=models.CASCADE)` matched_user = models.ForeignKey(User,related_name="username"on_delete=models.CASCADE)` But there is error all time Thanks for answers :) -
Django: setting initial in get_context_data doesn't work as expected
I am trying to set initial within a class based view, to pre-populate a text input with name=description The following code seems to accept an integer input in the url as specified, and puts this where I want it in the template. #urls.py urlpatterns += ( path('repair/', views.RepairListView.as_view(), name='app_name_repair_list'), path('repair/create/<int:pk>', views.RepairCreateView.as_view(), name='app_name_repair_create'), ) # views.py class RepairCreateView(CreateView): model = Repair form_class = RepairForm def get_context_data(self, **kwargs): context = super(RepairCreateView , self).get_context_data(**kwargs) self.initial['description'] = self.kwargs['pk'] return context However when accessing in the browser... access: /repair/create/1 text input contains: 1 access: /repair/create/2 text input contains: 1 (again) access: /repair/create/3 text input contains: 2 (and so forth) Have I done something blatantly wrong here or is this some kind of weird bug? I'm basically plan to have a URL somewhere else on the site, that the user would click to load this form, thus populating the form with already known information which would be in said URL. -
ckeditor_uploader Dynamic Image Upload Path
I have a Django application that requires users to upload multiple images per document. The application has django-ckeditor installed, but the uploaded images end up in the same folder set by the CKEDITOR_UPLOAD_PATH setting. I would like the path to be dynamic, based on the URL scheme. For example, images uploaded to the CKEditor instance on https://myapp/report/1/finding/5 should reside in /ckeditor_base_path/report/1/finding/5/my_img.png. Unfortunately, the URL for the view function that handles setting the path is set by the widget (CKEditorUploadingWidget) before the view creates a context parameter. I was hoping to send the parameters URL parameters to ImageUploadView for processing. Any help or advice on this is greatly appreciated. -
Receive http request
CLIENT: I sent this http request, code: import requests payload = {'data': [{'name': 'pippo', 'age':'7'}, {'name':'luca', 'age':'12'}]} r = requests.post("http://127.0.0.1:8000", data=payload) print(r.url) Server Django. code views.py: from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt @csrf_exempt def home(request): context = {'request_method': request.method} if request.method == 'POST': context['request_payload'] = request.POST.dict() post_data = request.POST print(post_data) for key, value in post_data.items(): for subvalue in value: print{key, subvalue} if request.method == 'GET': context['request_payload'] = request.GET.dict() return render(request, 'main/index.html', context) when i do execute. Django i not receive data of send client. My result in print(post_data)on django are : <QueryDict: {'data': ['name', 'age', 'name', 'age']}> I would like to extract this: {'name': 'pippo', 'age':'7'} {'name':'luca', 'age':'12'} How can I do? -
Redirecting if already logged in
After my users log in, they can still access the login.html page and "log in again". They can also manually access the pages meant to be seen only when registering ("enter your name and telephone number" sort of pages). I'd rather they not be able to access these after they're logged in. There is no @login_forbidden decorator. So how can I redirect if a user is already logged in?