Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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. -
How to combine AJAX + view function (API call) + url mapping the smart way?
I have a Javascript/AJAX function that assigns the team_id of a soccer team to a variable on 'click' of the teams name in the sidebar (see below for a screenshot). This variable shall then be used to make the according API call to get fresh data to update the dashboard as requested. The web application/dashboard is Django based. The Javascript itself assigns the variable smoothly and the views function itself fetches data from the API as well (when using a fix API URL without the assigned variable). To make this thread a future guidance for similar issues, i divided the content in different questions and tried to present it as neat as possibe. 1.) Now when I want to combine these steps i always end up with a TypeError (because the API call doesn't return any data) since the views function seems not to use the assigned variable 'team_id' within the API url (the team_id is emtpy when debugging = no API data in return). Why is that? 2.) I also tried to change the logic of the url mapping that way (which I would prefer) that there is only one url e.g. www.dasocc.com to display the dashboard and the … -
Using django url tag inside jquery ajax
I am building a page which holds some categories and when user clicks on a link, then I go ahead and fetch the details for that specific category (products of that category). The way to do this, I thought, was to use jQuery Ajax. Anyway, the part where i append my data is like this: ... $.ajax({ ... success: function(results) { $("#cards").empty(); for (let iterator = results.length -1; iterator>=0; iterator--) { $("#cards").append( '<a href="{% url "product" '+results[iterator].id+' %}">' +'<div>' + '<div class="card mb-5 shadow-sm">' + '<img class="card-img-top"' + 'src="'+results[iterator].image+'" />' + '<div class="card-body">' + '<h5 class="card-title">'+results[iterator].name+'</h5>' + '<p class="card-text">'+results[iterator].price+'</p>' + '</div>' + '</div>' +'</div>' +'</a>' ); } }, ... }); ... Based on this block of code, i get this error: Reverse for 'product' with arguments '('+results[iterator].id+',)' not found. 1 pattern(s) tried: ['(?P<id>[0-9]+)/$'] Since i get the results in form of json i don't have a problem with using it the way i did, but the problem rises when adding the a tag around my container div. I don't understand what course of action I should take since i'm not really experience with neither Django nor jQuery. -
Django + nginx + gunicorn not serving static files
Sorry for kind of repeating question, I know that similar questions has been asked before, but none of them helped to find solution. I am very new to whole web development thing and been struggling with this problem for couple of days now. My website do not show static files then I turn off debug mode. To my understanding that's why i should use nginx. I configured everything according to this guide. Following guide I put my static files into /opt/myenv/static/ directory. Done collectstatic command, created symbolic link (to my understanding), restarted nginx but still if I turn off debugging I see no static files served. My nginx config: server { server_name stvskaiciuokles.eu; access_log off; location /static { alias /opt/myenv/static/; } location /media { alias /opt/myenv/STV_skaiciuokle/skaiciuokle_web/media/; } location / { proxy_pass http://127.0.0.1:8001; proxy_set_header X-Forwarded_Host $server_name; proxy_set_header X-Real_IP $remote_addr; add_header P3P 'CP="ALL DSP COR PSAa PSDa OUR NOR ONL UNI COM NAV"'; } } My settings.py relevant part: STATIC_URL = '/static/' STATIC_ROOT = '/opt/myenv/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') Please help me determine what is wrong, since I cannot find any suitable solution despite reading multiple similar questions online? Guide I used is from 2013 maybe syntax changed a … -
django uwsgi - "No module named 'project'"
I'm trying to set up a Dockerised django/uwsgi stack. When I start the containers, uWSGI logs a "ModuleNotFoundError: No module named 'project'". I'm obviously doing something dumb, but I can't see what. Following the guide here, my dir tree looks like: mysite docker-compose.yml manage.py project __init__.py urls.py wsgi.py settings __init__.py base.py local.py The django docker container mounts the entire mysite dir as /mysite. My uwsgi INI file contains: chdir = /mysite/project module = project.wsgi:application env = DJANGO_SETTINGS_MODULE=project.settings.local (I've also tried with chdir = /mysite) What simple and obvious mistake am I making here? -
Foreign key issue in UserProfile django
I want to retrieve User profile data of User who is logged in. e.g. Based on logged in user I want to retrieve the country of the user from userprofile. Seems straightforward but I am missing some fine print. Tried a lot but no success. Need help. I tried and referred django document but I am a newbie I am having following model. class User(AbstractUser): username = models.CharField(max_length=100,blank=True, null=True) email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username', 'first_name', 'last_name'] def __str__(self): return "{}".format(self.email) class UserProfile(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE,) title = models.CharField(max_length=5) dob = models.DateField() address = models.CharField(max_length=255) country = models.CharField(max_length=50) city = models.CharField(max_length=50) zip = models.CharField(max_length=5) photo = models.ImageField(upload_to='uploads', blank=True) -
django - upload file to folder and show the current logged in username in the uploadform
I have a userprofile that captures the username and the group the user is assigned to. I want the uploaded files to be saved under the group name folder. The folders already exit at the media root, the files shoud be routed to these folder I solved the problem by the solution given. Now the username is shown as a dropdown list on the upload page. I want only the logged it username to be shown or exclude even showing it models.py class uploadmeta(models.Model): path = models.ForeignKey(Metadataform, on_delete=models.CASCADE) user_profile = models.ForeignKey(UserProfile, on_delete=models.CASCADE, null=True, verbose_name='Username') tar_gif = models.FileField(upload_to=nice_user_folder_upload, verbose_name="Dataset") # validators=[FileExtensionValidator(allowed_extensions=['tar', 'zip'])] def __str__(self): return self.request.user.username class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) Group= models.CharField(max_length=500, choices=Group_choices, default='Please Select') def __str__(self): return self.user.username view.py def uploaddata(request): if request.user.is_authenticated: if request.method == 'POST': form = uploadmetaform(request.POST, request.FILES) if form.is_valid(): form.save() return redirect('file_list') else: form = uploadmetaform() return render(request, 'uploaddata.html', { 'form': form }) else: return render(request, 'home.html') forms.py class uploadmetaform(forms.ModelForm): count = Metadataform.objects.all().latest('id').id #To know the id of latest object data = Metadataform.objects.all().filter(id=count) #return the queryset with only latest object path = forms.ModelChoiceField(queryset=data) def __init__(self, *args, **kwargs): super(uploadmetaform, self).__init__(*args, **kwargs) count = Metadataform.objects.all().latest('id').id data = Metadataform.objects.all().filter(id=count) self.fields['path'] = forms.ModelChoiceField(queryset=data) class Meta: model = uploadmeta … -
Making a Page in Django to render data from API?
I Have a problem statement where i have a RShiny Code and i have converted it into an API using Plumber . I want to create page in django which should take input from user and then hit that pi hosted and display the rendered JSON output from that api. Can anybody guide me what should i go forward to do this ? -
How to find area of Polygon intersection to annotate GeoDjango query?
In my model, I have a Polygon Field. In my query, I would like to compute the area of the intersection between this field, and a predetermined circle, in order to find the proportion of the circle's area that is recovered by my Polygon model field. Here is my model definition: class WDPA(models.Model): site_code = models.CharField(max_length=200, primary_key=True) site_name = models.CharField(max_length=300) iucn = models.IntegerField(default=0) geom = models.MultiPolygonField() Here is my query: tile = Tiles.objects.filter(start_long__gte=float(form.cleaned_data.get("latitude")), end_long__lte=float(form.cleaned_data.get("latitude")), start_lat__lte=float(form.cleaned_data.get("longitude")), end_lat__gte=float(form.cleaned_data.get("longitude")) )[0] tiles = [tile.tile_id, tile.near_0, tile.near_1, tile.near_2, tile.near_3, tile.near_4, tile.near_5, tile.near_6, tile.near_7] center = Point(float(form.cleaned_data.get("longitude")), float(form.cleaned_data.get("latitude")), srid=4326) circle = center.buffer(0.01802) zones = WDPA.objects.filter(tiles__in=tiles).annotate( distance=Distance('geom', center) ).order_by('distance').filter(distance__lte=2000).annotate( intersection=ExpressionWrapper(F('geom'), output_field=PolygonField()).intersection(circle).area ) But I can't call .intersection() method, it causes this error: AttributeError: 'ExpressionWrapper' object has no attribute 'intersection' I also tried to use an Intersection object, but I can't call the area either in my annotate. Does someomne as a solution please ? Thanks in advance