django, python: reload function in shell – django, python: reload function in shell
I work in the django IPython-shell, which can be started with manage.py shell. When i load an extern function in the shell for testing, everything is alright. But when i make changes to the function, the shell still has the old version of the function. Even if i make a new import. I am working in the django IPython-shell and can start it using manage.py shell. When I load the extern function in the shell for testing, everything is fine. But when I make changes to the function, the shell still has the old version of the function. Even if I make a new import. Does anyone know how to reload the actual version of the function? Does anyone know how to reload the actual version of the function? Thanks in regards! Thank you! Edit: I use windows – if that makes a difference. Edit: I use Windows – if that makes a difference. 5 solutions #1 5 I reload the module by remove it from the the sys.modules and make a new import. I reloaded the module and made a new import by removing it from sys.modules. import sys sys.modules.pop(‘your.module’) import your.module #or from your.module import your_function #2 2…
Django, custom 404/500 when I return status_code404 or 500
I wrote custom 404/500 pages for a Django application that work fine except when a response with status code 500 or 404 is explicitly returned from my view. In the latter case I get whatever is returned in the response. I know I can render 404 and 500 templates in these responses, but is there a way to automatically use these 404/500 pages? To illustrate my problem: When the request is sent to ” http://my.host/pattern_not_matching_anything ” I get the 404.html page just fine. However, when an invalid request is received at http://my.host/valid_pattern/invalid_parameter “, that is, my view is called, I look for the parameter in the database and can’t find it, so I returned the appropriate response: return HttpResponse(“not found”, status_code=404) The HTML page returned contains only “Not Found”, whereas I want it to render my custom full 404 template. 1> Alasdair..: Instead of returning the response using status_code=404, you should raise a Http404Exception: from django.http import def my_view(request, slug): try: obj = MyModel.object.get(slug=slug) except MyModel.DoesNotExist: raise Http404 … This is a common pattern in Django, so you can use the get_object_or_404 shortcut instead. from django.shortcuts import get_object_or_404 def my_view(request, slug): obj = get_object_or_404(MyModel, slug=slug) … Status code 500 is…
Django,Create-react-app,Heroku
I have 3 folders in a Django web application. The folders are as follows: the folder containing settings.py (project), the folder containing models.py (application), and the folder containing the files created by create-react- The folder for the front-end react application created by app. I want to build a react frontend, copy the build artifacts to a static folder and then run the django app on heroku, but they are nearly impossible to accomplish with my current folder structure. Another way is to apply react The program flattens and uses build, src, node_modules, packagejson, etc. in the root of the project, but this looks really bad. Some configurations in settings.py: STATICFILES_DIRS = ( os.path.join(PROJECT_ROOT, ‘static’), os.path.join(BASE_DIR, ‘front-end/build/static’) ) What I’m running locally on the frontend: npm run build What I got back from the point of view: def index(request): return HttpResponse(loader.get_template(‘build/index.html’).render()) #above line returns index.html that is generated by npm run build How do I deploy the above project to Heroku so that it can find all static resources?
Django, Python inheritance: exclude some fields from superclass
I have inheritance between Employee and Manager classes. Employee – super class, Manager – subclass. class Employee(models.Model): ### name = models.CharField(max_length=50, null=False) address = models.CharField(max_length=50, null=False) ### class Manager(Employee): department = models.CharField(max_length=50) ### here I don’t want the ‘name’ and ‘address’ fields of Employee class. (I want other fields of Employee and department field of this class to be stored in Manager table in database) ### How can this be achieved. Thanks in advance. 1> Emin Mastiza..: You can use 2 underscore Python classes Private variables (__), check this example for more. However, they will store the value in the sub-object because there is nothing private or protected in Python. But another approach can work for Django. In Django model fields will be stored as per their value (CharField, DateField etc.) but if you will make item value None or any other static value (e.g., “string”), this should solve your problem: class Manager(Employee): name=None address=None # other_stuffs. In the example, Manager should not have name and address columns in the database, and when you try to access them you will get None. And if you want to get an AttributeError (which Django raises when the object doesn’t request a key),…
Deploy to docker using nginx, django, daphne
1> Neil Twist..: TLDR; Nginx is not configured correctly, but your docker-compose still needs some fixes: Nginx The Nginx website has some useful tips for deploying with Docker that you should read, including a sample, very simple Dockerfile: FROM nginx RUN rm /etc/nginx/conf.d/default.conf RUN rm /etc/nginx/conf.d/example_ssl.conf COPY content /usr/share/nginx/html COPY conf /etc/nginx This indicates that you need to make some improvements (see the Docker Compose section for more help with Docker). Considering the deployment updates we will make below, you will also need to change the Nginx configuration: Rename service.conf->service.template Change listen ${NGINX_PORT}; Change server_name ${NGINX_HOST}; Change proxy_pass http://${DAPHNE_HOST}:${DAPHNE_PORT}; Written by Docker Now that your Nginx configuration is correct, you need to set up the docker compose directive correctly. Thankfully, the Docker Hub Nginx page has a docker compose example: The following is an example using docker-compose.yml: web: image: nginx volumes: – ./mysite.template:/etc/nginx/conf.d/mysite.template ports: – “8080:80” environment: – NGINX_HOST=foobar.com – NGINX_PORT=80 command: /bin/bash -c “envsubst /etc/nginx/conf.d/default.conf && nginx -g ‘daemon off;'” Then the mysite.template file may contain variable references like this: listen ${NGINX_PORT}; Answer from r00m You can make all these improvements, in fact, without sharing the volume, your static files will not be served correctly. Create an image for…
django,pyenv,uwsgi-ModuleNotFoundError: No module named ‘django’
I have the following vassal configuration/etc/uwsgi/vassals/gsd.ini: [uwsgi] plugins=python env = DJANGO_SETTINGS_MODULE=%n.settings virtualenv = /home/toogy/.pyenv/versions/%n chdir = /home/webapps/%n module = %n.wsgi:application master = true vacuum=true pidfile = /tmp/uwsgi-%n.pid socket = /tmp/uwsgi-%n.sock daemOnize= /var/log/uwsgi/%n.log chmod-socket=666 uid=toogy gid = toogy This is the uwsgi log I got Tue Feb 7 10:49:12 2017 – received message 1 from emperor …gracefully killing workers… Gracefully killing worker 1 (pid: 31406)… worker 1 buried after 1 seconds binary reloading uWSGI… chdir() to /etc/uwsgi/vassals closing all non-uwsgi socket fds > 2 (max_fd = 1024)… found fd 3 mapped to socket 0 (/tmp/uwsgi-gsd.sock) running /usr/bin/uwsgi *** has_emperor mode detected (fd: 7) *** [uWSGI] getting INI configuration from gsd.ini *** Starting uWSGI 2.0.14 (64bit) on [Tue Feb 7 10:49:13 2017] *** compiled with version: 6.3.1 20170109 on 18 January 2017 00:35:47 os: Linux-3.14.32-xxxx-grs-ipv6-64 #7 SMP Wed Jan 27 18:05:09 CET 2016 nodename: renard machine: x86_64 clock source: unix pcre jit disabled detected number of CPU cores: 4 current working directory: /etc/uwsgi/vassals detected binary path: /usr/bin/uwsgi chdir() to /home/webapps/gsd your processes number limit is 15700 your memory page size is 4096 bytes detected max file descriptor number: 1024 lock engine: pthread robust mutexes thunder lock: disabled (you can enable it with…
Django, security and settings
From here, we add all database information as text: DATABASES = { ‘default’: { ‘ENGINE’: ‘django.db.backends.postgresql’, ‘NAME’: ‘mydatabase’, ‘USER’: ‘mydatabaseuser’, ‘PASSWORD’: ‘mypassword’, ‘HOST’: ‘127.0.0.1’, ‘PORT’: ‘5432’, } } Is this a safe method? Is there any way to save this data as encrypted data? 1> Sayse..: This is insecure and anyone with access to your source control now has access your database. The two main ways to store sensitive data are using environment variables or through json files Excerpted from Settings – Hide secret data using JSON files. The original authors are Antoine Pinsard and Fredley. Attribution details can be found on the contributors page. This source is licensed under CC BY-SA 3.0 and can be found in the Documentation archive. Reference topic ID: 942 and example ID: 8734. Use JSON files to hide secret data When using a VCS like Git or SVN, certain confidential data must never be version controlled (regardless of whether the repository is public or private). In this data you can find the SECRET_KEY setting and database password. A common way to hide these settings from version control is to create a secrets.json file in the root of the project (thanks to Django ” Two…
How does django use mysql database to query the database_Mysql database usage (Django), mysql, usage, django
One-to-many: Many-party definition foreign key!! # Student model class class Student( AbstractUser): mobile = models.CharField(max_length=11, unique=True, verbose_name='Mobile phone number') cid = models.ForeignKey(to=”Class”, to_field=”id”) class Meta: db_table = 'tb_student' verbose_name = 'user' verbose_name_plural = verbose_name # Class Model Class class Class(models.Model): id = models.AutoField(primary_key=True) cname &# 61; models.CharField(max_length=32) cdata = models.DateField() Implementing many-to-one in django When specifying , the usage is as follows: st = Student( username=student_name, password=password, cid=cl # cl is an instance of Class class ) In progress When searching : # One-to-many/many-to-one cl = Banji.objects.get(id& #61;3) tea = cl.student_set.all()[0] print(tea) print(cl.student_set .first()) st = Student.objects.get(username='fenghua') print(st.cid_id) print(st.cid.cname) Related query 1. Forward search (check more than 1): Get through the foreign key of the model class (here is cid) st.cid_id Find the class id corresponding to the student There is a field to_field=id when multiple parties define foreign keys in the model st.cid.cname Find the class name corresponding to the student 2. Reverse search (1 check more): If related_name is not set in the foreign key field& #xff0c;By default, the multi-party model lowercase _set is used. If related_name=”students”, is set, students can be used directly for reverse query cl (assumed to be a class object) cl.Model name lower case_set.first()…
django, squash migrations, too many circular dependencies – django, squash migrations, too many circular dependencies
I tried to squash migrations. I tried to suppress the migration. Unfortunately there are just too many circular dependencies. Unfortunately, there are too many circular dependencies. Is there a way to start over the migrations (although my project is already deployed in production) than trying to squash the migrations? Is there a way to restart the migration (although my project is already deployed in production) instead of trying to squash the migration? I don’t have to worry about some unknown developer using my project because it’s a private project. I don’t have to worry about some unknown developer using my project because it’s a private project. 1 solution #1 11 Yes, there is a way. See this similar question. In a nusthell: Yes, there is a way. Saw this similar question. In a nutthell: # 1) Fake migrations back to 0 ./manage.py migrate app zero –fake # 2) Delete migrations files git rm “app/migrations/*” # 3) Create new migration file ./manage.py makemigrations app # 4) Pretend to run the new migration ./manage.py migrate app –fake
Django, Ajaxurl not found in js file – Django, Ajaxurlnotfoundinjsfile
I’m making the website using django, python and Javascript. I get an error ‘Not found: /schedule/{% url ‘schedule_delete’ %}’ when I use the ajax in js file I used django, python and Javascript to create this website. When I use ajax in a js file, I receive an error “Not found:/schedule/{% url” schedule_delete’ %} fullcalendar.js fullcalendar.js function eventElementHandlers(event, eventElement) { eventElement .click(function(ev) { var start = event.start; var id = event.id; var title = event.title; var allData = {‘csrfmiddlewaretoken’: ‘{{ csrf_token }}’, “id”:id, “start”:start, “title”:title}; $.ajax({ url: “{% url ‘schedule_delete’ %}”, type: “POST”, data: allData, dataType: “json”, success: function(response){ alert(“success!”); $(‘#used_session’+id).html(response.used_session); }, error:function(error){ alert(“fail!”); } }); } urls.py urls .py from django.conf.urls import url from .import views urlpatterns=[ url(r’^$’, views.home, name=’home’), url(r’^schedule_delete/$’, views.schedule_delete, name=’schedule_delete’), ] I also made schedule_delete in views.py. I also created schedule_delete in views.py. Why url is wrong?? The same url format was okay in the other template. Is url format different depending on the django template or js file?? Why is the address wrong? In other templates, the same url format is OK. Is the url foramt different depending on the django template or js file? Any help will be very helpful to me, thanks! Any…