Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django List objects that will be deleted by deleting the current object
In my DeleteView template, I'd like to warn the user that deleting the current object will delete the following objects (since the db schema requires on_delete = models.CASCADE). Here is an example model: class Book(models.Model): course = models.ForeignKey(Course, related_name = 'course_books', on_delete = models.CASCADE, null = True, blank = True) class Exercise(models.Model): book = models.ForeignKey(Book, related_name = 'exercises', on_delete = models.CASCADE, null = True, blank = True) ... class Solution(models.Model): exercise = models.ForeignKey(Exercise, related_name = 'solutions', on_delete = models.CASCADE, null = True, blank = True) So, say the user wants to delete a course, I'd like to warn the user which books, exercises, and solutions will be deleted upon deleting the current book. Something to this effect: WARNING: Deleting course Programming 101 will delete Python Programming for Beginners and Python By Example. It will also delete Excersises 1-5 and solutions 1-10 This will require that I can look at the related field to see if the on_delete is set to CASCADE or not. If it is, I should add it to the list of to_be_deleted objects. I have looked to see if I can check the on_delete attribute of the field: for related_object in the_course._meta.related_objects: dir(related_object.field) But nothing shows up … -
Django authenticate method returns None
I am trying to create a user login. I am registering the user through django's admin page. Username and passwords are entered correctly. Also I have tried adding authentication backends to settings.py I have tried multiple ways but couldn't get it to work. AUTHENTICATION_BACKENDS = ( 'django.contrib.auth.backends.ModelBackend', ) My code looks like below : models.py : class Account(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) views.py: def login(request): if request.method == 'POST': username = request.POST.get('user') password = request.POST.get('pass') user = authenticate(username=username, password=password) ----------> None if user: if user.is_active(): login(request, user) return HttpResponseRedirect(reverse('index')) else: return HttpResponse('Account not active') else: print('Someone tried to login and failed ') print('Username {} and passowrd {}'.format(username, password)) return HttpResponse('Invalid login details supplied!!') else: return render(request,'account/login.html', {}) -
Django & Django ORM: performance improvements to bulk updating records
I'm hoping this will be a really simple question. I just wanted some advise on the bulk updating of records. An example bulk update may go something like this: for user in User.objects.all().iterator(): user.is_active = False user.save() Is there a more efficient way to do this on the database level using the Django ORM? Would the following be more efficient: User.objects.all().update(is_active=False)? -
Why is makedirs() creating an empty file instwad of a folder?
I am creating a Django app and using Python to create an upload folder. For now, I am using static names to test. My function creates an empty file only, not a folder. I have tried both mkdir() and makedirs() with the same result. I am testing on Windows 10. This is in my model: def uploadloc(self, irun): if not os.path.exists('device1'): os.makedirs('device1') return 'device1' iimage = models.ImageField(null=True, default=None, upload_to=uploadloc) I think this should be creating a folder but it is only creating an empty file. irun is currently no used. -
Chart js does not load on page
I have the following Django code, it has a list of cards that are automatically generated and each card should be generated a Chart. However, this chart is being generated only on the first card, not the others. What can I be doing wrong? Check out my code {% extends 'base.html' %} {% load static %} {% block title %} Listagem de Linhas {% endblock title %} {% block content %} <div class="row"> {% for row in list %} <div class="col-xs-6 col-md-4"> <div class="card"> <h5 class="card-header">{{row.description}}</h5> <!--<img class="card-img-top" src="{% static 'img/gauge.png' %}" width="100" height="200" alt="Card image cap">!--> <canvas id="myChart"></canvas> <a href="{% url 'row_details' pk=row.pk %}" class="btn botao-detalhar">Detalhar</a> </div> </div> {% endfor %} </div> {% endblock content %} {% block scripts %} <script> var ctx = document.getElementById('myChart').getContext('2d'); var chart = new Chart(ctx, { // The type of chart we want to create type: 'doughnut', // The data for our dataset data: { labels: ["January", "February", "March", "April", "May"], datasets: [{ label: "My First dataset", backgroundColor: ['rgb(0, 99, 132)', 'green', 'red', 'yellow', 'orange'], borderColor: '#fff', data: [5, 10, 5, 2, 20], }] }, // Configuration options go here options: { circumference: 1 * Math.PI, rotation: 1 * Math.PI, cutoutPercentage: 90 } }); … -
Dynamic year wise data in chart.js
I am using chart.js. And i want to know how can i display dynamic date and data using the following queryset. I am using django 2.2 its i could not find any complete tutorials online. views.py def get(self, request, format=None): qs = Add.objects.annotate( month=TruncYear('date')).values('month').annotate(total_income=Sum('budget'), total_expense=Sum('expense')).order_by('month') labels = ["2019",'2020',] default_items = [100, 200 ], data = { "newlabels": labels, "newdata": default_items, } return Response(data) Template var endpoint = '/api/chart/data/' var labels = [] var defaultData = []; $.ajax({ method: "GET", url: endpoint, success: function(i){ labels = i.newlabels defaultData = i.newdata var ctx = document.getElementById('myChart'); var myChart = new Chart(ctx, { type: 'bar', data: { labels: labels, // CHANGED datasets: [{ label: 'sum', data: defaultData, // CHANGED }] } }) }, -
Django - Get mode from ImageField
I want to find out the mode while saving an image. I have a model something like this: class Model(models.Model): image = models.ImageField() def save(self, *args, **kwargs): self.create_dominant_color() super().save(*args, **kwargs) def create_dominant_color(self): color = get_dominant_color(self.image) self.dominant_color = color that's my get_dominant_color (from https://stackoverflow.com/a/34964548/9878135): def get_dominant_color(image_file): im = Image.new(image_file.mode, (150, 150)) ar = scipy.misc.fromimage(im) shape = ar.shape ar = ar.reshape(scipy.product(shape[:2]), shape[2]) codes, dist = scipy.cluster.vq.kmeans(ar, NUM_CLUSTERS) vecs, dist = scipy.cluster.vq.vq(ar, codes) # assign codes counts, bins = scipy.histogram(vecs, len(codes)) # count occurrences index_max = scipy.argmax(counts) # find most frequent peak = codes[index_max] colour = "#" + ''.join(chr(c) for c in peak).encode('hex') return colour -
Another module not found error for django-docs
I am running a Cookiecutter django app. Now I want to integrate django-docs (https://pypi.org/project/django-docs/). I am fairly sure that I am doing it correctly since I am just copy and pasting from the documentation. After installing it I build my docker image anew and run my server. I get the error: ModuleNotFoundError: No module named 'docs.urls' My process was like this: 1) Add app to base requirements django-docs==0.3.1 # https://github.com/littlepea/django-docs 2) Add it to my apps in my config file ... 'allauth.socialaccount', 'rest_framework', 'docs', .... 3) Rebuild docker image docker-compose -f local.yml build 4) Then I added this to my urls which throws me the error: url(r'^docs/', include('docs.urls')), I also tried path('docs/', include('docs.urls')), Is there anything I am missing? THe other SO questions didn't solve my problem. Thanks for any help! Very much appreciated! -
Django - Get a list of values from another model
I installed a third party app which has basically 5 fields: id, name, state, geocode, geometry. I created a new app which I need to import only the values from the 'name' field from the other model. So I basically did this: from django.db import models from django.contrib.auth.models import User from django.contrib.gis.geos import Point from brasil_municipios.models import Municipio #which is the third party app class Escritorio(models.Model): nomeescritiorio = models.CharField(max_length=255) cidade = models.OneToOneField(Municipio.objects.values_list('name').order_by('name')[0:10], on_delete=models.PROTECT, null=True) And got this error: AssertionError: OneToOneField(<QuerySet [('ABADIA DE GOIÁS',), ('ABADIA DOS DOURADOS',), ('ABADIÂNIA',), ('ABAETETUBA',), ('ABAETÉ',), ('ABAIARA',), ('ABARÉ',), ('ABATIÁ',), ('ABAÍRA',), ('ABDON BATISTA',)]>) is invalid. First parameter to ForeignKey must be either a model, a model name, or the string 'self' I already tried others ways to solve the issue, using filter(), get() and etc, but all get the same error in all of them. Any tip will be really helpful. Thanks in advance. -
python lxml throwing key error bool while processing kwargs as dict
I'm trying to chain Django Q() objects with code piece below: excludes = None for val in service_dict.values(): field_filter_name = field_name.format(val) exclude_filter = {field_filter_name + "__isnull": True} if excludes is None: excludes = Q(**exclude_filter) else: excludes |= Q(**exclude_filter) On run time, when code hit to excludes = Q(**exclude_filter) line on first loop, throwing this error: File "/lib/python3.6/site-packages/lxml/builder.py", line 218, in call get(dict)(elem, attrib) File "/lib/python3.6/site-packages/lxml/builder.py", line 205, in add_dict attrib[k] = typemap[type(v)](None, v) KeyError: <class 'bool'> I'm quite certain that the values are string type. But this is working on python shell in the same environment: In [9]: Q(**{"foo__isnull": True}) Out[9]: <Q: (AND: ('foo__isnull', True))> I also tried outside of the environment: >>> a = {'foo': True} >>> def k(foo): ... print(foo) ... >>> k(**a) True On the other hand; that kind of usage of the kwargs are working at any other part of the code. How could this issue be solved? -
Django Form Submit 'null value in column "project_id" violates not-null constraint', but Form is valid
I have a form that is two values, a name and a foreign key reference to a parent id. When I submit the form, it validates and I can see the two values (name and parent id), but upon saving I get a null constraint error. Model: class Product(models.Model): """Product object containing LCI information for contained substances.""" name = models.CharField(null=False, blank=False, max_length=255) stages = models.ManyToManyField('LifeCycleStage') project = models.ForeignKey(Project, on_delete=models.CASCADE) Form: class ProductForm(ModelForm): """ Base form for creating a new product. """ # Product Name name = CharField( max_length=255, widget=TextInput({'class': 'form-control mb-2', 'placeholder': 'Product Name'}), label=_("Product Name"), required=True) project_id = IntegerField( widget=NumberInput({'class': 'form-control mb-2', 'readonly': 'readonly'}), required=True, label=_("Parent Project")) class Meta: """Meta data for Product form.""" model = Product fields = ('name', 'project_id') Post method: @method_decorator(login_required) def post(self, request, *args, **kwargs): """Process the post request with a new Product form filled out.""" form = ProductForm(request.POST) if form.is_valid(): product_obj = form.save(commit=True) return HttpResponseRedirect('/products/create/lifecyclestage?product_id=' + product_obj.id) return render(request, "create.html", {'form': form}) Completed and validated form in the view: Completed and validated form in the view Template error: IntegrityError at /products/create/ null value in column "project_id" violates not-null constraint DETAIL: Failing row contains (4, Test Product, null). Request Method: POST Request URL: http://localhost:58661/products/create/ Django … -
Error setting up gdal in windows 10 for my Django project
I am having problems setting up gdal in a Djnago project.I have django and installed ad my virtual environment activated.I also have gda installed via OSGeo4W.Iam using python version 3.7.2 32 bit and postrges database which have have been correctly configured in may settings.py file but whenever I try to migrate it throws an error. This is my settings file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'blog' ] DATABASES = { 'default' : { 'ENGINE': 'django.contrib.gis.db.backends.postgis', 'NAME' : 'location', 'USER' : 'postgres', 'HOST' : 'localhost', 'PASSWORD' : 'bjhbchbcjbhc', 'PORT' : '5432', } } Do I need to add the settings to the system PATH?,or could it be that the I need to` install other packages or it to work -
How to use variables in url mapping / Django
I would like to achieve the following when using my dashboard: 1.) When a user selects a different team in the sidebar, the url should change accordingly. Can this be done using a variable in html href tag (and to call the same views function)? If so, how would I have to adapt the url mapping accordingly? 2.) To each team a team_id is assigned. How can I forward this variable (javascript on 'click') to the according views function to make a specific API call or how could a possible workaround look like? So basically I would like to have the user selecting a team and the dashboard to update accordingly (with the view function to make an API call using the individual team_id to get the correct data in return for rendering). At this stage I am searching for a non Ajax solution with reloading the page (since the URL shall change anyways). the related html ecerpt: <!DOCTYPE html> {% load static %} {% csrf_token %} <html lang="en" dir="ltr"> <head> <meta charset="utf-8"> <link rel="stylesheet" href="{% static "/styles.css" %}"> <link href="https://fonts.googleapis.com/css?family=Muli&display=swap" rel="stylesheet"> <link href="https://fonts.googleapis.com/css?family=Roboto&display=swap" rel="stylesheet"> <link rel="shortcut icon" href="/dasocc_site/dasocc_app/static/images/dasoccfavicon.png"/> <title>DASOCC</title> </head> <body> <div id="outerContainer"> <!-- Sidebar --> <div id="sidebar"> <header> … -
Django Rest framework post ForeignKey
I am using DRF to update data. Its works good, but I am struggling how to update foreign keys. { "name": "Ready Or Not", "releases": [ { "platform": { "name": "test" }, "date": "2019-10-02T11:38:18Z" } ] }, This is a response of my API. But I want to update this 'releases' information as well. To sent I have this. If the 'platform' name doesnt exist it should also create one. How do I do this? headers = { 'Authorization': 'Token ' + ss_token, } data = { 'steam_id': 23, "releases": [ { "platform": { "name": "wanttoupdate" }, "date": "2019-10-02T11:38:18Z" }, ], "website": 'testweb' } source = Source.objects.all().first() url = source.url + str(947) + '/' response = requests.patch(url, headers=headers, data=data) My models: class Game(models.Model): name = models.CharField(max_length=255) class Platform(models.Model): name = models.CharField(max_length=255) class Release(models.Model): platform = models.ForeignKey(Platform, on_delete=models.CASCADE) game = models.ForeignKey(Game, related_name='releases', on_delete=models.CASCADE) date = models.DateTimeField() -
Django: Easy Way to Enable Translation in Javascript?
Django developers might at some point run into the problem how to get translation into their JavaScript files. Django offers a JavaScriptCatalog. It passes the translations into JavaScript, so you can call gettext, etc., from within JavaScript. In my mind, this generates too much overload for most smaller projects. So I would like to share my solution, how to generate a lightweight translated JavaScript translated catalog. -
Django API - No Data in Console
I get no data from the api in the browser's console and nothing in the template index.html <script> {% block jquery %} var endpoint = '/api/data/' $.ajax({ method: 'GET', url: endpoint, success: function(data){ console.log(data) }, error:function(error_data){ console.log("error") console.log(error_data) } }) {% endblock %} </script> <div class="col-12" url-endpoint='{% url "api-data" %}' ></div> <h1>{{ customers }}</h1> views.py def index(request): return render(request, 'personal/header.html') def get_data(request,*args,**kwargs): data = { 'sales':100, 'customers': 10, } return JsonResponse(data) urls.py url(r'^$', index, name='index'), url(r'^api/data/$', get_data, name="api-data"), Thank you for any help -
Image cropping when a whole image is chosen it corrupts?
I have a Django app where users might want to crop images so I used CropperJs and PILL. The function works as expected when they want only a part of the image but when they choose the whole image the result would be just a corrupted black image. result: here's the pill function : def crop(corrd, path): dot = path.rfind(".") fn = path[:dot] ext = path[dot:] image = Image.open(path) time = datetime.now().strftime("%Y%m%d-%H%M%S") path_ = fn + time + ext cropped_image = image.crop(corrd) resized_image = cropped_image.resize((384, 384), Image.ANTIALIAS) resized_image.save(path_) return path_ and here's the js function to manipulate the box data: $("#modalcrop{{image.pk}}").on("shown.bs.modal", function () { $image{{image.pk}}.cropper({ viewMode: 1, aspectRatio: 1/1, minCropBoxWidth: 200, minCropBoxHeight: 200, ready: function () { $image{{image.pk}}.cropper("setCanvasData", canvasData{{image.pk}}); $image{{image.pk}}.cropper("setCropBoxData", cropBoxData{{image.pk}}); } }); -
Transform foreignkey multipoint object values to coordinates for webmap
I'm trying to construct a gejson from a model with a foreignkey geometry, to be read by leaflet and display it in a webmap, but I cant find a way to transform the values, model.py class Info_Proy_eyd(models.Model): nombre_proyecto = models.CharField(max_length=50) rol_fk = models.ForeignKey(D_Base_Roles, on_delete=models.CASCADE, blank=True, null=True, verbose_name="Rol) function inside model: def json(self): return { 'nombre_proy':self.nombre_proyecto, 'geom':str(self.rol_fk.geom) } I insert the value as a string or I get this as the value in the json: < MultiPoint object at 0x7f0f680dea28 > the value I get from calling the foreign key to insert in a json function is: ['SRID=32719;MULTIPOINT (357585.933215158 7389786.21755914)'] How can I transform it to coordinates to insert in my json function and be read by leaflet?? thanks!! -
I'd like to create a url link on the current page to an existing form using the current url
I'm learning Django by following the mdn locallibrary tutorial and would really like some help constructing links to update and delete authors. I have created a link to my create author form (<li><a href="{% url 'author_create' %}">Add Author</a></li>) which works fine. What I am trying to do next is to grab the trailing integer from the current page (my author_detail.html) url e.g. http://127.0.0.1:8000/catalog/authors/12 and then create a new url that links to my update author form. I have added the following code to the end of my author_detail.html file: {% if user.is_staff %} <hr /> <ul class="sidebar-nav"> <li>Staff</li> {% if perms.catalog.can_mark_returned %} <li><a href="{% url 'author_create' %}">Add Author</a></li> <li>{{ currentUrl}}...current url</li> {% endif %} </ul> {% endif %} </div>``` The 'Add Author' link works fine but I have absolutely no idea how to construct the url to update the author on which the current page is displaying. In the code above, the second list item is trying to display the current page url, it doesn't work and I just get '...current url' displayed. I actually want to construct the url to allow the user to update the current author I have this class defined in my views.py: ```class AuthorDetailView(generic.DetailView): model … -
Through django ORM get all the equipmets and equipment details which has category_id = 1?
These are my django models. explaination of db models : thinkpad is a equipment of laptop subcategory.and laptop subcategory has a category called electronics. now laptop can have many attributes like processor,ram,color,screen_size. Question : Find out all the equipment with theirequipment detail and attribute names,value which have category_id =1 . Tried approach: subcategories_of_specific_category = Category.category_subc__set.all() for each in subcategories_of_specific_category: equipments_of_each_subcategories =[] equipments_of_each_subcategories.append(each.subcategory_eq__set.all()) for each in equipments_of_each_subcategories: equipment_details = [] and so on ... ...very lengthy approach as i will have to again make loop for attribute names of each equipment. Models : class Category(models.Model): category_id = models.AutoField(primary_key=True, default=None) category_name = models.CharField(max_length=15, unique=True) created_at = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) def __str__(self): return str(self.category_id)+","+self.category_name class Meta: db_table = "category" class Subcategory(models.Model): subcategory_id = models.AutoField(primary_key=True, default=None) category = models.ForeignKey( Category, on_delete=models.CASCADE, related_name="category_subc", verbose_name="category_id") subcategory_name = models.CharField(max_length=15, unique=True) created_at = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) def __str__(self): return str(self.subcategory_id)+","+self.subcategory_name class Meta: db_table = "subcategory" class Equipment(models.Model): equipment_id = models.AutoField(primary_key=True, default=None) subcategory = models.ForeignKey( Subcategory, on_delete=models.CASCADE, related_name="subcategory_eq", verbose_name="subcategory_id") created_at = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) def __str__(self): return str(self.equipment_id) class Meta: db_table = "equipment" class Attribute(models.Model): attribute_id = models.AutoField(primary_key=True, default=None) attribute_name = models.CharField(max_length=15, unique=True) subcategory = models.ManyToManyField( Subcategory, through="SubcategoryAttributeMap") created_at = models.DateTimeField(auto_now_add=True) last_modified = models.DateTimeField(auto_now=True) def __str__(self): … -
Django how to search filter in subquery
How to search intro subquery my view dif = Account.objects.annotate(credit_sum=Subquery(credits.values('sum_credits')),debit_sum=Subquery(debits.values('sum_debits')),balance=F('credit_sum') F('debit_sum')).values_list('name', 'balance') my view search filter qs = Account.objects.filter(owner=request.user) name= request.GET.get('name') if is_valid_queryparam(name): qs = qs.filter(name=name) Not show result -
PermissionError: [Errno 13] Permission denied when including a template via context variable, works fine when hardcoded
I'm trying to pass a variable with a template name/path from views to the another template. So than I can use the variable in the include tag. I'm getting the error: File "c:\program files\python37\lib\site-packages\django\template\loaders\filesystem.p y", line 23, in get_contents with open(origin.name, encoding=self.engine.file_charset) as fp: PermissionError: [Errno 13] Permission denied: 'D:\\temp\\YandexDisk\\programming\\py\\n hl_web_app\\templates' Full traceback: Internal Server Error: /game/anaheim-ducks-san-jose-sharks2018-10-03/2018020004/ Traceback (most recent call last): File "c:\program files\python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "c:\program files\python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "c:\program files\python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "D:\temp\YandexDisk\programming\py\nhl_web_app\players\views.py", line 110, in ga me_detail return render(request, 'players/game_detail.html', context) File "c:\program files\python37\lib\site-packages\django\shortcuts.py", line 36, in re nder content = loader.render_to_string(template_name, context, request, using=using) File "c:\program files\python37\lib\site-packages\django\template\loader.py", line 62, in render_to_string return template.render(context, request) File "c:\program files\python37\lib\site-packages\django\template\backends\django.py", line 61, in render return self.template.render(context) File "c:\program files\python37\lib\site-packages\django\template\base.py", line 171, in render return self._render(context) File "c:\program files\python37\lib\site-packages\django\test\utils.py", line 96, in i nstrumented_test_render return self.nodelist.render(context) File "c:\program files\python37\lib\site-packages\django\template\base.py", line 937, in render bit = node.render_annotated(context) File "c:\program files\python37\lib\site-packages\django\template\base.py", line 904, in render_annotated return self.render(context) File "c:\program files\python37\lib\site-packages\django\template\loader_tags.py", lin e 150, in render return compiled_parent._render(context) File "c:\program files\python37\lib\site-packages\django\test\utils.py", line 96, in i nstrumented_test_render return self.nodelist.render(context) File "c:\program files\python37\lib\site-packages\django\template\base.py", … -
Upload Image File along with regular Form Data
I am using django with VueJS. The data is updating properly in my database. I need to accomplish two things: Post the correct content to the field image_file. Get the downloaded image file pasted onto the servers folder which is media/shop/images My attempted code is as below: models.py ... image_file = models.ImageField(upload_to='shop/images/', blank=True, null=True) urls.py ... urlpatterns += [ url(r'^Load-Image-Axios$', myviews.Load_Image_Axios, name='Load-Image-Axios'), ] views.py @api_view(['GET', 'POST', 'PUT', 'DELETE']) def Post_Items_Axios(request): if request.method == 'POST': data_itemfullhd = request.data['Item Name'] data_image_file = request.data['Item Image File'] td_items, created = Md_Items.objects.get_or_create( itemfullhd = data_itemfullhd) td_items.imagefl = data_imagefl td_items.image_file = data_image_file td_items.save() data = { 'data_itemfullhd': data_itemfullhd } return Response(data) bm_home.html <template id="product-edit"> <div> <h2>Product details</h2> <form method="post" enctype="multipart/form-data">{% csrf_token %} <div class="form-group"> <label for="edit-name">Item Name</label> <input class="form-control" id="edit-name" v-model="product.itemfullhd" required/> </div> <!-- Upload single Image files --> <div class="form-group"> <label for="edit-imagefile">Image</label> <input type="file" id="edit-imagefile" @change="onFileChanged" required/> </div> <button type="submit" class="btn btn-primary" @click.prevent="updateProduct">Save</button> <a class="btn btn-dark"><router-link to="/product-list">Cancel</router-link></a> </form> </div> </template> Vue template var ProductEdit = Vue.extend({ template: '#product-edit', data: function () { return { product: findProduct(this.$route.params.product_id), selectedImage: null, }; }, methods: { onFileChanged (event) { this.selectedImage = event.target.files[0] this.product.image_file = this.selectedImage.name }, updateProduct: function () { let product = this.product; products[findProductKey(product.id)] = { id: product.id, … -
Is it possible to add an app to django that does not require a database
I have a simple script that creates a unique one time only disposable hash and I was hoping to just add it to my existing django site as this tool is for the people that use the site. I can find nothing at all on google about this and it seems a shame to have to create a completely separate website just to provide a GUI for a simple 5 line script. -
Aggregation by Foreign Key and other field in Django Admin
I'm working in Django and having an issue displaying something properly in my Admin site. These are the models class IndexSetSize(models.Model): """ A time series of sizes for each index set """ index_set = models.ForeignKey(IndexSet, on_delete=models.CASCADE) byte_size = models.BigIntegerField() timestamp = models.DateTimeField() class IndexSet(models.Model): title = models.CharField(max_length=4096) # ... some other stuff that isn't really important def __str__(self): return f"{self.title}" It is displaying all the appropriate data I need, but, I want to display the sum of IndexSetSize, grouped by the index_set key and also grouped by the timestamp (There can be multiple occurrences of an IndexSet for a given timestamp, so I want to add up all the byte_sizes). Currently is just showing every single record. Additionally, I would prefer the total_size field to be sortable Current Admin model looks like: class IndexSetSizeAdmin(admin.ModelAdmin): """ View-only admin for index set sizes """ fields = ["index_set", "total_size", "byte_size", "timestamp"] list_display = ["index_set", "total_size", "timestamp"] search_fields = ["index_set"] list_filter = ["index_set__title"] def total_size(self, obj): """ Returns human readable size """ if obj.total_size: return humanize.naturalsize(obj.total_size) return "-" total_size.admin_order_field = 'total_size' def get_queryset(self, request): queryset = super().get_queryset(request).select_related() queryset = queryset.annotate( total_size=Sum('byte_size', filter=Q(index_set__in_graylog=True))) return queryset It seems the proper way to do a group by …