Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
why uploaded files is not deleting
I am new in Django, Here I have added a correct code but it is not deleting the file. Please help me someone. views.py: def control_upload(request): if request.method == 'POST': form = ControlForm(request.POST, request.FILES) if form.is_valid(): model_instance = form.save() model_instance.save() else: form = ControlForm() controlmachiness = Controlmachine.objects.all() return render(request,'usermaster/control_uploadfile.html',{'form':form,'controlmachiness':controlmachiness}) def control_index(request): controlmachines = Controlmachine.objects.all() return render(request,"usermaster/control_show.html",{'controlmachines':controlmachines}) def control_destroy(request, id): if request.method == 'POST': controlmachine = Controlmachine.objects.get(id=id) controlmachine.delete() return HttpResponseRedirect('/usermaster/controlfile/') models.py: class Controlmachine(models.Model): machine_name = models.CharField(max_length=100) operation_no = models.IntegerField() control_uploadfile = models.FileField(upload_to='control_files/') class Meta: db_table = "controlmachine" def delete(self, *args, **kwargs): self.machine_name.delete() self.operation_no.delete() self.control_uploadfile.delete() super.delete(*args, *kwargs) forms.py: class ControlForm(forms.ModelForm): class Meta: model = Controlmachine fields = ['machine_name', 'operation_no', 'control_uploadfile'] #https://docs.djangoproject.com/en/3.0/ref/forms/widgets/ widgets = { 'machine_name': forms.TextInput(attrs={ 'class': 'form-control' }), 'operation_no': forms.TextInput(attrs={ 'class': 'form-control' }), 'control_uploadfile': forms.ClearableFileInput(attrs={ 'class': 'form-control' }), } urls.py: path('controlfile/',views.control_index,name='control_index'), path('cdelete/<int:id>',views.control_destroy,name='control_destroy'), path('controlupload/',views.control_upload,name='control_upload'), path('upload/',views.upload,name='upload'), path('save',views.save_machine,name='save_machine'), control_show.html: {% extends 'usermaster/home.html' %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> <link href="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/css/bootstrap.min.css" rel="stylesheet" id="bootstrap-css"> <script src="http://maxcdn.bootstrapcdn.com/bootstrap/3.3.0/js/bootstrap.min.js"></script> <script src="http://code.jquery.com/jquery-1.11.1.min.js"></script> <script src="https://cdn.datatables.net/1.10.16/js/jquery.dataTables.min.js"></script> <script src="https://cdn.datatables.net/1.10.16/js/dataTables.bootstrap4.min.js"></script> </head> {% block body %} <body> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="table-responsive"> <table id="bootstrapdatatable" class="table table-striped table-bordered" width="90%"> <thead> <th><input type="checkbox" id="checkall" /></th> <th>ID</th> <th>Machine Name</th> <th>Operation Number</th> <th>File</th> <th>Delete</th> </thead> <tbody> … -
Error when running heroku run manage.py migrate
If you run python manage.py migrate in Heroku, python: can't open file 'manage.py': [Errno 2] No such file or directory I am getting this error. How can I fix this error? If i run heroku run ls accounts config db.sqlite3 manage.py media photo Procfile requirements.txt runtime.txt templates rqueirments.txt asgiref==3.5.0 dj-database-url==0.5.0 Django==3.2.11 django-heroku==0.3.1 django-storages==1.12.3 gunicorn==20.1.0 Pillow==9.0.0 psycopg2==2.9.3 psycopg2-binary==2.9.3 pytz==2021.3 sqlparse==0.4.2 typing-extensions==4.0.1 whitenoise==5.3.0 Procfile `web: gunicorn config.wsgi` runtime `python-3.7.12` -
New superuser unable to log in to CMS
I'm new to Wagtail and django. I've completed the https://learnwagtail.com/wagtail-for-beginners/ course and managed to get my site up and running on Digital ocean, however I'm unable to login to the admin area. I have tried using the superuser credentials that were used locally. I have also tried multiple times to create a new superuser with: python manage.py createsuperuser and while the process appears to work successfully in the terminal (I'm logged in via SSH to my DO droplet), I continually receive the 'Your username and password didn't match. Please try again.' message when attempting to log in with the newly created username and password. If I use the shell to check users I can see my newly created user exists. I have also tried using python manage.py changepassword myusername to change the password on the previously created superusers, but again, while the process appears to work successfully in the terminal I continue to receive the error message when attempting to log in. Can anyone point me in the right direction as to what I might be missing or doing wrong here? And / or how I might best debug the issue? Thanks in advance! -
Error while adding records by admin panel django
So, lately I have been using Termux app in my android device to build django app. while I was using admin panel it opened but when I tried to add any records in my database tables through it It just prompted this error in the Termux terminal. Internal Server Error: /admin/travello/destination/add/ Traceback (most recent call last): File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/core/files/move.py", line 61, in file_move_safe locks.lock(fd, locks.LOCK_EX) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/core/files/locks.py", line 111, in lock fcntl.flock(_fd(f), flags) OSError: [Errno 38] Function not implemented During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/core/handlers/base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/contrib/admin/options.py", line 622, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/views/decorators/cache.py", line 57, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/contrib/admin/sites.py", line 236, in inner return view(request, *args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1670, in add_view return self.changeform_view(request, None, form_url, extra_context) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/utils/decorators.py", line 43, in _wrapper return bound_method(*args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/utils/decorators.py", line 130, in _wrapped_view response = view_func(request, *args, **kwargs) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1549, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "/data/data/com.termux/files/usr/lib/python3.10/site-packages/django/contrib/admin/options.py", line 1599, in … -
List Class View didn't return an HttpResponse
I've been trying to get a class-based list view to display all entries under a user's account (applicant), but when loading the page I'm given the following error: The view jobassessment.views.view didn't return an HttpResponse object. It returned None instead. To me that sounds like the URL dispatcher isn't running the correct view, but this is my URL file for both the whole site and the jobassessment application and I can't seem to spot the fault. Site URL.py: urlpatterns = [ path('admin/', admin.site.urls, name="admin"), path('accounts/', include('django.contrib.auth.urls'), name="accounts"), path('applicant/', include('userprofile.urls'), name="applicant"), path('assessments/', include('jobassessment.urls')), ] JobAssessment App's URL.py: from django.urls import path from . import views urlpatterns = [ path("", views.AssessmentListView.as_view(), name="assessment"), ] This is my ListView that is called: class AssessmentListView(LoginRequiredMixin, generic.ListView): model = Assessment template_name ='assessments_index.html' paginate_by = 5 def get(self, request, *args, **kwargs): # Ensure they have first created an Applicant Profile if not Applicant.objects.filter(user=self.request.user).exists(): messages.info(request, "You must create a profile before you can view any assessments.") return redirect('profile_create_form') def get_queryset(self): return Assessment.objects.all().filter(applicant=Applicant.objects.filter(user=self.request.user)).order_by('-assessment_stage') -
selenium test doesn't display static files and data objects
Everything works perfectly on the local server and in the production but when trying to run the selenium test, the static files don't load. Even created data objects been displayed on the template is not also displayed. Here are the static setting in the settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_STORAGE = 'whitenoise.storage.CompressedManifestStaticFilesStorage' # Default primary key field type # https://docs.djangoproject.com/en/3.2/ref/settings/#default-auto-field DEFAULT_AUTO_FIELD = 'django.db.models.BigAutoField' DEFAULT_FILE_STORAGE = 'cloudinary_storage.storage.MediaCloudinaryStorage' -
How to make auto-genertion(auto-fill and increment) in django admin
I want to make code field should be auto filled and auto increment in django admin. models.py class GeneralDocumentType(models.Model): code = models.CharField(max_length=10, null=False, unique=True) name = models.CharField(max_length=100, null=False, unique=True) description = models.TextField(blank=True, null=True) def __str__(self): return self.name I want to show my code field default=DOC001, and it will show increment by 1 before adding data by user.How can I achieve this?.. -
Django Search Box not displaying results
I'm new to coding and working on my class assignment displaying a search box in Django. I was able to display the search box, but the results are not being displayed. In the inspector tool, I do see the search results coming through the GET method so I am assume it must an issue with my HTML code. I would appreciate any suggestions/resources on how to fix this issue. Picture of search box {% extends "base_menu.html" %} {% block content %} <h1>Ads</h1> <div style="float:right"> <!-- https://www.w3schools.com/howto/howto_css_search_button.asp --> <form> <input type="text" placeholder="Search.." name="search" {% if search %} value="{{ search }}" {% endif %} > <button type="submit"><i class="fa fa-search"></i></button> <a href="{% url 'ads:all' %}"><i class="fa fa-undo"></i></a> </form> </div> <p> {% if ad_list %} <ul> {% for ad in ad_list %} <li> <a href="{% url 'ads:ad_detail' ad.id %}">{{ ad.title }}</a> {% if ad.owner == user %} (<a href="{% url 'ads:ad_update' ad.id %}">Edit</a> | <a href="{% url 'ads:ad_delete' ad.id %}">Delete</a>) {% endif %} </li> {% if user.is_authenticated %} <!-- Two hrefs with two stacked icons each - one showing and one hidden --> <a href="#" onclick= "favPost('{% url 'ads:ad_unfavorite' ad.id %}', {{ ad.id }});return false;" {% if ad.id not in favorites %} style="display: none;" … -
.NET vs Django vs Node [closed]
I'm a beginner at web development. I am considering learning web development and I need to choose a framework. What will you use .NET, Django or Node? I like being the language is typesafe. I'm currently learning C++. Could you please give me advice such as job opportunities, current trends? -
Connection to the another DB not created by Django
I have Django project and want to look the another db (not default db created by Php Symfony) Django can set up two DB in settins.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', "NAME": config("DB_NAME"), "USER": config("DB_USER"), "PASSWORD": config("DB_PASSWORD"), "HOST": config("DB_HOST"), "PORT": config("DB_PORT"), 'OPTIONS': { 'charset': 'utf8mb4', 'init_command': "SET sql_mode='STRICT_TRANS_TABLES'" }, } 'extern': { 'ENGINE': 'django.db.backends.mysql', 'NAME': config("DB_EXTERN_NAME"), 'USER': config("DB_EXTERN_USER"), 'PASSWORD': config("DB_EXTERN_PASSWORD"), 'HOST': config("DB_EXTERN_HOST"), 'PORT': config("DB_EXTERN_PORT"), } } and set models.py for example class Area(models.Model): class Meta: db_table = 'my_area' However it requires to change the extern database when python manage.py makemigrations,python manage.py migrate I just want to reference the extern db not alter. Is there any good practice?? -
Using DRF + frontend framework with Django froms
Background I ran into a really annoying problem here. I've decided to use Svlete as my frontend. Also, I have a lot of endpoints in my REST api that expect form data. In the past I would just forms.py in my app's directory and then add a form like: class ProductsModelForm(forms.ModelForm): class Meta: model = Product fields = ( 'name', 'weight', ) class ProductForm(forms.Form): name = forms.CharField() weight = forms.IntegerField() And would then use <form method="post"> {% csrf_token %} {{ form.as_p }} <button type="submit">Submit</button> </form> In the HTML template. All cool. DRF + Frontend Framework Obviously I still have the form in the forms.py but now I have to define the form in the fronend too. And with bigger forms it gets really annoying because I always have to compare that I have every field in my frontend form that I have defined in the django backend form. Is ther any solution to this? -
Trying to make a form with 2 inputs
I have two different forms in my register page as the one to one relationship in one of the model will show a drop down box therefore I am using the second models field where the user will have to input the field. How would I make it so when the forms are valid, the 'SNI' will save to the first form and not the second. Model from asyncio import FastChildWatcher import email from pyexpat import model from xxlimited import Null from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class userCouncil(BaseUserManager): def create_user(self, userID, password=None): if not email: raise ValueError("Email is required") user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.save(using=self._db) return user def create_superuser(self, userID, password): user = self.model(userID = self.normalize_email(userID)) user.set_password(password) user.is_staff = True user.is_admin = True user.save(using=self._db) return user class sni(models.Model): SNI = models.CharField(max_length=256, primary_key=True) Used = models.IntegerField(null=True, blank=True) password = None USERNAME_FIELD = 'SNI' def __str__(self): return self.SNI class Account(AbstractBaseUser): userID = models.EmailField(primary_key= True ,max_length=256, unique=True) name = models.CharField(max_length=100) dateOfBirth = models.DateField(max_length=8, null=True) homeAddress = models.CharField(max_length=100, null=True) is_staff = models.BooleanField(default=False) is_admin = models.BooleanField(default=False) sni = models.OneToOneField(sni, on_delete=models.CASCADE, null=True, blank=True) USERNAME_FIELD = 'userID' objects = userCouncil() def __str__(self): return self.userID def has_perm(self, perm, obj=None): return self.is_admin def has_module_perms(self, … -
Django dont create a new instance of a many-to-many field if its field already exists in db, instead increment another field
I have the following classes in my Models.py (removed unrelated fields & classes) class Size(models.Model): prod_size = models.DecimalField(max_digits=3, decimal_places=1) quantity = models.IntegerField(default=1) class Product(models.Model): sizes = models.ManyToManyField(Size, related_name='products') Currently, if I go under a existing product from django admin and add a new size to an existing product with an existing prod_size value (i.e. prod_size = 8.5 with product_id = 4 in the intermediate table) a new Size object (with its new size_id and product_id = 4 in the intermediate table) and prod_size = 8.5 with quantity = 1 in the Size table are created. I would instead like to increment the quantity field of the existing Size object by one in the database, how can I achieve this? -
Websockets problem with django on production
I have a django app and its including websockets, so websockets on running with gunicorn -b 0.0.0.0 or runserver but not working with nginx configuration or problem like that i dont know whats the problem -
Pytest / Django: How to change a decorator that is defined during build time?
I am making a network request and give it a 10 second timeout. The timeout is raised by a decorator that reads the time limit from settings, so it looks like this: @timeout(settings.TIMEOUT). The problem is that I want the test to be super fast, so I change the timeout to 0.1: settings.TIMEOUT = 0.1 The problem is that the decorator is already initialized (I might be using the wrong word) by the time I try to test it. So the decorator is created/defined at build time, then I change the settings, but too late, the decorator doesn't read the updated setting again. Here is a simplified version: ############## settings.py ############### TIMEOUT = 10 ############### request_maker.py ############### from timeout_decorator import timeout from django.conf import settings from time import sleep class MakeRequest @timeout(settings.TIMEOUT) def make_the_request(self): sleep(100) ############### tests.py ############### import pytest from timeout_decorator import TimeoutError from request_maker import MakeRequest def test_make_request(settings): settings.TIMEOUT = 0.1 mr = MakeRequest() with pytest.raises(TimeoutError) as e: mr.make_the_request() # < Even though TIMEOUT is 0.1, it actually times out for 10 seconds How can I change the code so that during production, it is @timeout(10) and during testing it is @timeout(0.1)? -
The best library to add chart in Django Jazzmin admin page
I have 3 models in my Django app and customised user model. I'd like to add few basic bar and pie charts on main admin page. I am using Jazzmin library. Please recommend some libraries or scripts that I can use to create such charts. -
how to Build a referral and earning system in django python
i am currently working on a system, when a user register and do a particular task they will be credited with a certain amount, also the app will have a referral system every user will have a unique referral id when you invite somebody with your code when there do a task you will also earn a certain amount as a referral commission i have already design my data base but i don't know where to start from here, if any one here has build a similar app should please share they code with me, if I didn't deliver this job my work will be at risk thanks -
Embedding http requests into Qt c++ application
I apologize if this is the wrong location to be asking this, let me know and I'll remove it and post it in the right area. I was wondering about standards for performing http requests in a Qt desktop application. For example, I want to create a tool that will register users with a Python based Django application which has a database of users. However, there's a problem here. Do I just hard code the URLs for development and release like this? #ifdef _DEBUG std::string register_url = "http://localhost:3000"; #else std::string register_url = "https://api.mywebsite.com"; #endif I feel like hard coding urls like this is bad practice but I don't know any other way of doing this. Should I use an .ini file? Environment variables? What's the standard for when you have multiple different request URLs? Like I will have the following URLs: /login /register /request_json_web_token /logout /refresh_token Am I supposed to hard code a list of URLs in a header file somewhere? What do you guys do? What's the standard way of doing this? Make monolithic headers full of URLs? -
django raw sql in models with ForeignKey
Let's say this pseudocode represents models to work with class Quiz(): name = models.CharField() class Answer(): quiz = models.ForeignKey(Quiz) answer_text = models.CharField() I would like to trace raw SQL, so let's also import from django.db import connection print(Answer.objects.all().select_related('quiz').query) ok, here we have inner join under the hood >>> a = Answer.objects.all() >>> print(a[0].quiz.query) however the latter example throws AttributeError: 'Quiz' object has no attribute 'query' Could you tell if there are any ways of tracing raw sql more effectively? Which way is the best? I'm practicing more complicated prefetch_related and select_related queries. Thanks -
Settings.BASE_DIR in django returning Windows path instead of Base directory
I ran these commands in the python shell from django.conf import settings print(settings.BASE_DIR) This returned the project's absolute path as expected "C:/Users/User/Desktop/Project" But this was not the case when I tried accessing the same function in a function inside my custom filter, in which it started to return the windows path "C:/" instead. filter.py import os from django import template import moviepy.editor import datetime from django.conf import settings register = template.Library() @register.filter(name='vduration') def vduration(videourl): video = video = moviepy.editor.VideoFileClip(os.path.join(settings.BASE_DIR, videourl)) video_time = int(video.duration) video_time = str(datetime.timedelta(seconds=video_time)) return video_time in my settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent Does anyone know what could be going on? -
Python Social Auth grabbing access token for user
I would like to create a custom user with a username, email from the social pipeline using Google OAuth2. If there is a user already associated with that email, username then just attach the access token to that account otherwise create the account but it should get a way to access it through pw after creation? Maybe set a default pw or just delete the account after login? I was looking into pipelines and saw something like this where if backend was something like facebook I could get the values out into a new custom user. { 'username': 'foobar', 'access_token': 'CAAD...', 'first_name': 'Foo', 'last_name': 'Bar', 'verified': True, 'name': 'Foo Bar', 'locale': 'en_US', 'gender': 'male', 'expires': '5183999', 'email': 'foo@bar.com', 'updated_time': '2014-01-14T15:58:35+0000', 'link': 'https://www.facebook.com/foobar', 'timezone': -3, 'id': '100000126636010', } pipeline: def save_profile(backend, user, response, *args, **kwargs): if backend.name == 'facebook': profile = user.get_profile() if profile is None: profile = Profile(user_id=user.id) profile.gender = response.get('gender') profile.save() SOCIAL_AUTH_PIPELINE = ( 'social_core.pipeline.social_auth.social_details', 'social_core.pipeline.social_auth.social_uid', 'social_core.pipeline.social_auth.auth_allowed', 'social_core.pipeline.social_auth.social_user', 'social_core.pipeline.user.get_username', 'social_core.pipeline.user.create_user', 'path.to.save_profile', # <--- set the path to the function 'social_core.pipeline.social_auth.associate_user', 'social_core.pipeline.social_auth.load_extra_data', 'social_core.pipeline.user.user_details', ) My current custom user: class Profile(AbstractUser): bio = models.TextField(max_length=100, blank=True,null=True) phone_number = PhoneNumberField(max_length=25, region='US') birth_date = models.DateField(blank = True, null = True) is_doctor = models.BooleanField(default=False) date_created … -
Django dropdown list of users
I am attempting to create an issue tracker similar to github's. I'm stuck on trying to implement the assigning feature, here's what I have so far class Assign(models.Model): name = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) class Issue(models.Model): MARK_AS = ((True, 'Open'), (False, 'Closed')) title = models.CharField(max_length=100) content = models.TextField() date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) assignee = models.ForeignKey(Assign, on_delete=models.SET_NULL, null=True) mark_as = models.BooleanField(choices=MARK_AS, default=True) def __str__(self): return self.title def get_absolute_url(self): return reverse('issue-detail', kwargs={'pk': self.pk}) admin page I feel like I'm close, however when I try to use class Assign(models.Model): name = models.OneToOneField(User, on_delete=models.SET_NULL, null=True) def __str__(self): return self.name I get the error of __str__ returned non-string (type User) Anyone ideas on how to fix this? Thank you. -
Display data from multiple tables in one Template
I'm trying to create a dashboard for orders placed by a customer. I've got multiple tables, but the two I'm dealing with is "Order" and "Order_Detail". From the "Order" table, I need to display Customer, Status, and Required_date, from the "Order_Detail" table, I need Product. I'm able to access the data but I can figure out how to display all the records at the same time on one page. models.py class Order(models.Model): STATUS = ( ('New', 'New'), ('Ready For Fullfillment', 'Ready For Fullfillment'), ('Fullfilled Ready For Delivery', 'Fullfilled Ready For Delivery'), ('Out For Delivery', 'Out For Delivery'), ('Delivered', 'Delivered'), ) order_date = models.DateTimeField(auto_now_add=True, null=True) required_date = models.DateTimeField(auto_now_add=True, null=True) status = models.CharField(max_length=200, null=True, choices=STATUS) note = models.CharField(max_length=1000, null=True, blank=True) customer = models.ForeignKey(Customer, null=True, on_delete=models.SET_NULL) def __str__(self): return self.customer.name class Order_Detail(models.Model): orderNumber = models.ForeignKey(Order, null=True, on_delete=models.SET_NULL) product = models.ForeignKey(Product, null=True, on_delete=models.SET_NULL) pounds = models.IntegerField(null=True) ounces = models.IntegerField(null=True) container = models.ForeignKey(Container, null=True, on_delete=models.SET_NULL) lot_code = models.CharField(max_length=200, null=True, blank=True) note = models.CharField(max_length=1000, null=True, blank=True) In my views.py, I'm playing with the following code: print('TEST2') o = Order.objects.all() o_notdelivered = Order.objects.exclude(status='Delivered') for e in o_notdelivered: print('Order ID:', e.id) order_detail_data = serializers.serialize("python", Order_Detail.objects.all().filter(orderNumber=e.id)) print('order_detail_data:', order_detail_data) With that code, I'm able to get the ORDER data and … -
What are the correct permissions and virtualhosts for running Django in a sub-directory?
I'm trying to install and run Django in a sub-directory, to keep it separate from a static html site in root, and am having issues with either file/folder permissions or virtualhosts. These two questions haven't helped and are very old: install django on subdirectory and Configure django on sub directory Is this file/folder permissions or virtualhosts issue? Why are the .py files not executing? Running Ubuntu 20.04.3 LTS Apache2 already installed and running Python3 and Django installed libapache2-mod-wsgi installed and enabled Apache restarted several times I ran the usual shell commands to start a Django project: django-admin.py startproject contact and then I ran createsuperuser, collectstatic, etc., successfully. https://example.com/contact/index.html works fine, But this is what I get at example.com/contact/contact: This is my file structure: settings.py: import os BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) SECRET_KEY = '...' DEBUG = True ALLOWED_HOSTS = [] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'contact.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION = 'contact.wsgi.application' DATABASES = { 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), } } AUTH_PASSWORD_VALIDATORS … -
graphene-django: Determine Object type when multiple GraphQL object types use the same django model in node query
This is specifically for graphene-django (not just graphene) when performing a node(id: ...) {} query. Assume a fixed schema with 2 (or more) different GraphQL object types using graphene_django.DjangoObjectType linked to the same django model: import graphene_django from .models import Org as OrgModel class Org(graphene_django.DjangoObjectType): class Meta: model = OrgModel fields = ( "id", "name", "billing" ) class AnonymousOrg(graphene_django.DjangoObjectType): class Meta: model = OrgModel fields = ( "id", "name", ) Let's assume a query to Org of ID 7eca71ed-ff04-4473-9fd1-0a587705f885. btoa('Org:7eca71ed-ff04-4473-9fd1-0a587705f885') 'T3JnOjdlY2E3MWVkLWZmMDQtNDQ3My05ZmQxLTBhNTg3NzA1Zjg4NQ==' { node(id: "T3JnOjdlY2E3MWVkLWZmMDQtNDQ3My05ZmQxLTBhNTg3NzA1Zjg4NQ==") { id __typename ... on Org { id } } } Return: { "data": { "node": { "id": "QW5vbnltb3VzT3JnOjdlY2E3MWVkLWZmMDQtNDQ3My05ZmQxLTBhNTg3NzA1Zjg4NQ==", "__typename": "AnonymousOrg" } } } It returns the other object type 'AnonymousOrg:7eca71ed-ff04-4473-9fd1-0a587705f885', despite the relay ID specifying it was an Org object. Is there a way in graphene-django to "hint" or provide detail to assure the return type if what's specified in the ID and its fragment? Clarification on question Other questions were discussing graphene, not specifically graphene-django, which is doing the type determinations in this case. This is different from Django-graphene multiple types for the same model, as that one asked about how to handle field permissions and opened possibility to reconsidering schema structure (e.g. splitting …