Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django database error when running tests
I have been trying to solve a database related error for a long time which prevents me from running tests unless I disable migrations temporarily before launching the task. I am getting a ProgrammingError, specifically: django.db.utils.ProgrammingError: relation "django_facebook_open_graph_share" does not exist LINE 1: ...ango_facebook_open_graph_share"."created_at" FROM "django_fa... when running test someapp --verbosity=2. This is the displayed output: Creating test database for alias 'default' ('test_dbname')... Type 'yes' if you would like to try deleting the test database 'test_dbname', or 'no' to cancel: Got an error creating the test database: database "test_dbname" already exists yes Destroying old test database 'default'... Operations to perform: Synchronize unmigrated apps: app1, app2, app3 Apply all migrations: appx, appy, appz Synchronizing apps without migrations: Creating tables... Running deferred SQL... Installing custom SQL... Running migrations: Rendering model states... DONE Applying app1.0001_initial... OK ...many more lines line the one above... Applying appn.000x_someapp... OK Traceback (most recent call last): ..trace... django.db.utils.ProgrammingError: relation "django_facebook_open_graph_share" does not exist LINE 1: ...ango_facebook_open_graph_share"."created_at" FROM "django_fa... I am having trouble figuring out what migration is causing that error because the log doesn't point it out. I assume it is the one being executed right after appn.000x_someapp but it just doesn't say which one it is, so … -
How to allow access only for kubernetes pods in postgresql?
I have a Django app running in Kubernetes in GKE. And that django app connects to a static (non-containerized) postgresql server. As both of them are located in one zone, my django app uses internal IP to connect to database. I want only my django app to request a connection to the postgresql database and deny connection for requests coming from other IPs. To do that, in pg_hba.conf I did this: host all all 14.133.0.0/24 md5 Because all internal IPs start with 14.133. However, the requests are coming from pod IPs and thus requests for connection are denied. An example for a Pod IP can be 14.4.123.32. So, if I do the following in pg_hba.conf, the problem will be fixed: host all all 14.0.0.0/8 md5 Another thing to note is that Pod IPs always change. So, this solution will break once the pod is updated. What is the best practice to go about this? -
Test asc for arg which is self
Test should give 400 status code, but it ascs for self as argument, but isn't it a mistake? This is test: def test_cab_number_does_not_exist(self): data = {"cab_number": "0"} self.client = self.Client url = reverse('api:orders') response = self.client.post(url, data) response_content = json.loads(response.content) cab_number = response_content['cab_number'] self.assertEqual(response.status_code, 400) This function gives mistake like: TypeError: test_cab_number_does_not_exist() takes exactly 1 argument (0 given) . I don't know how to fix it. -
Celery is constantly starting with supervisor
How to run celery in Supervisor? This is my .conf file: [program:celery_worker] command=celery -A urlextractor worker -l info process_name=%(program_name)s ; process_name expr numprocs=1 directory=/home/omuntean/Django/urlextractor /urlextractor ; directory to cwd to before exec (def no cwd) autostart=true ; start at supervisord start (default: true) autorestart=unexpected ; when to restart if exited after running user=root stopasgroup=true stopsignal=QUIT stdout_logfile=/var/log/urlextractor /celery_w_out.log stderr_logfile=/var/log/urlextractor /celery_w_err.log priority=100 If I run the celery command normally it works fine without any errors, however, when I type: sudo service supervisor start Then see the status with: supervisorctl status It gives me: celery_worker RUNNING pid 10651, uptime 0:00:02 urlextractor RUNNING pid 9761, uptime 0:08:08 And then after I type again it gives me: celery_worker STARTING urlextractor RUNNING pid 9761, uptime 0:08:09 Why is this happening and how can I make it work? -
Organizing a one-to-one relationships for checksums
Django==1.11.6 I'd like to collect checksums for uploaded files. I have done it via GenericRelation. This is clumsy. Because it is one-to-many relationship whereas a checksum is definitely one-to-one. Could you help me understand whether this can be rewritten as a one-to-one relationship case? @receiver(post_save, sender=ItemFile) @receiver(post_save, sender=Image) def save_file_checksum(sender, instance, **kwargs): """ Save a ckecksum for a file. """ checksum = get_checksum(instance.file.path) existing_checksum = instance.checksum.first() if existing_checksum: existing_checksum.checksum = checksum existing_checksum.save() else: FileChecksum.objects.create(content_object=instance, checksum=checksum) class ItemFile(models.Model): file = models.FileField(blank=False, max_length=255, upload_to=get_item_path, verbose_name=_("file")) checksum = GenericRelation(FileChecksum) class Image(models.Model): file = models.ImageField(blank=False, verbose_name=_("Image"), max_length=255, upload_to=get_sheet_path) checksum = GenericRelation(FileChecksum) class FileChecksum(models.Model): content_type = models.ForeignKey(ContentType, on_delete=models.CASCADE) object_id = models.PositiveIntegerField() content_object = GenericForeignKey('content_type', 'object_id') checksum = models.CharField(blank=True, null=False, max_length=255, verbose_name=_("checksum")) def __str__(self): return "{} {}: {}".format(self.content_type, self.content_object, self.checksum) -
Running multiple instances of daphne behind a load balancer: django-channels
I am using django-channels to add HTTP2 & WebSocket support for my application. I could not find a lot of documentation as to how to scale channels. Below is my nginx configuration that load balances multiple instances of daphne running on the same machine but different ports. Is this the correct way to do it? upstream socket { least_conn; server 127.0.0.1:9000; server 127.0.0.1:9001; server 127.0.0.1:9002; server 127.0.0.1:9003; } server { listen 80; server_name 127.0.0.1; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { root /home/niscp/home-screen; } location /nicons/ { root /home/niscp/home-screen; } location / { include uwsgi_params; uwsgi_pass unix:/home/niscp/home-screen/home-screen.sock; } location /ws/ { proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_pass http://socket; } } Along with that, I am running individual instances of workers to listen to individual channels in the following manner: python manage.py runworker --only-channels=websocket.connect python manage.py runworker --only-channels=websocket.receive python manage.py runworker --only-channels=websocket.disconnect I have got uwsgi to handle all http requests the way django normally handles them. All daphne and workers do is handle WebSocket requests. Is this a viable method to scale django-channels, or is there something I could do better? -
'Authorization: Bearer token' vs 'Authorization: token' (Can't use Bearer header in Oauth2)
I'm using Oauth2. And somehow I can't attach Bearer header. It only work without Bearer Header. (But header Token header works) Is there any advantage of using Bearer? Should I use it? def get_queryset(self): # signing self.request.user header_token = self.request.META.get('HTTP_AUTHORIZATION', None) if header_token is not None: try: token = sub('Token ', '', self.request.META.get('HTTP_AUTHORIZATION', None)) token_obj = Token.objects.get(key = token) self.request.user = token_obj.user except Token.DoesNotExist: pass qs = Outfit.objects.all(user=self.request.user) return qs Can I do this with Bearer header? -
Leverage Browser caching django-nginx not working
I prepare a django project with server engine nginx using gunicorn for that. I am trying to work out page insights and I want to leverage browser caching in my nginx settings. My directory layout of project is: mainprojectfolder --mainproject ----static manage.py --media_cdn --static_cdn In my settings.py I arranged static files : STATIC_URL = '/static/' MEDIA_URL = '/media/' STATIC_ROOT = "/home/ytsejam/public_html/ozkansimple/static_cdn/" MEDIA_ROOT = "/home/ytsejam/public_html/ozkansimple/media_cdn/" My nginx settings are server { listen 80; server_name www.ozkandurakoglu.com; client_max_body_size 4G; root /home/ytsejam/public_html/ozkansimple/; access_log /home/ytsejam/public_html/ozkansimple/logs/nginx-access.log; location /static/ { autoindex on; alias /home/ytsejam/public_html/ozkansimple/ozkand/static/; } location /media/ { autoindex on; alias /home/ytsejam/public_html/ozkansimple/media_cdn/; expires 365d; } #location ~* \.(jpg|jpeg|png|gif|ico|css|js)$ { # expires 365d; # } } when I comment out cache , all my static and media files gets 404 and nothing is shown. can you help me ? Thanks -
Replacing image dynamically using jQuery
I'm trying implement a like button that changes color when clicked. I am trying to replace the image dynamically using jQuery. <div class = "col-sm-10" style = "margin-top: 2%"> <input style = "width : 4%; height: 4%" type = "image" id = {{schedule.id}} + "image" class = "likes" data-scheduleid = "{{schedule.id}}" data-user = "{{curruser.person.id}}" src = "{% static 'img/notliked2.png' %}"/> </div> This is image file that gets pressed as a button. Essentially, I am trying to change the image file on click. $(document).ready(function() { $('.likes').click(function(e){ var sched_id; var curruser; sched_id = $(this).attr("data-scheduleid"); curruser_id = $(this).attr("data-user"); $.get('/profiles/like_schedule/', {schedule_id: sched_id, current_user: curruser_id}, function(data){ var first = data.split("/") $('#' + sched_id).html(first[0]); console.log(first[1]) //$('#likes').html("<input style = 'width : 4%; height: 4%' type = 'image' id = {{schedule.id}} class = 'likes' data-scheduleid = '{{schedule.id}}' data-user = '{{curruser.person.id}}' src = {% static 'img/" + first[1] + "' %}/>"); $('.' + sched_id + "image").attr("src", "{% static 'img/" + first[1] + "' %}") e.preventDefault(); }); }); }); This is the jQuery. I logged first[1], and it is correct. It alternates between "notliked2.png" and "liked2.png" when someone likes and unlikes. But for some reason replacing the image source doesn't work. I even tried replacing the entire html, and it … -
Get the IP of the response hit by the requests library and even make it a bit faster in Django Python2.7
I am creating a django application where I have to scrape my profile for displaying purpose. The following is the views.py: url = 'my public profile' header = {'User-Agent': "Mozilla/5.0 (Windows NT 6.1; WOW64) AppleWebKit/537.36 (KHTML, like Gecko) " "Chrome/43.0.2357.134 Safari/537.36"} extract_profile = requests.get(url, headers=header) Here I have a guess that the scraping what I am trying is done through my server IP. I am not getting the idea to how I can make use of my my local IP for scraping the profile instead of my server IP? Also this process is taking a hell lot of time which is not good or my experiment. So I want to know what I need to improve to make it faster? kindly, let me know so I improve. -
https redirect custom domain google app engine
I have a custom domain in google app engine. I have all ok. Capture But when It do the redirection, it redirect to http domain, not https domain. If change the domain manually to https, it work. The domain is in google domain. -
Python-Neo4j Security error while connecting to database Failed to establish secure connection to '[SSL:UNKNOWN_PROTCOL(_ssl.c:600)
Im trying to connect the Django to Neo4j using neo4j-driver but I'm getting Security error. Error is :- neo4j.exceptions.SecurityError: Failed to establish secure connection to '[SSL: UNKNOWN_PROTOCOL] unknown protocol (_ssl.c:600)' Python Version 3.4.3 My Dependencies django1.9 neo4j-driver==1.4.0 CODE Views.py from django.shortcuts import render # Create your views here. from neo4j.v1 import GraphDatabase,basic_auth from django.conf import settings from django.db import IntegrityError from django.views.decorators.cache import cache_page from django.http import HttpResponse from django.contrib import messages from django.http import HttpResponse, HttpResponseRedirect, JsonResponse,Http404 from django.http import StreamingHttpResponse from django.shortcuts import render_to_response from django.shortcuts import render from django.template import RequestContext from django.views.decorators.csrf import csrf_exempt from django import template uri = "bolt://localhost:7474" driver = GraphDatabase.driver(uri, auth=("neo4j", "aditya369")) def friends(request): name = "Cameron Crowe" with driver.session() as session: with session.begin_transaction() as tx: for record in tx.run("MATCH (a:Person)-[:PRODUCED]->(f) " "WHERE a.name = {name} " "RETURN f.title", name=name): print(record["f.title"]) return render(request, "friends.html") Error The above exception was the direct cause of the following exception: Traceback (most recent call last): File "/Users/sskadit/Desktop/graphdb/src/lib/python3.4/site-packages/django/utils/autoreload.py", line 226, in wrapper fn(*args, **kwargs) File "/Users/sskadit/Desktop/graphdb/src/lib/python3.4/site-packages/django/core/management/commands/runserver.py", line 116, in inner_run self.check(display_num_errors=True) File "/Users/sskadit/Desktop/graphdb/src/lib/python3.4/site-packages/django/core/management/base.py", line 426, in check include_deployment_checks=include_deployment_checks, File "/Users/sskadit/Desktop/graphdb/src/lib/python3.4/site-packages/django/core/checks/registry.py", line 75, in run_checks new_errors = check(app_configs=app_configs) File "/Users/sskadit/Desktop/graphdb/src/lib/python3.4/site-packages/django/core/checks/urls.py", line 10, in check_url_config return check_resolver(resolver) File "/Users/sskadit/Desktop/graphdb/src/lib/python3.4/site-packages/django/core/checks/urls.py", … -
Changed JWT to OAuth2 and getting "Invalid token header. No credentials provided."
I decided to change my HTTP Authorization method from JWT to OAuth2. While testing my API with Postman, I'm getting same error for hours, "Invalid token header. No credentials provided." My header is Authorization: Bearer 416a444281fdcd6d2a344970eea0d47c22d01528 I don't see anything wrong in settings.py, but Do you see any? I commented out JWT setting just in case. INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'corsheaders', 'allauth', 'allauth.account', 'rest_auth.registration', 'rest_framework', 'rest_framework.authtoken', 'oauth2_provider', 'social_django', 'rest_framework_social_oauth2', 'rest_auth', ... 'allauth.socialaccount', 'storages', 'allauth.socialaccount.providers.facebook', ... ] # localhost:8000/ SITE_ID = 7 ACCOUNT_AUTHENTICATION_METHOD = 'username_email' ACCOUNT_EMAIL_VERIFICATION = 'none' SOCIALACCOUNT_EMAIL_VERIFICATION = 'none' REST_USE_JWT = False # for gmail EMAIL_USE_TLS = True EMAIL_HOST = ... EMAIL_HOST_USER = .. EMAIL_PORT = ... EMAIL_HOST_PASSWORD = ... EMAIL_BACKEND = ... DEFAULT_FROM_EMAIL = ... SERVER_EMAIL = ... LOGOUT_ON_PASSWORD_CHANGE = False OLD_PASSWORD_FIELD_ENABLED = True AUTHENTICATION_BACKENDS = ( # Oauth2 backends 'oauth2_provider.backends.OAuth2Backend', # Needed to login by username in Django admin, regardless of `allauth` 'django.contrib.auth.backends.ModelBackend', # `allauth` specific authentication methods, such as login by e-mail 'allauth.account.auth_backends.AuthenticationBackend', # Facebook OAuth2 'social_core.backends.facebook.FacebookAppOAuth2', 'social_core.backends.facebook.FacebookOAuth2', # django-rest-framework-social-oauth2 'rest_framework_social_oauth2.backends.DjangoOAuth2', ) MIDDLEWARE = [ # OAuth2 'django.contrib.auth.middleware.SessionAuthenticationMiddleware', 'oauth2_provider.middleware.OAuth2TokenMiddleware', 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] CORS_ORIGIN_WHITELIST = ( '10.0.2.2', 'localhost' ) ROOT_URLCONF = ... TEMPLATES = [ … -
Django QuerySet/Manager filter employees by age from birthday
I am a beginner. I would like to get list employees have age > 25 and calculate the average age of employees. Currently, we need to get age from birthday (I have no idea about it ^^) . Please help me create sample QuerySet/Manager about it. Thanks all :)) My model: class Employee(models.Model): """"Employee model""" first_name = models.CharField(max_length=30) last_name = models.CharField(max_length=30) birthday = models.DateField(max_length=8) -
Django model manager transaction and signal
# The model class UserManager(models.Manager): def create_user(self, temp_user_id): new_user = self.create(require data) # insert row to model B # The model manager class User(models.Model): # model fields objects = UserManager() # Post save signal handler def send_notification_to_user(sender, instance, created, **kwargs): # send sms notification to the newly created user signals.post_save.connect(send_notification_to_user, sender=User) # The view class UserView(APIView): def post(self, request, format=None): try: with transaction.atomic(): c_user = User.objects.create_user(request.data["temp_reg_id"]) return Response(status=status.HTTP_201_CREATED) except Exception as e: return Response(status=status.HTTP_400_BAD_REQUEST) In this scenario if a user registered then user get a sms. But here I'm running the model manager in transaction, so if somehow # insert row to model B instruction fails then all database will rollback. The problem is in this situation user will get the account creation sms, which is not true. How can I overcome this problem or which approach will be better? My English is not good, you can ask me for more explanation. -
django use spyne lib on apache server response no content
I have develop a webservice ,use spyne.protocol.soap.soap11. when running In django command (python manage runserver), it works as expected: 1.I can get wsdl file from $url?wsdl 2.call a webservice and get response but when deployed in apache server, it response $url?wsdl with status 200 OK but no content: "Connection →close Content-Length →0 Content-Type →text/xml; charset=utf-8 Date →Mon, 16 Oct 2017 02:22:08 GMT Server →Apache/2.2.15 (CentOS)" and I can also call a webservice, and the server do what i want(insert a data to database) but apache server response no content. note:all above running in the same machine, same python I have search in google and stackoverflow, but there is no similar questions. -
Django/AngularJS: How do I access my Python Context Items from my AngularJS Script
Good day SO! I am a beginner thats trying out a Django Project while using AngularJS for my frontend Firebase chat system. Here is a previous question that I asked regarding this project: Firebase/Angular: Messages not showing in HTML, but contain the message objects I know that it is not wise to use json variables on your html directly while using django/python, but it just so happens that my firebase chat module is using angularJS (and I do not know how to code this chat function in django..), and my angularJS code requires access to my Django's context querysets from View.py. Is there any way that I can either: Push json items into my HTML/Template the same way I push context information into my HTML/Template from Views.py and use it in my AngularJS Script? Access my Django/Python's data sets from Context from Views.py? Here is my AngularJS code for firebase: var app = angular.module('chatApp', ['firebase']); app.controller('ChatController', function($scope, $firebaseArray) { //I want to populate the crisis and sender variables with something from my context //from Views.py.. var crisis = "Crisis1"; var sender = "Sender1"; //Query var ref = firebase.database().ref().child(crisis).child('CMO-PMO'); $scope.messages = $firebaseArray(ref); $scope.send = function() { $scope.messages.$add({ sender: sender, message: $scope.messageText, … -
app.yaml username and password for django python on google app engine
How can i find the username, password and database for my app.yaml? "runtime: custom api_version: 1 vm: true env: flex entrypoint: gunicorn -b :$PORT main:app threadsafe: yes - url: .* script: test.wsgi.application runtime_config: python_version: 2 env_variables: # Replace user, password, database, and instance connection name with the values obtained # when configuring your Cloud SQL instance. SQLALCHEMY_DATABASE_URI: >- mysql+pymysql://USER:PASSWORD@/DATABASE?unix_socket=/cloudsql/intancesNAME beta_settings: cloud_sql_instances: intancesNAME " i am very new to GAE and django -
AttributeError at /notify/notify/ 'UserNotifications' object has no attribute 'user'
I am trying to make a notifications app. I have a middle that collects info about the action the user should be notified about and in the view that handles the action it automatically creates an instance in the UserNotification model. This is all working. Now, if a user's post gets liked by another user, that actions needs to be displayed on the notifications page. However, I obviously don't want any one use to be able to see every notification that is being created on the site, but rather only the notifications that are created by their posts. I am running into an issue with the view and filtering the notifications based on the current user. More specifically, I am getting this error: AttributeError at /notify/notify/ 'UserNotifications' object has no attribute 'user' With traceback: Traceback (most recent call last): File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/views/generic/base.py", line 68, in view return self.dispatch(request, *args, **kwargs) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/contrib/auth/mixins.py", line 56, in dispatch return super(LoginRequiredMixin, self).dispatch(request, *args, **kwargs) File "/anaconda3/envs/dev/lib/python3.6/site-packages/django/views/generic/base.py", line 88, in dispatch return handler(request, *args, **kwargs) … -
Migration urls in app ...has no Migration class
Why when I try to run migration I get "Migration urls in app *** has no Migration class"? I just added new app and thats it. Have no idea what direction to look > C:\Users\PAPA\DEV\liberty\lib\site-packages\django\db\models\__init__.py:55: > RemovedInDjango19Warning: The utilities in django.db.models.loading > are deprecated in favor of the new application loading system. from > . import loading > > Traceback (most recent call last): File "manage.py", line 22, in > <module> > execute_from_command_line(sys.argv) File "C:\Users\PAPA\DEV\liberty\lib\site-packages\django\core\management\__init__.py", > line 338, in execute_from_command_line > utility.execute() File "C:\Users\PAPA\DEV\liberty\lib\site-packages\django\core\management\__init__.py", > line 330, in execute > self.fetch_command(subcommand).run_from_argv(self.argv) File "C:\Users\PAPA\DEV\liberty\lib\site-packages\django\core\management\base.py", > line 390, in run_from_argv > self.execute(*args, **cmd_options) File "C:\Users\PAPA\DEV\liberty\lib\site-packages\django\core\management\base.py", > line 441, in execute > output = self.handle(*args, **options) File "C:\Users\PAPA\DEV\liberty\lib\site-packages\django\core\management\commands\makemigrations.py", > line 63, in handle > loader = MigrationLoader(None, ignore_no_migrations=True) File "C:\Users\PAPA\DEV\liberty\lib\site-packages\django\db\migrations\loader.py", > line 47, in __init__ > self.build_graph() File "C:\Users\PAPA\DEV\liberty\lib\site-packages\django\db\migrations\loader.py", > line 174, in build_graph > self.load_disk() File "C:\Users\PAPA\DEV\liberty\lib\site-packages\django\db\migrations\loader.py", > line 109, in load_disk > "Migration %s in app %s has no Migration class" % (migration_name, app_config.label) django.db.migrations.loader.BadMigrationError: > Migration urls in app expense has no Migration class -
Fixing this "Page not found (404)" error
I am attempting to access a page in my application but I keep getting this error : Page not found (404) Request Method: GET Request URL: http://127.0.0.1:8000/nesting/Identity-nest/%7B%25%20url%20'nesting:Symptoms_nest_list'%7D Using the URLconf defined in Identity.urls, Django tried these URL patterns, in this order: ^admin/ ^Identity/ ^nesting/ ^$[name='nesting'] ^nesting/ ^Identity-nest/$[name='Identity_nest_list'] ^nesting/ ^Symptoms-document/$[name='Symptoms_nest_list'] ^$ [name='login_redirect'] The current URL, nesting/Identity-nest/{% url 'nesting:Symptoms_nest_list'}, didn't match any of these. This is my main urls.py from django.conf.urls import url, include from django.contrib import admin from Identity import views urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^Identity/', include('Identities.urls', namespace = 'Identities')), url(r'^nesting/', include('nesting.urls', namespace = 'nesting')), url(r'^$', views.login_redirect, name = 'login_redirect'), ] This is my nesting urls.py from django.conf.urls import url from nesting.views import Identity_view, Identity_nest_list_view, Symptoms_document_view from . import views urlpatterns = [ url(r'^$', Identity_view.as_view(), name = 'nesting'), url(r'^Identity-nest/$', Identity_nest_list_view.as_view(), name = 'Identity_nest_list'), url(r'^Symptoms-document/$', Symptoms_document_view.as_view(), name = 'Symptoms_nest_list') ] This is my views.py class Symptoms_document_view(TemplateView): model = Symptoms template_name = 'nesting/Symptoms_list.html' def get(self, request): form = Symptom_Form() Symptoms_desc = Symptoms.objects.all() var = {'form':form, 'Symptoms_desc':Symptoms_desc} return render(request, self.template_name, var) def post(self, request): form = Symptom_Form(request.POST or None) Symptom_content = None if form.is_valid(): Symptoms_description = form.save(commit = False) Symptoms_description.user = request.user Symptoms_description.save() Symptoms_content = form.cleaned_data['Symptoms_description'] form = Symptom_Form() redirect('nesting:nesting') var = {'form': … -
How to initialize django objects automatically for the first time?
This is my first django application and I looked all over the place to find an answer, to no avail. I created my models and I know need to to initialize the values to one of the classes. I could do it using the admin page, one by one, but I want anyone using my application to be able to just load the application for the first time to have all the correct objects (and associated records in the database) to be created automatically. Please help -
Django: how to create a record that contains one or more items from a different db tables
I want to make a simple ticket system. I have 3 tables : Ticket, Responsible and Services .I also have the views that create, update and delete data to all 3 tables. what I am having problems is creating a view that creates the main ticket. My 3 tables are Ticket, Services and Responsible. my ticket can only have one responsible person and my ticket need to have one or more services. I'm lost on how to select multiple services to a ticket my models looks like this: from django.db import models from django.core.urlresolvers import reverse # Create your models here. class Servicios(models.Model): servicio = models.CharField(max_length=250) precio = models.FloatField() class Doctor(models.Model): nombre = models.CharField(max_length=250) porcentaje = models.FloatField() class Ticket(models.Model): fecha = models.DateTimeField(auto_now_add=True) servicio = models.ForeignKey(Servicios) doctor = models.ForeignKey(Doctor) cantidad = models.IntegerField() p_unitario = models.FloatField() total = models.FloatField() def get_absolute_url(self): return reverse('Main:get-list') -
I can't open manage.py
On the command prompt, (Windows 10) I created a virtual environment, I then created a new project, I installed django in the virtual environment using pip. Then decided to run the command python manage.py runserver To run djangos web server, This returned with "...can't open file 'manage.py': [Errno 2] No such file or directory" I did see a similar question to this on this platform but it seems to only apply to those using linux. Where answers specify to use the ls command, which is not applicable on Windows command prompt. I have tried this multiple times but i just can't open manage.py -
Django creates migration files after each 'makemigrations' because of dictionary?
I've noticed strange things in my Django project. Each time I run python manage.py makemigrations command new migration file for my app called notifications is created. I did zero changes to the model, but the new migration file is created. I can run makemigrations command N number of times and N number of migration files will be created. The model looks as following: from django.db import models from django.db.models.fields import EmailField class EmailLog(models.Model): email = models.EmailField(max_length=70, null=False) subject = models.CharField(max_length=255, null=False) html_body = models.TextField(null=False) sent_choices = { ('OK', 'Sent'), ('KO', 'Not sent'), ('KK', 'Unexpected problems') } status = models.CharField(max_length=2, choices=sent_choices, null=False, default='KO') sent_log = models.TextField(null=True) sent_date = models.DateTimeField(auto_now_add=True, null=False) Each migration just swaps the position of sent_choices field. that's all! Is it because dictionaries in Python have random order? How do I avoid it?