Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get the number of inserts from a raw INSERT query in Django?
I'm running a fairly large insert into select query in Django, which I do using MyModel.objects.raw(insert_query) But that doesn't do anything since queries seem to only be run when something is taken from it's result. So when I do this it runs the query MyModel.objects.raw(insert_query)[0] but also gives an error: TypeError: 'NoneType' object is not iterable Is there a way that I can run the raw query and get the number of records it inserted or a possible error if that occurred? -
What is the use of wsgi.py file that is there in django application when created using django-admin startproject
Can anyone help me in understanding what is the use of wsgi.py file? import os from django.core.wsgi import get_wsgi_application os.environ.setdefault("DJANGO_SETTINGS_MODULE", "myproject.settings.local") application = get_wsgi_application() -
I'd like to build a python code editor for my django project
Currently I have a Django project which is based on stocks. I would like include a code editor in my project. So, that users can write their own strategy in python. the user written code will be executed in the backed and populates the output. Is there any plugins or anything else for code editors? How can I achieve this? Thanks In Advance!! -
Migrate project from from Symfony 3 to Django
I have a project in Symfony 3 (SaSS application) relatively large monolith, about 5 years old with more than 150 entities and about 13GB of MySQL database. The truth is that for about a year I have been doing smaller projects in Django and have fallen in love for obvious reasons. Now, before my Symfony application continues to grow, I would like to separate the backend (Django -in process-) from the frontend (Vue-pending-) and I have some doubts about the migration process: I have created some models already in Django but I am not very clear on how to migrate the database so that both applications work on it, since during the duration of the migration process, the two applications will have to coexist in the same database. How would the process be so as not to lose information and that both applications coexist? Thank you -
I can't activate virtual environment
Python 3.7.4 Windows 10 I made new virtual environment P:\learning_log\env But It seems like I cant activate it with: P:\learning_log\env>Scripts\activate.bat Just because there no such file named activate.bat In Scripts I have only python.exe and pythonw.exe, I have already remade environment for more then 10 times, searched in Net, so can't solve it, help me pls -
Django - save copy of instance in inherited model
Using Django 2.1.5, I have one model that is completely inherited by another model. Both tables in DB. I want to save 'revisions' of the model as the inherited model. All fields should be the same at the time of the copy (including the id/pk). What's the right and quick way to copy the instance of the parent model to the inherited? Let's say these are the models (but with a lot of fields, foreign keys, json fields..): class MyModel(models.Model): id = models.UUIDField(default=uuid.uuid4, editable=False, db_index=True, unique=True, primary_key=True) identifier = models.IntegerField(default=-1) title = models.CharField(max_length=1000) revision = models.IntegerField(default=0) class MyModelRevisions(MyModel): pass Now, I want to take an instance of MyModel and completely copy it to MyModelRevisions. I thought of something like this: model_revision = MyModelRevisions(MyModel.objects.get(pk=my_model.pk)) model_revision.save() But I'm getting an error message saying that the title of my_model is not a valid UUID. -
Configure Nginx with two docker-compose containers (Flask and Django)
I am trying to expose two different address used like APIs. One in Django and the other one in Flask, they are Docker-compose containers. I need configure Nginx for expose the two containers in two different subdomains. It is my Nginx.conf: http { upstream app { server django:5000; } upstream app { server app:5090; } server { listen 5090; root /usr/share/nginx/html; location / { try_files $uri @app; } location @app { include uwsgi_params; uwsgi_pass flask:5090; } } server { listen 5000; charset utf-8; location / { try_files $uri @proxy_to_app; } location @proxy_to_app { ... } } } And my production.yml nginx: build: ./compose/production/nginx image: *image ports: - 80:80 depends_on: - flask - django My nginx.conf probably is wrong, if you know a documentation or a way for do it, please, answer me. -
Two orders being submitted after checkout
I am with an issue that after I submit a payment the order is being submitted twice. There are some cases that if I load the application for the first time in my device it will be charged once. However, since it is done more than once there will have more than one charge for the same order. # Create your views here. stripe.api_key = settings.STRIPE_SECRET @login_required() def checkout(request): if request.method == "POST": # call the two forms that will be used order_form = OrderForm(request.POST) payment_form = MakePaymentForm(request.POST) # Then will check if both forms are valid if yes, save if order_form.is_valid() and payment_form.is_valid(): order = order_form.save(commit=False) order.date = timezone.now() order.save() cart = request.session.get('cart', {}) total = 0 for id, quantity in cart.items(): destination = get_object_or_404(Destinations, pk=id) total += quantity * destination.price order_line_item = OrderLineItem( order=order, destination=destination, quantity=quantity ) order_line_item.save() try: customer = stripe.Charge.create( amount=int(total * 100), currency="EUR", description=request.user.email, card=payment_form.cleaned_data['stripe_id'], ) except stripe.error.CardError: messages.error(request, "Your card was declined!") if customer.paid: messages.error(request, "You have successfully paid") request.session['cart'] = {} #clear the cart in session return redirect(reverse('destination')) else: messages.error(request, "Unable to take payment") else: messages.error(request, "We were unable to take a payment with that card!") else: payment_form = MakePaymentForm() order_form = OrderForm() … -
django rest framework - model with string primary key
I'm trying to add Tag model to django rest framework. The model is extremaly simple: class Tag(models.Model): name = models.CharField(max_length=128, primary_key=True) as well as serializer: class TagSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Tag fields = '__all__' and view: class TagView(viewsets.ModelViewSet): queryset = Tag.objects.all() serializer_class = TagSerializer After that I can access a particular tag, for example http://127.0.0.1:8000/tag/SharePoint/ But I cannot list all of them: http://127.0.0.1:8000/tag Results in: Could not resolve URL for hyperlinked relationship using view name "tag-detail". You may have failed to include the related model in your API, or incorrectly configured the lookup_field attribute on this field. Do I have to add an id field to the model? -
Problem while deploying a Django app with Apache2 on Ubuntu
I've been trying to deploy a Django app on Ubuntu 18.04 using Apache2 for the past couple of days now, and it still doesn't work. My apache2 config is: <VirtualHost *:1337> <Directory /var/www/LGSM_webpanel/LGSM_webpanel> <Files wsgi.py> Require all granted </Files> </Directory> ErrorLog ${APACHE_LOG_DIR}/LGSM-error.log CustomLog ${APACHE_LOG_DIR}/LGSM-access.log combined WSGIScriptAlias / /var/www/LGSM_webpanel/LGSM_webpanel/wsgi.py WSGIDaemonProcess LGSM_webpanel python-path=/var/www/LGSM_webpanel WSGIprocessGroup LGSM_webpanel DocumentRoot /var/www </VirtualHost> However, for some reason, when I access http://localipofthemachine:1337 I just get the google chrome error Connection refused. Now, the server works when I use manage.py runserver, and I can fully access it, but when I use apache, I just get this error. The apache logs are also empty by the way. Thanks in advance for your help -
Get domain making request to my django application
I have a django view from which I would like to determine which domain is making a request to it. When I print(request.__dict__) inside the view, I see a bunch of information but nothing on the domain making the request to view. For example if a website www.okay.com is making a request to my django application, I would love to get the value inside my view, any idea on how I can retrieve this information would be much helpful. -
Django import export extended User
I'm trying to use django import export to import data in my app. Even with the documentation, I can't make it work for my "Proprietaire" Model, wich is extending django's user model. Here my models: class Proprietaire(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) adresse = models.CharField(max_length=500) telephone_regex = RegexValidator( regex="[0-9]{10}", message="Veuillez entrer un numéro de téléphone valide." ) telephone = models.CharField(validators=[telephone_regex], max_length=10) date_inscription = models.DateField(auto_now_add=True) The user import seems to be working fine but then I don't know how to import my Proprietaires and link them to my Users. Reading documentation I tried something like that in my admin file: class ProprietaireResource(ModelResource): class Meta: model = Proprietaire fields = ('user__username','telephone','adresse') import_id_fields = ('user__username') @admin.register(Proprietaire) class ProprietaireAdmin(ImportExportModelAdmin): resource_class = ProprietaireResource admin.site.unregister(User) @admin.register(User) class UserAdmin(ImportExportModelAdmin): pass But whatever I try (without import_id_fields or without fields, or with adrresse as import_id_fields...), I keep getting errors like: Traceback (most recent call last): File "C:\Users\perre\AppData\Local\Programs\Python\Python38\lib\site-packages\import_export\resources.py", line 500, in import_row instance, new = self.get_or_init_instance(instance_loader, row) File "C:\Users\perre\AppData\Local\Programs\Python\Python38\lib\site-packages\import_export\resources.py", line 277, in get_or_init_instance instance = self.get_instance(instance_loader, row) File "C:\Users\perre\AppData\Local\Programs\Python\Python38\lib\site-packages\import_export\resources.py", line 265, in get_instance import_id_fields = [ File "C:\Users\perre\AppData\Local\Programs\Python\Python38\lib\site-packages\import_export\resources.py", line 266, in <listcomp> self.fields[f] for f in self.get_import_id_fields() KeyError: 'a' I don't understand whats happening, can someone help me out? For … -
Django 3.0 server is automatically stops
Recently I started using django3, in this new version whenever I am try to access my admin panel, it stops automatically. But reset of the urls are working fine. Like if I go to 127.0.0.1:8000/api/ this url it will work fine but if I go to 127.0.0.1:8000/admin/ and type my username and password it automatically stops the server. I have tried many different project. But same problems occurs . -
React JS: POST to nested tables in a Django back end
I want to POST multiple nested tables in our backend. We have tried to do the POST in the one function but that didn't work. We keep getting an issue with the foreign keys and 400 BAD REQUEST issue with the Room table(The one everything is nested into). Here is the issue: IntegrityError at /dwelling/data/ insert or update on table "Dwelling_roomdata" violates foreign key constraint "Dwelling_roomdata_related_room_id_5388fced_fk_Dwelling_" DETAIL: Key (related_room_id)=(null) is not present in table "Dwelling_room". Here is the backend we want to post to: [ { "room_code": "ABC-XYZ_1", "related_dwelling": 4, "room_name": "Living Room", "data": [ { "related_room": "ABC-XYZ_1", "co2": "12.94,87.695,61.7,8.171,6.336,95.6,90.24,47.6,74.784,44.62,25.159,53.409,39.378,49.255,31.247,60.789,52.643,46.596,96.631,45.303,48.122,51.384,46.221,21.482,46.259,68.254,89.263", "humidity": "29.404,6.598,72.877,67.636,37.648,84.184,78.746,47.629,44.967,45.176,54.086,1.101,34.513,70.163,61.245,5.81,21.01,67.954,37.802,38.149,68.162,94.878,44.093,8.396,91.185,6.43,61.908,36.355,36.347", "temperature": "7.424,98.779,4.836,29.367,50.697,23.392,8.027,72.277,83.955,12.916,3.44,71.052,48.132,35.48,34.934,96.888,6.806,7.574,13.066,61.898,15.185,16.058,93.841,1.174,62.919,95.049,80.526,35.162" } ], "devices": [ { "device_code": "ABC-XYZ_1_1", "device_name": "Samsung Smart TV", "mac_address": "g2-h3-h4-j5-j6", "energy_used": 50, "state": false, "room": "ABC-XYZ_1" }, { "device_code": "ABC-XYZ_1_2", "device_name": "TV", "mac_address": "0", "energy_used": 0, "state": false, "room": "ABC-XYZ_1" } ], "suggestion": [ { "id": 1, "related_room": "ABC-XYZ_1", "suggestion": "Turn off the Lights" } ] } Here is the code we are trying to connect to the backend: class AddRoom extends Component { state = { modal: false, credentials: { room_code: 'ABC-XYZ_5', related_dwelling: '4', room_name: 'Connors Bedroom', data: { related_room: 'ABC-XYZ_5', co2: '0', humidity: '0', temperature: '0' }, devices:{ device_code: 'ABC-XYZ_5_1', device_name: … -
How to catch sql error in Django Rest Framework serializer?
I've got a Django Rest Framework endpoint to which an external party sends data in a fairly high volume. Because it was running about 200 inserts per second I checked the queries it was making. I found that it actually first did a SELECT query to check whether there was a duplicate id. Since I didn't think there would be any (or at least not many) duplicate keys I wanted to disable that check. So I added this line to my Serializer: id = serializers.UUIDField(validators=[]) # Disable the validators for the id, which improves performance (rps) by over 200% And as you can see in the comment, it greatly enhances the performance. However, one disadvantage of it is that it gives a 500 error if a duplicate key is in fact posted, saying duplicate key value violates unique constraint How would I be able to catch this Database error and returning a neat response instead of throwing this 500 error? -
Django + Celery. Lost connection to MySQL server during query
I have a Django app that run some chained tasks with celery. The first task asks an external app for it's DB dump, the second one downloads it and the third is the one that is giving me problems. First of all it unzips the dump through Popen, it takes like 30 minutes. After that it runs a sed command also through Popen that deletes a few tables that I won't use. This sed command takes like one hour Finally I run a Popen once more to restore the dump proc = Popen([ "mysql", "-h{}".format(settings.MYSQL_HOST), "-u{}".format(settings.MYSQL_USER), "-p{}".format(settings.MYSQL_PASSWORD), snapshot_restore.database_name ], stdout=PIPE, stderr=PIPE, stdin=sed_dumpfile) This process takes 8 hours approximately. Once the restore is finished it updates a django model in the DB, and that singal should triggers the next task. snapshot_restore = SnapshotRestore.objects.get(id=snapshot_restore_id) snapshot_restore.status = "processing" snapshot_restore.save() # Here I make the unzip, the sed and the restore snapshot_restore.status = "finished" snapshot_restore.database_status = "active" snapshot_restore.save() But here is when I have this error [2020-04-19 11:33:20,723: WARNING/ForkPoolWorker-2] File "/usr/local/lib/python3.6/site-packages/django/db/backends/mysql/base.py", line 266, in _set_autocommit self.connection.autocommit(autocommit) [2020-04-19 11:33:20,723: WARNING/ForkPoolWorker-2] File "/usr/local/lib/python3.6/site-packages/MySQLdb/connections.py", line 256, in autocommit _mysql.connection.autocommit(self, on) [2020-04-19 11:33:20,723: WARNING/ForkPoolWorker-2] _mysql_exceptions.OperationalError: (2013, 'Lost connection to MySQL server during query') [2020-04-19 11:33:20,723: WARNING/ForkPoolWorker-2] The above … -
How to get rid of additional image info (current image, clear checkbox) while rendering Django Form with Imagefield?
I have a model form containing Imagefield but when rendering, my template adds few additional info about current image (path), so it looks like this: Now: user1/Avatar.png Change: (Choose file...) I'd like to get rid of this "Now: ...", so it shows only the Choose file.. button. When in Profile model avatar field is set to null=True, blank=True, it also renders checkbox to clear the avatar, which isn't anything I'd like to have as well. models.py class Profile(models.Model): name = models.CharField(max_length=250) avatar = models.ImageField(upload_to=user_directory_path) forms.py class ProfileForm(forms.ModelForm): class Meta: model = Profile fields = ('name', 'avatar') template <section class="container"> <form action="." id="Form" enctype='multipart/form-data' method="POST"> {{ profile_form.as_p }} {% csrf_token %} <p> <input type="submit" value="Update!"/> </p> </form> </section> -
Docker-compose - How to populate a container data to another container?
My docker-compose file is as follows: version: '3' services: database: image: postgres restart: always environment: POSTGRES_PASSWORD: qwerty POSTGRES_USER: qwerty backend: depends_on: - database build: #Dockerfile used here will use python image,build the django project and run using uwsgi in port 4000 context: . dockerfile: dockerfile_uwsgi ports: - "4000:4000" image: backend_img environment: DB_HOST: database DB_NAME: qwerty DB_USER: qwerty DB_PASSWORD: qwerty migration: depends_on: - backend image: backend_img entrypoint: ["sh", "-c"] command: [" python manage.py collectstatic --noinput; python manage.py makemigrations; python manage.py migrate;"] environment: DB_HOST: database DB_NAME: qwerty DB_USER: qwerty DB_PASSWORD: qwerty frontend: depends_on: - backend build: #The dockerfile used her uses nginx image, it is configured to act as reverse proxy and serve static files. context: . dockerfile: dockerfile_nginx ports: - "9443:8443" Explaination about docker-compose.yaml: Here the backend container setups the django project and serves the project using uwsgi, using same image the migration container will collect the static files from all the app directories and populates it into the current working directory of the container. The frontend container is a nginx, which acts as reverse proxy. Also i would like to serve static files from nginx container. The issue im facing here is, i want to the static files which is … -
Why are browsers refusing to load my .js files and complaining about MIME types?
I'm trying to learn Django from a (very good) book. It's just got to the chapter where some Javascript is being added. I am not really a newb when it comes to Javascript. But I've hit the complete buffers with this. We are told to put these lines towards the end our Django template file base.html: <script src="/static/jquery-3.3.1.min.js"></script> <script src="/static/list.js"></script> <script> initialize(); // NB this is a simple function in the list.js script </script> All the browsers I've tried (Firefox, Chrome, Opera) fail to load these JS files. In the case of Chrome (console) I get Status 404 for these two files, whereas two .css files in the same directory get Status 200. In the case of FF (v. 72) the console messages are slightly more cryptic: for both files the console first gives a baffling MIME-related message: "The script from “http://localhost:8000/static/jquery-3.3.1.min.js” was loaded even though its MIME type (“text/html”) is not a valid JavaScript MIME type." and then immediately afterwards says "Loading failed for the with source “http://localhost:8000/static/jquery-3.3.1.min.js”." I have done quite a bit of searching to find out what might be going on. I have tried lines like this in the Django template file in question: <script type="text/javascript" … -
Installing latest version of GDAL with Dockerfile to deploy django app in gcloud
I'm trying to deploy my django app in gcloud, however it's failing to run due to the version (version 1.11.3) of GDAL that is being installed when I run the dockerfile, because I need to have GDAL version superior to 2 (according to what I've read about the error in other posts). I've seem similar issues with different suggestions, but I haven't been able to fix my problem. Any ideas what I could do? The error I get when running with the attached app.yaml and Dockerfile is the following: Updating service [default] (this may take several minutes)...failed. ERROR: (gcloud.app.deploy) Error Response: [9] Application startup error! Code: APP_CONTAINER_CRASHED [2020-04-19 17:56:40 +0000] [6] [INFO] Starting gunicorn 20.0.4 [2020-04-19 17:56:40 +0000] [6] [INFO] Listening at: http://0.0.0.0:8080 (6) [2020-04-19 17:56:40 +0000] [6] [INFO] Using worker: sync [2020-04-19 17:56:40 +0000] [9] [INFO] Booting worker with pid: 9 [2020-04-19 17:56:44 +0000] [9] [ERROR] Exception in worker process Traceback (most recent call last): File "/env/lib/python3.7/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker worker.init_process() File "/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line 119, in init_process self.load_wsgi() File "/env/lib/python3.7/site-packages/gunicorn/workers/base.py", line 144, in load_wsgi self.wsgi = self.app.wsgi() File "/env/lib/python3.7/site-packages/gunicorn/app/base.py", line 67, in wsgi self.callable = self.load() File "/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 49, in load return self.load_wsgiapp() File "/env/lib/python3.7/site-packages/gunicorn/app/wsgiapp.py", line 39, … -
How to use linebreak in Django templates
Hi I am new to python Django. I want new line in specific places, So I tried def abc(request): text = "This is\n a good example" return render(request, 'test.html', {'text' : text}) In HTML part Hello {{ text|linebreaks }} And this is working perfectly fine with output Hello This is a good example Here is my question I store some 400 - 800 words in my database which has approximately 4-5 paragraph. I want to new line here. So, I store data like "This is\n a good example" in my database. And simply call it in django template(Html side) but it prints Hello This is\n a good example In here why line break is not working? My HTML true code {% for essay in eassays %} {{ essay.description|linebreaks }} {% endfor %} I have changed name. Also, I am loading 100 such data. Any possible solution or other logic! Thankyou! -
How to open a project folder in Spyder IDE?
I am new to Spyder after VS Code and now want to open my Django project folder. I'm following these steps: Projects > New project > Existing directory > Create but Spyder opens some temp.py which after closing opens untitled0.py,untitled1.py,untitled2.py and so on. How can I see my project structure, files as in VS Code ? -
How can I use id as foreign key in django?
Product Model with fields Name, Description, Price Stock model with ProductID(foreignkey Reference), Name, Description, Price, Quantity -
Django Middleware is not able to process view functions correctly
I am trying to do login/logout using Django Middleware. I have gone through few tutorials but all are posted with old versions. I am trying to hardcode the except function inside middleware instead of having in setting.py as follow: middleware.py: EXEMPT_FUNC = ['Accounts:login', 'Accounts:logout', 'Accounts:register'] class LoginRequiredMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) return response def process_view(self, request, view_func, view_args, view_kwargs): assert hasattr(request, 'user') path = request.path_info.lstrip('/') url_is_exempt = any(url.match(path) for url in EXEMPT_FUNC) if path == reverse('Accounts:logout').lstrip('/'): logout(request) if request.user.is_authenticated() and url_is_exempt: return redirect('User:home') elif request.user.is_authenticated() or url_is_exempt: return None else: return redirect('Accounts:login') url.py: app_name = 'Accounts' urlpatterns = [ path('login', views.login_view, name='login'), path('logout', views.logout_view, name='logout'), path('register', views.register_view, name='register') ] Above code is not working as intended, please help on what am I doing wrong. Really appreciate your help. -
count same value in one column of database and display in template Django
I am having trouble to count same value in one column of database and display in template Django template image in template image {{bestofartists.0.artist_name}} gives 'Alessia Cara' and {{bestofartists.1.artist_name}} gives Coldplay database image now by seeing database image, i need to take that value 'Alessia Cara' again from template and do query to count total 'Alessia Cara' in 'album_artist' and display in same template, value is '2' as per image. can it be done in template only? sorry for long question. noob here. need help. thank you