Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Succesful migrations and migrate but "ProgrammingError: relation "Patient" does not exist LINE 1: ..." while trying to populate data
I have created a custom User model and have two models "Staff" and "Patient" having OneToOne relationship with my custom User model. I have successfully migrate but when I tried python populate_health.py , I get this ERROR: "django.db.utils.ProgrammingError: relation "Patient" does not exist LINE 1: ...el_no", "Patient"."address", "Patient"."NIN" FROM "Patient" ..." models.py class User(AbstractUser): #use email as authentication username = None email = models.EmailField(_('email address'), unique=True) USERNAME_FIELD = 'email' REQUIRED_FIELDS = [] objects = CustomUserManager() USER_TYPE_CHOICES = ( (1, 'doctor'), (2, 'labPeople'), (3, 'receptionist'), (4, 'patient'), (5, 'admin'), ) user_type = models.PositiveSmallIntegerField(choices=USER_TYPE_CHOICES,null=True) def __str__(self): return self.email # class Meta: # db_table = 'auth_user' class Staff(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,related_name='staff') id = models.AutoField(db_column='ID', primary_key=True) # Field name made lowercase. fname = models.CharField(max_length=255, blank=True, null=True) lname = models.CharField(max_length=255, blank=True, null=True) sex = models.BooleanField(blank=True, null=True) tel_no = models.CharField(max_length=255, blank=True, null=True) email = models.EmailField(max_length=255,unique=True) department = models.ForeignKey('Department', on_delete=models.CASCADE, db_column='department', blank=True, null=True) hospital = models.ForeignKey('Hospital', on_delete=models.CASCADE, db_column='hospital', blank=True, null=True) class Meta: # managed = False db_table = 'Staff' class Patient(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE,related_name='patient') email = models.EmailField(max_length=255,unique=True) fname = models.CharField(max_length=255, blank=True, null=True) lname = models.CharField(max_length=255, blank=True, null=True) dob = models.DateField(db_column='DOB', blank=True, null=True) # Field name made lowercase. sex = models.BooleanField(blank=True, null=True) tel_no = models.CharField(max_length=255,blank=True,null=True) address … -
Add javascript to django admin change form
I'm trying to add the following https://github.com/ubilabs/geocomplete to a textbox on the admin pages in django that add/edit models. I'm unable to find out how I add the necessary scripts as said in the README, how to I add javascript to the admin pages? Some other similar solutions have not worked. -
Bootstrap Modal Not Submitting/Redirecting in Django
I have a bootstrap modal - it renders fine and submits fine, but when I change the url I would like for it to use when a user submits the form, it no longer submits. It also does not redirect to the url I want to use. views.py #view for the modal class ManifestUpdate(BSModalUpdateView): model = Manifests template_name = 'manifest_update.html' form_class = UpdateManifestForm success_message = 'Success: Manifest was updated.' success_url = reverse_lazy('manifest') #when this is set to 'index' it works fine #view I would like to land on when form is submitted def manifest(request): form = CreateManifestForm(request.POST) if request.method == "POST": if form.is_valid(): form.save() return redirect('manifest') else: reference_id = request.POST.get('Reference_Nos') data = Manifests.objects.all().filter(reference__reference=reference_id) form = CreateManifestForm(initial={ 'reference': Orders.objects.get(reference=reference_id), }) total_cases = Manifests.objects.filter(reference__reference=reference_id).aggregate(Sum('cases')) context = { 'reference_id': reference_id, 'form': form, 'data': data, 'total_cases': total_cases['cases__sum'], } return render(request, 'manifest_readonly.html', context) manifest_readonly.html #html file for page I am launching the modal from, as well as the one I would like to land back on <div class="container"> <div class="col-xs-12"> {% if messages %} {% for message in messages %} <div class="alert alert-success" role="alert"> <center>{{ message }}</center> </div> {% endfor %} {% endif %} </div> </div> <div class="container"> <form id="create_mani_form" method="POST"> <br> <br> <br> {% … -
User Acccount (login, logout, sign in, vv...) get error 500 when i get DEBUG = False
When I set DEBUG = False. User Account get Error 500. I done try fix it. But hopeless. Help me thanks. This is my setting.py file. """ Django settings for locallibrary project. Generated by 'django-admin startproject' using Django 2.2.1. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! # SECRET_KEY = '-ofza@cbrd#bn^ean07*0f7u1pkgy#4f(*uzb%y_j@pdx0nysd' SECRET_KEY = os.environ.get('DJANGO_SECRET_KEY', '-ofza@cbrd#bn^ean07*0f7u1pkgy#4f(*uzb%y_j@pdx0nysd') # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = ['*', 'localhost', '127.0.0.1'] # Application definition INSTALLED_APPS = [ 'widget_tweaks', 'rest_framework', 'crispy_forms', 'catalog.apps.CatalogConfig', 'django.contrib.admin', 'django.contrib.auth', # Core authentication framework and its default models. 'django.contrib.contenttypes', # Django content type system (allows permissions to be associated with models). 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] AUTH_USER_MODEL = 'catalog.CustomUser' MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'whitenoise.middleware.WhiteNoiseMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', # Manages sessions across requests 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', # Associates users with requests using sessions. 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Store.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [ os.path.join(BASE_DIR, "templates") … -
Image files no longer appear in production how to fix the problem
Before anyone can tell me how to put the other question solved? Hello local site works well, but in Heroku the picture is not displayed anymore In production the static files are at the same level as the folder of the images according to the logging that's what breaks the problem thank you for your help. -
Query model for objects that do not have an associated child object
I am trying to display summary information about child objects, and about child objects that do and do not contain grandchild objects. Two of the three work, but not very well. I am not able to get a result set at all looking for child objects that do contain grandchild objects, though the result for objects that do not contain grandchild objects works. My models are Campaign, Lead, and leadQA. Models (relevant) class Campaign(models.Model): id = models.IntegerField(primary_key=True, unique=True) class Lead(models.Model): campaign = models.ForeignKey(Campaign, on_delete=models.CASCADE) class LeadQA(models.Model): lead = models.ForeignKey(Lead, on_delete=models.CASCADE) Views (relevant) lead_count_with_qa = list(Lead.objects.filter(campaign__id=pk, leadqa__lead=True).values_list('cid').annotate(Count('id'))) lead_count_without_qa = list(Lead.objects.filter(campaign__id=pk, leadqa=None).values_list('cid').annotate(Count('id'))) lead_qa_count = list(LeadQA.objects.filter(lead__campaign__id=pk).values_list('qa_status').annotate(Count('id'))) I get only an empty list for lead_count_with_qa. I've tried multiple permutations, and there are definitely related leadQA objects that have that object as the foreign key. -
Python social auth "AuthForbidden"
I am trying to get google authentication working with django using social-auth and I haven't had any luck as of yet. Other questions with similar error messages suggest that it could be caused by whitelisting, but I'd like to accept all gmail suffixes in my app. (no whitelist required) INSTALLED_APPS = [ 'livereload', # TODO Remove when finished 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'dashboard.apps.DashboardConfig', 'user.apps.UserConfig', 'social_django' ] Both 'social_django.context_processors.backends' and 'social_django.context_processors.login_redirect' are in my context processors in settings.py. AUTHENTICATION_BACKENDS = ( 'social_core.backends.open_id.OpenIdAuth', # for Google authentication 'social_core.backends.google.GoogleOpenId', # for Google authentication 'social_core.backends.google.GoogleOAuth2', # for Google authentication 'django.contrib.auth.backends.ModelBackend', ) urlpatterns = [ path('dashboard/', include("dashboard.urls", namespace="dashboard")), path('admin/', admin.site.urls), path('login/', auth_views.LoginView.as_view(), name="login"), path('logout/', auth_views.LogoutView.as_view(), name="logout"), path('auth/', include("social_django.urls", namespace="social")), ] When I sign in with google and am redirected to my auth url, I get the message: AuthForbidden at /auth/complete/google-oauth2/ Your credentials aren't allowed How do I get this to work properly? -
Cannot make requests to APIs without auth token after added "WSGIPassAuthorization On"
We had a issue after deploying Django to AWS. The problem is that We cannot make requests to the APIs whose permission classes is set to "IsAuthenticated", even if we put the auth token in the header. permission_classes = (IsAuthenticated,) We can only make requests to the API whose permission_classes is set to "Allowany" After reading this post Authentication credentials were not provided. when deployed to AWS, We have figured out that it was the authorization header did not pass through. after we used the following command: 01_wsgipass: command: 'echo "WSGIPassAuthorization On" >> ../wsgi.conf' The exact opposite thing happended. The auth token somehow become mandantory. We can make request with auth token in the header only to the API whose permission classes is set to "IsAuthenticated". Making requests to the APIs with permission_classes set to "Allowany" returns 401. How do we fix it? Thanks in advance. -
How to host multiple site in single droplet
I just hosted my website on the digital ocean by following below link. https://www.digitalocean.com/community/tutorials/how-to-set-up-django-with-postgres-nginx-and-gunicorn-on-ubuntu-18-04 It works like a charm. But i also want to host multiple site on the single drop let. I've no idea that how to host multiple site on the single droplet. Does name matters while creating gunicorn service file and socket file. I mean do I need to create separate service and socket file for separate project and also do i need to create separate sock file for separate project. -
.env reload with django-environ on uwsgi
I really need some punch. I do have fully setup and running project. Django, nginx, supervisor, uwsgi - emperor with touch reload enabled. # {{ ansible_managed }} [Unit] Description=uWSGI Emperor service [Service] ExecStartPre=/bin/bash -c 'mkdir -p /run/uwsgi; chown {{ deploy_user }}:{{ deploy_group }} /run/uwsgi' ExecStart=/bin/bash -c '{{ uwsgi_path }}/uwsgi --emperor /etc/uwsgi/vassals' Restart=always KillSignal=SIGQUIT Type=notify NotifyAccess=all [Install] WantedBy=multi-user.target uwsgi.ini # {{ ansible_managed }} [uwsgi] project = {{ project_name }} uid = {{ deploy_user }} gid = {{ deploy_group }} base = /home/%(uid) chdir = %(base)/www/{{ project_url }}/%(project) home = %(base)/.pyenv/versions/%(project) module = config.wsgi ;logto = /tmp/uwsgi.log master = true processes = 10 harakiri = 30 socket = /run/uwsgi/%(project).sock chown-socket = %(uid):%(gid) chmod-socket = 660 vacuum = true touch-reload = {{ project_path }}/{{ project_name }}.touch LANG=en_US.UTF-8 env = DJANGO_READ_DOT_ENV_FILE=True ;todo version for prod env = DJANGO_SETTINGS_MODULE=config.settings.{{ version }} when I make changes and touch file, it reloads everything as should, project running perfectly. But I do have an issue with .env file. django settings.py import environ ... env = environ.Env( # set casting, default value DEBUG=(bool, False) ) # reading .env file env.read_env(str(ROOT_DIR.path('.env'))) If I change something in .env file and upload it to the server, touch wsgi file, it does not … -
Django Channels Adding (Different Communicator) User to Group
I am writing a web-application using websockets from django-channels. In which: Customer users can make orders from store users. When a user requests an order via their communicator, I create a channel group using the order's id. The store related to this order should be added to this channel group as well. This is what I'm struggling to achieve. This logic can be seen in my pytest below: async def test_store_is_added_to_order_group_on_create(self, settings): customer = await create_customer() store = await create_store() product = await create_product(store=store) store_communicator = await auth_connect(store) # Log in as customer and create order customer_communicator = await auth_connect(user) await communicator.send_json_to({ 'type': 'create.order', 'data': { 'product': str(product.id), 'customer': user.id } }) response = await communicator.receive_json_from() data = response.get('data') await communicator.disconnect() # Send JSON message to new order's group. order_id = data['id'] message = { 'type': 'echo.message', 'data': 'This is a test message.' } channel_layer = get_channel_layer() await channel_layer.group_send(order_id, message=message) # Store should receive JSON message from server. response = await store_communicator.receive_json_from() assert_equal(message, response) await communicator.disconnect() The communicator function create_order should create a new channel_layer group to which both the customer and store should be added. async def create_order(self, event): order = await self._create_order(event.get('data')) order_id = f'{order.id}' # Add the … -
How do I solve this TemplateSyntaxError in Django that says "Could not parse the remainder"
I am trying to render a block of HTML code repeatedly using for loop. But Django throws a TemplateSyntaxError when I reload my browser <div class="carousel-item active"> {% for number in range(3) %} <!--Slide {{ number + 1 }}--> <div class="row"> {% for number in range(6) %} <!--Slide 1 Col {{ number + 1 }}--> <div class="col-lg-2"> <div class="card" style="width: 100%;"> <img class="card-img-top" src="..." alt="Card image cap"> <div class="card-body"> <h5 class="card-title">Card title</h5> <p class="card-text">Some quick example text to build on the card title and make up the bulk of the card's content.</p> <a href="#" class="btn btn-primary">Go somewhere</a> </div> </div> </div> {% endfor %} </div> {% endfor %} </div> I expected a repeated rendering of the blocks inside the for loop but got "TemplateSyntaxError at / Could not parse the remainder: '(3)' from 'range(3)'" instead -
How to design a database for ecommerce django website
I'm new to django and I'm trying to build ecommerce website but I'm facing a problem of storing data of products that don't share the same attributes , I'm wondring which database technologies to use and how design database in such way that i could store different products attributes without problems. Please help me solve this problem Thank you -
Auto Fill Text field from one text field to another with small change
Is there anyway to auto populate fields based on user input from the 1 text field, then update rest of the fields with small changes in each field. For example: [user input] Field 1 Network: 192.168.0.0 [auto] Field 2 Network_Util: 192.168.1.0 [auto] Field 3 Network_Util2: 192.168.2.0 I tried to for following code, but it copies the text, how to change the third octet value? <input type="text"id="network1" name="Network1" value="" > <input type="text" id="network2" name="Network2" value=""> $("#network1").keyup(function(){ var net = network1.split("."); var octet3 = net[2]; $("#network2").val(this.value); }); Thank you for your help -
Are atomic transactions supposed to produce more connection.queries in Django?
I have the following in my models: from django.db import models class X(models.Model): ... class Y(models.Model): ... x = models.ForeignKey(X, on_delete=models.CASCADE) class Z(models.Model): ... y = models.ForeignKey(Y, on_delete=models.CASCADE) In one of my views, I am updating all my models like so: from .models import X, Y, Z from django.db import connection, transaction def do_something(bro, z_pk): z = Z.objects.select_related('y__x').get(pk=z_pk) y = z.y x = y.x ... with transaction.atomic(): z.save() y.save() x.save() print(len(connection.queries)) With the transaction.atomic(), the length of queries is 5. However, without it, the length returned is 4. That is, the following code: from .models import X, Y, Z from django.db import connection def do_something(bro, z_pk): z = Z.objects.select_related('y__x').get(pk=z_pk) y = z.y x = y.x ... z.save() y.save() x.save() print(len(connection.queries)) Returns a length of 4. Is this normal or am I missing something? Moreover, with the transaction.atomic(), am I hitting my database less times? Its difficult to understand that based on the connection.queries. Note: The extra query in the atomic function is the following: {'sql': 'BEGIN', 'time': '0.000'} -
A Desktop application for Django
I'm making a little Time Attendance Django Application where I want two parts of that program. A web part and a Desktop part. The Web Part would be used to view the Employees, Manager them, get payroll whereas the Desktop Part would be used to add attendance and stuff. And before anyone asks, I'll be using facial recognition for the attendance. So unless there's a way to use good and fast facial recognition on the web, I can't do it all on the Web. I was thinking of using electron. Make things simple. Have two login types, one for the web and the other for the Desktop. If that's the case, I would like to have different views and templates for the both of them without making a new app. Maybe add an option on the login page where you can choose either Desktop login or Web login. (Let me clear this here that by Web Login, I mean the Website like how you put in the URL in the browser and by Desktop Login, I mean the same thing but outside a browser. I understand that Electron is a browser but I hope you understand xD) If this is … -
How to fix empty custom user fields submission on custom user model requested from rest-auth/registration?
I am just a beginner here. Please help me out. I am using Django REST Framework, with django-rest-auth, I created a custom user model with extra fields. I want to use the django-rest-auth registration endpoint to register a new user in one request, and thus sending all the data to create a new user, including the data for the extra field but the extra field are not receiving the data. I am using AbstractBaseUser. This is how i created my custom user class UserManager(BaseUserManager): use_in_migrations = True def create_user(self, username, email, first_name, last_name, role_id, contact_num, opt_contact_num, citizenship_num, password=None): user = self.model( username=username, email=self.normalize_email(email), first_name=first_name, last_name=last_name, role_id=role_id, contact_num=contact_num, opt_contact_num=opt_contact_num, citizenship_num=citizenship_num, ) user.set_password(password) user.save(using=self._db) return user def create_staffuser(self,username, email, first_name, last_name, role_id, contact_num, opt_contact_num, citizenship_num, password): user = self.create_user( username=username, email=email, first_name=first_name, last_name=last_name, role_id=role_id, contact_num=contact_num, opt_contact_num=opt_contact_num, citizenship_num=citizenship_num, ) user.is_staff = True user.save(using=self._db) return user def create_superuser(self, username, email, first_name, last_name, role_id, contact_num, opt_contact_num, citizenship_num, password): user = self.create_user( username=username, email=email, first_name="True", last_name="True", role_id=0, contact_num=contact_num, opt_contact_num=opt_contact_num, citizenship_num=citizenship_num, password=password, ) user.is_staff = True user.is_admin = True user.save(using=self._db) return user #custom user table class User(AbstractBaseUser): username = models.CharField(max_length=120, unique=True) email = models.EmailField(unique=True) first_name = models.CharField(max_length=120) last_name = models.CharField(max_length=120) role_id = models.PositiveIntegerField(default=0) contact_num = PhoneNumberField(null=False, blank=False) … -
Start celery worker as daemons task doesn't run
I am new to celery and I am kinda confused. I followed tutorial from here I am able to start workers by systemctl start celeryd and viewing status celery -A jobs status worker1@c0326ddd3f01: OK worker2@c0326ddd3f01: OK Even on flower I can see those to worker online. However, when I run a task from my Flask app, nothing happens it gets stuck. In another terminal if I run celery worker -A jobs -l info another worker starts celery@c0326ddd3f01 and my task gets completed by this worker only. Even if I have multiple jobs queued up, this worker only runs them. I am not sure what I am doing wrong here. -
How to install dlib in django azure web app service
I want to publish a django web app in azure that uses dlib and opencv for processing images When trying to deploy the app through local code, it fails with dlib unable to install due to cmake not found. I tried using windows machine also but received same error. CMake must be installed to build the following extensions: dlib Expected to install dlib successfully in azure webapp -
django does not redirect in iframe
I have two websites(A and B). They both uses openID auth at the same provider. I want to embed one of those websites(B) to another(A) using <iframe>. But there is a problem with auth in embedded website(B). Problem: If I log in into A website and after this open B in another browser Tab, OpenID auth works fine and B automatically authenticate without providing login and password. And if I go to the page at A with embedded B: source in <iframe> recognize me as authenticated user. But If I open A without opening B in another browser Tab, <iframe> redirects me to openID provider login page and not redirect further. I'm trying to look at the Chrome Network debug and see some strange thing. How redirect look like in B if its open in another browser Tab: General section looks the same: Request URL: https://oidc.domain.com/openid/auth/?client_id=CLIENT_ID&redirect_uri=http://B.domain.com/callback&response_type=code Request Method: GET Status Code: 302 Found But Response headers section looks different. 1. If B is open in another browser tab: Connection: keep-alive Content-Length: 0 Content-Type: text/html; charset=utf-8 Date: Tue, 13 Aug 2019 17:53:32 GMT **Location: https://B.domain.com/callback?code=CODE** Server: nginx Vary: Cookie If B is opening like embedded part of A: Connection: keep-alive Content-Length: … -
Django Elastic Beanstalk Token Authentication
I've been working on an application which connects to a Django Server using Token authentication in Django Rest Framework, and Locally it's been working great, no problems with authentication and I've even been able to use the visual browsable api with authenticated users. Now when I deployed the project to Elastic Beanstalk I keep getting Unauthorized while using all urls that require authentication. I've tried the answers in here and in here. None seem to work, I'm using this document for http redirect as shown in aws's documentation. This are the authentication classes in my Django view: authentication_classes = (BasicAuthentication,TokenAuthentication,) And the permission classes: permission_classes = (gbets_permissions.IsSameUser,permissions.IsAuthenticated) I've already double checked settings.py and retried in local environment. Thanks for the help, I'm not used to working on back end, and I'm currently stuck, thank you. And if you need any more information let me know. -
How to update table row with jQuery-Tabledit and Django?
I am trying to create Crud app which creates,updates and delete data on same page after spending some time on internet I have ended up Jquery tabledit but I am not getting how to use django with Tabledit,Is there any way to to use django with Tabledit,Or any another way to create live edit in django ? -
Bootstrap Nav Dropdowns with Embedded CognitoForms
I'm learning Django and trying to model a web application where the end user of the application is to follow a process for a particular customer record. The process steps for the customer are shown using Bootstrap "Navs: Tabs with Dropdowns". Each step has the same drop down menu under it. The idea I'm going for is that when you click on any of the steps, it brings up an embedded web form (cognitoforms.com) relevant to that step of the process. If the customer record doesn't exist yet, end user populates the empty form and saves form data to the database using "Database Save". If the customer record does exist, end user can use "Database Pull" to repopulate the form with information from the database, end user can then edit and save updated form data back to the database using "Database Save". When end user is ready, they can click on "Generate Document" which will populate a template (.docx or similar) with the most up to date information from the database. Here is the Bootstrap code for creating "Step1" and "Step2" for Nav with Dropdowns. This works fine. <ul class="nav nav-tabs justify-content-center"> <li class="nav-item dropdown"> <a class="nav-link active dropdown-toggle" data-toggle="dropdown" … -
Import and Use django Model Class using variable
I am new to both python and django. First of all I am trying to do database query by using standard django feature . I dont want to use raw SQL. What i want to achieve: I want import and use Django Class dynamically by using variable like: dynamic_var = "Note" #import from .model import dynamic_var #query q = dynamic_var.objects.all() print(q) but above code are not working. I know there are some solid reason behind it, because dynamic_var is a String not a Class/model class. But how can i achieve this behavior. dynamic_var = "Note" from .model import Note ## Not work but i want to achieve info = dynamic_var.objects.all() # Working info = Note.objects.all() print(info) Error AttributeError at /note/ 'str' object has no attribute 'objects' -
How can I set Django model options in runtime?
I'm working on an admin panel and want to provide some configurable options for the end user. For example, when I have a User model I want an option in my panel to be able to select which fields are required. How can I change the model options in runtime and make it persistent?