Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django + AWS s3 can upload files but not access them
Following this tutorial I set up our system to use Amazons S3 file storage using boto3 and Django-storages. I ran the collectstatic command and it worked just fine, the files show up in the AWS Management Console. But when running the server locally (runserver) all static files are missing. Looking at the console there are the error messages GET https://BUCKET.s3.eu-central-1.amazonaws.com/static/admin/css/nav_sidebar.css net::ERR_ABORTED 403 (Forbidden) for each of the files. The url looks right to me, the upload worked fine, but apparently the access doesn't work. Does this have something to do with my config in AWS? Or is this a django settings issue? -
Django - Certain Py Module doesn't work in IIS
This is my first time putting a question here. Some background, I started coding on Django this year and Python more than a year but less than 2 years so I don't much. This problem is a concern to my what I developing in at work. And my team working on it is novice or no experience on coding Python or Django or both. The Problem We have a web app based on Django 3.0.2 and use MSSQL for the db. Our company policy is to use Windows server and IIS as the prod and test server. We done a lot of work on it and all work well except for some python library and Django module that don't work, mainly Xlwings and Django-post-office. For XLwings, it doesn't run the code and Excel(we have valid license and latest Excel programme on the server). code below; filepath = BASE_DIR + '\\media\\Template.xlsm' temp_path = BASE_DIR + '\\media\\' + '{}.{}'.format(uuid4().hex, 'xlsm') shutil.copyfile(filepath, temp_path) pythoncom.CoInitialize() app1 = xw.App(visible=True) wt = xw.Book(temp_path) sht = wt.sheets['Cover'] sht.range('E5').value = request.POST.get('year') sht.range('E6').value = request.POST.get('company') sht.range('E7').value = companydata.employer_no sht.range('E8').value = email wt.save(temp_path) app1.quit() As for Django-post-office, we have module using it working but other modules using it doesn't work. … -
Django - What field or fields in model should I be indexing to speed up the following query?
What field or fields in model should I be indexing to speed up the following query? Query Subscriber.objects.filter(audience=audiencepk).order_by('-create_date') Models: class Subscriber(models.Model): first_name = models.CharField(max_length=15, blank=True) last_name = models.CharField(max_length=15, blank=True) audience = models.ForeignKey(Audience, on_delete=models.CASCADE) create_date = models.DateTimeField(auto_now_add=True) class Audience(models.Model): audience_name = models.CharField(max_length=50) create_date = models.DateTimeField() store = models.ForeignKey(Place, on_delete=models.CASCADE) -
django template rendering fail?
Variables are not rendered correctly by django my views dynasty_li=['a','b','c','d'd] html {% for d in dynasty_li %} {% if d == dynasty %} <a href="{% url 'poet_list' '{{ d }}' %}" class="active">{{ d }}</a> {% else %} <a href="{% url 'poet_list' '{{ d }}' %}">{{ d }}</a> {% endif %} {% endfor %} actual <a href="category/{d}">a</a> <a href="category/{b}">b</a> <a href="category/{c}" class="active">c</a> <a href="category/{d}">d</a> -
Where are my environment variables in Elastic Beanstalk for AL2?
I'm using elastic beanstalk to deploy a Django app. I'd like to SSH on the EC2 instance to execute some shell commands but the environment variables don't seem to be there. I specified them via the AWS GUI (configuration -> environment properties) and they seem to work during the boot up of my app. I tried activating and deactivating the virtual env via: source /var/app/venv/*/bin/activate Is there some environment (or script I can run) to access an environment with all the properties set? Otherwise, I'm hardly able to run any command like python3 manage.py ... since there is no settings module configured (I know how to specify it manually but my app needs around 7 variables to work). -
Image is not showing in Django on Heroku server
The images I'm uploading in the model are showing in the localhost but not working on the Heroku server. I'm already using the white noise, and staticfiles(CSS, js, and images) which is stored in static folder are working fine in both places (locally and on the server) the only problem is happening with images I uploaded in the model. Heroku logs "GET /media/product_image/pixel4a_8dq6jPP.jpeg HTTP/1.1" 404 771 "https://mobile-care.herokuapp.com/explore/" "Mozilla/5.0 (X11; Linux x86_64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/85.0.4183.121 Safari/537.36" models.py image = models.FileField(upload_to='product_image', urls.py urlpatterns = [...] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) HTML file {% for item in products %} <img src="{{item.image.url}}"> {% endfor %} I repeat I'm already using whitenoise and already initialized the MEDIA_ROOT and MEDIA_URL in settings.py. -
ModelNotFoundError in Django
For some reason, VS code doesn't recognize some standard external Django modules. I keep getting the ModelNotFoundError. When I try to run pip or pip3 install on for example django.contrib I'm getting the following error: ERROR: No matching distribution found for django.contrib I'm using VS Code on Windows 10. Would be awesome if someone could help me fix this problem. -
How to add a file upload progress bar with percentages in django and jquery
I want to create a file upload progress bar to my form, but am getting an error inside my console saying "jquery.min.js:4 POST http://localhost:8000/music/create/ 403 (Forbidden)" below is my code #Model class Song(models.Model): genre = models.ManyToManyField(Genre) #FORMS class SongCreateForm(forms.ModelForm): class Meta: model = Song fields = ['audio',] #VIEWS def songcreate(request): artist = Artist.objects.get(user=request.user) form = SongCreateForm() if request.method == "POST": form = SongCreateForm(request.POST or None, request.FILES) form.instance.artist = artist if form.is_valid(): form.save() return render(request, 'music/song_form.html', {'form':form}) #URLS path('music/create/', songcreate, name="song_create"), #TEMPLATE AND JQUERY <form action="/" method="post" enctype="multipart/form-data"> <legend><h3>Update</h3></legend> {% csrf_token %} {{ form|crispy }} <input type="submit" class="btn-block razo-btn" placeholder="upload"> </form> <script> $(document).on('submit', function(event){ event.preventDefault(); var formData = new FormData($('form')[0]); var csrf = $('input[name=csrfmiddlewaretoken]').val(); $.ajax({ xhr : function(){ var xhr = new window.XMLHttpRequest(); xhr.upload.addEventListener('progress', function(e){ if (e.lengthComputable) { console.log('Bytes loaded: ' + e.loaded); console.log('Total ' + e.total); console.log('Percetage uploaded ' + (e.loaded / e.total)); } }); return xhr; }, type : 'POST', url: '', data : { formData, csrfmiddlewaretoken:csrf }, processData : false, contentType : false, success : function() { alert('File uploaded'); } }); }); </script> -
Form automatically downloading data from the user's profile
I would like to create a function that will automatically retrieve data from a user's profile by clicking the save button. I want to create a platform on which a user can sign up for a tournament and I would like to do this in the purest and most intuitive way -
What the proper way of uploading an image in Django
I have a REST endpoint for creating certain resource, but now I want to add the functionality of uploading an image when creating the resource. What's the proper way of doing such feature? Do you need to upload the file separately then do another POST request for creating the resource? -
Django: multiprocessing: multiprocessing in a module with windows?
I am using multiprocessing inside one of my views.py #current module is someapp.views #current file is someapp.views.py from someapp.models import ModelA. ModelB getScore(args): --get some data from ModelA and ModelB based on args --do some calculation with the args and models return a value def Getsomedata(request): arg_instances = [..array of inputs] import multiprocessing pool = multiprocessing.Pool(4,initializer=subprocess_setup) results = pool.map(getScore, [ arg_instances ]) It keeps giving error Apps not loaded I tried def Getsomedata(request): if __name__ == "__main__": arg_instances = [..array of inputs] import multiprocessing pool = multiprocessing.Pool(4,initializer=subprocess_setup) results = pool.map(getScore, [ arg_instances ]) the if statement does not quality because __name__ = someapp.views HOw to run the multiprocessing -
How to url encode in Django views
In Django, I want to do this <a href="{% url 'firstapp:create' %}?next={{ nextos|urlencode }}"> but in my views.py, when I render a page return render(request, 'create' + parameter next=nextos) Any ideas? -
How can I get the full URL from my request argument? [duplicate]
I have a method that resolves a get request that looks like this: import json import json_api_doc import requests from django.conf import settings from django.core.cache import cache from django.utils import timezone from rest_framework.response import Response from rest_framework.views import APIView class MyClassAPIView(APIView): def get(self, request): foo = request.query_params.get('foo', '') # url = request.url <-- this does not work, but is what I'm trying to accomplish ... return {...} As you can see, I am able to get the query_params, but I would also like to get the full URL that is coming in. For example, this is the URL I am trying to read: https://example.com?foo=bar I have tried print(dir(request)) to see what is available, but not seeing anything related to path or url. I am successfully getting the query_param -- how can I get the full URL? -
Can we make an android app using django and briefcae packaging?
Can we make an android app using django and briefcae packaging? I mean use django as its gui framework and make an android apk installer using briefcase. -
Django Models (dynamic?)
I am just starting Django Website; I have deciced to go with a model (with SQLite DB), which have the following properties: class Flow(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE, verbose_name="Owner", default="ADMIN") source = models.CharField(default='HTTP', choices=SOURCE_CHOICES, editable=True, max_length=12) name = models.CharField(max_length=50, default=" ") date = models.DateTimeField(verbose_name="Creation date") I want to add others fields to this model depending on the source field value. For example if the source field : 'File' is selected. I will create additionnal field (like file name, file directory ...) If 'Http' is selected, I will create a field URL. Thus depending on the source field, I will have differents field and type. I have read this kind of model is difficult to reprensent in Django; I am open minded to other kind of solution. My idea was to created as many model as the possible source value. -
Invalid block tag on line 1: 'extend'. Did you forget to register or load this tag?
Invalid block tag on line 1: 'extend'. Did you forget to register or load this tag? My homepage code {% extend "mainApp/wrapper.html" %} {% block content %} <p> Darbibas parbaude! </p> {% endblock %} My wrapper code <!<!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta name = "viewport" content = "width = device-width, initial-scale = 1.0"> <meta http-equiv = "X-UA-Compatible" content = "ie=edge"> <title></title> </head> <body> <body style media = "background:silver"> {% block content %} {% endblock %} </body> </html> -
Django i18n translation after changing default language
I have two languages on the website - en and ru. When the project started, the default language was en. So, in the template I type something like {% trans 'Hello' %} and make translations only for ru in the locale folder. But now I have changed the default language to ru. And now the website was in ru even if the language is en because I haven't translated anything for en (it's already in en however). How to fix it? how to make it so that in the absence of translation i18n doesn't translate anything and shows just the text as it is? Thanks. -
How to insert two user chat data into firebase database using Django?
i am new in Firebase. i want to implement chat module in firebase using django.i want insert users chat into firebase according to image structure, here is the image as mentioned in image , all the messages of user number 30 are under entry number "30" . how to insert data in above formet? -
Django 3: Passing slug in URLs to views?
I'm trying out Django for a webshop, I'm following the instructions of a book(Django 3 by example), but there seem to be something missing. I have tested if return to home in def product_list seen in views.py, so I believe the problem is in the "if category_slug:" condition or it is not receiving the slug. In main urls.py: urlpatterns = [ path('admin/', admin.site.urls), path('', include('shop.urls', namespace='shop')), ] In app urls.py urlpatterns = [ path('', views.product_list, name='product_list'), path('<slug:category_slug>/', views.product_list, name='products_list_by_category'), path('<int:id>/<slug:slug>/', views.product_detail, name='product_detail'), ] In views.py: def product_list(request, category_slug=False): category = None categories = Category.objects.all() products = Product.objects.filter(available=True) if category_slug: category = get_object_or_404(Category, slug=category_slug) products = products.filter(category=category) return render(request, 'shop/product/list.html', {'category': category, 'categories': categories, 'products': products}) -
Can't perform migration on django 3, python 3, sqlite3
I run manage.py migrate on my django blog project and get this: (joelgoldstick.com) jcg@jcg-hp:~/code/p3/joelgoldstick.com/blog$ python manage.py migrate . . . django.db.utils.OperationalError: table "django_content_type" already exists During handling of the above exception, another exception occurred: . . . raise IntegrityError( django.db.utils.IntegrityError: The row in table 'blog_app_entry_categories' with primary key '8' has an invalid foreign key: blog_app_entry_categories.category_id contains a value '3' that does not have a corresponding value in blog_category.id. but the table blog_category contains a row with id = 3 -
Django project not start
Why my django project not start? django version - 1, path - 2 -
How to get data from a data base in Django
I want to create a car park app using Django and need to query the database for all carparks and then display this information on the app home page. Below is a models.py file. from django.db import models class Campus(models.Model): enter code herecampus_id = models.IntegerField(primary_key = True) enter code herename = models.CharField(max_length = 100) enter code heredef str(self): enter code hereenter code herereturn self.name class Carpark(models.Model): enter code herecarpark_id = models.IntegerField(primary_key = True) enter code herename = models.CharField(max_length = 100) enter code herecampus_id = models.ForeignKey(Campus,on_delete = models.CASCADE) enter code herespaces = models.IntegerField() enter code heredisabled_spaces = models.IntegerField() enter code heredef str(self): enter code hereenter code herereturn self.name -
How to delete Data from db by Datatable href delete button using django python
**I need to delete data from the data table please check my below code. kjndekjnkewjkjbwebewbrbkjewkjkjdkjfcbsdbndksjfhkhweiroiweoirjowjernkjm bmdsvmn mndsf dkjsfnkjdsnfkjkdsfkjdbskjfbwehrohoweijroiwej] lkfnewlklewjrjewiroijewoirjoierwhktbkjergtmnbermntbewnmbnmwebmnrbwemnrbmnwebrmnbwewenrbnmwebrmnewbnmr ** What i have to pass in htlm href tag *********Model.py ******* class Ownership(models.Model): ownrspid=models.AutoField Ownership_Type= models.CharField(max_length=20, default='') Desc= models.CharField(max_length=254, default='') def __str__(self): return self.Ownership_Type #*********views.py ******* def RemoveOnwer(request, id): if request.method == "POST": onwrid = int(request.POST.get('ownrspid')) onwr = Ownership.objects.get(id=onwrid) onwr.delete() messages.success(request, 'Ownership Type successfully deleted!') return redirect('/Add_Ownership') ownr = Ownership.objects.all() return render('Add_Ownership.html', {'ow': ownr}) *********urls.py ******* path('Add_Ownership', views.RemoveOnwer, name='Add_Ownership') *********Add_Ownership.html******* <tbody> {% if ow %} {% for j in ow %} <tr> <td>{{j.Ownership_Type}}</td> <td>{{j.Desc}}</td> <td class="text-right"> <a href="#" class="btn btn-link btn-info btn-just-icon like"><i class="material-icons">favorite</i></a> <a href="#" class="btn btn-link btn-warning btn-just-icon edit"><i class="material-icons">dvr</i></a> <a href="/RemoveOnwer/{{}}" class="btn btn-link btn-danger btn-just-icon remove" type="Submit" value="yes"><i class="material-icons">close</i></a> </td> </tr> {% endfor %} {% else %} NoData {% endif %} </tbody> -
Django migrate error for Oracle database table
I have created django project where following versions I have used. Python version 3.8.6 Django version 3.1.2 Oracle 11g I have run makemigrations which works all correct but mugrate commands give me error i.e django.db.migrations.exceptions.MigrationSchenaMissing: Unable to create the django_migrations tabel (ORA-02000: missing ALWAYS keyword) Database setting is following: > DATABASE = { 'default':{ 'ENGINE': 'django.db.backebds.oracle', > 'NAME': '10.1.5.87:1529/cdxlive', 'user': 'cisadm', 'PASSWORD': > 'cistechnology' } } Table I am creating is class Test(models.Model): name = models.CharField() score = models.CharField() -
Call different view function with empty url path , on same app (multiple empty url mapping to different view function)
This is my project urls.py urlpatterns = [ path('', include('index.urls'), name='index'), path('admin/', admin.site.urls), path('i18n/', include('django.conf.urls.i18n')), ] urlpatterns += i18n_patterns( path('terms-and-conditions/', include('index.urls', namespace='index'), name='terms'), ) this is my app's urls.py: urlpatterns = [ path('', views.index, name='index'), path('', views.terms, name='terms'), ] my goal is to have the main urls.py generate paths, without having to change the path inside my app's urls.py Example (desired behaviour): website.com/en/terms-and-conditions -> views.terms gets called website.com/ -> views.index gets called The following app's urls.py works: urlpatterns = [ path('', views.index, name='index'), path('terms/', views.terms, name='terms'), ] But now i get www.website.com -> maps to views.index (This is correct) www.website.com/en/terms-and-conditions/ -> maps to index as well. (not correct) and www.website.com/en/terms-and-conditions/terms -> maps to views.terms (NOT THE DESIRED URL) www.website.com/terms -> maps to views.terms (not desired, its redundant and maps to the same page as above) I could solve this by using an app for each page, but this seems very unnecessary as this is a simple website where i'd like to keep everything contained in one app. I started using django 3 or 4 days ago, so i am really at a loss on how to solve problems like these. Any help is very welcome . And i thank you …