Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 … -
Backend is not taking styles, images, etc
I make a project, backend is make in python/django and frontend is make in React. I already finish and I make a npm run build:prod to make a umd.js and umd.js.map. I upload that files to my backend folder /static/js, but there is not styles or images when I deploy my backend server. -
how to use CASE when then in sql?
i have an sql query that crash the program i want to check if the field contain 0 or 1 so i used : query = cursor.execute('select ID, CASE WHEN status = 1 THEN "GOOD" WHEN status = 0 THEN "BAD" END AS status FROM Person') the error is below : invalid column name "GOOD" invalid column name "BAD" -
Heroku Deployment: Scaling dynos... ! ▸ Couldn't find that process type (web) error - Django Application
I keep getting the following errors when trying to deploy my django application to Heroku. Scaling dynos... ! ▸ Couldn't find that process type (web) error heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=abc123.herokuapp.com dyno= connect= service= status=503 bytes= protocol=https heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=abc123.herokuapp.com dyno= connect= service= status=503 bytes= protocol=https -
Django- Why I am getting this Programming Error
Django- Why I am getting this Programming Error When I have not declared shop_product variable anywhere . Please help Click here to view error Image please refer to this image of error -
Local variable unreferenced in decorator definition
My code is behaving weird, and I can't get why. Here is the code: # 1) The decorator urlpatterns = [] def route(url, name=""): def dec(f): print("NAME:", name) urlpatterns.append( path(url, f, name=name) ) return f return dec # 2) The decorator call @route("/my_function") def my_function(): print("Hello world") I get an UnboundLocalError on name File "urls.py", line 10, in dec if name == "": UnboundLocalError: local variable 'name' referenced before assignment name should be set to "" by default, I don't understand where the problem is. The weird thing is if I run the same code and change the decorator to this: urlpatterns = [] def route(url, name=""): def dec(f): if name == "": print("I work!") urlpatterns.append( path(url, f, name=name) ) return f return dec It works perfectly and output: I work ! while the problem was supposed to come from the line if name == "" PS: I'm programming on django, this line is in the urls.py file. -
Django models timestamp in MYSQL Db
I want to store time as unix timestamp in my MYSQL database, I have django project with model: date = models.DateField() But I didn't find any models.Timestamp() or anything similiar. Is there a way to create timestamp column for MYSQL Db in Django? I found some articles here on stack but they are 5+ years old so there might a be a better solution now.