Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django core exceptions ImproperlyConfigured:
I had my django up and running last night at around midnight, everything was kawa when i closed but in the morning when i open my pc i get django.core.exceptions.ImproperlyConfigured: error !error Note that only Django core commands are listed as settings are not properly configured (error: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings.). I tried closing the VScode and Terminal, reopened them, started virtualenvironment again but the error persists \env\Scripts\python.exe: No module named django I have django installed on the virtudal env as well as set as a global environment variable thanks in advance I expected python to get django installed on the virtual environment -
Django : Using the register form i gave the url in the lastline for redirecting to the loginpage it is not getting it is showing the page not found
when i click the login button here im getting page not found.. This is my template file i gave like this im getting like this error plz any one can solve this im new Django framework Im trying to click the login button but it not redirecting to the login page it getting like the page is not found i gave the correct url <a href="{% url 'login'}" but im not getting plz any solve this issue -
Hi I'm having trouble customizing authentication in Django
I am a newbie and I am designing Django authentication software My problem is that I have to check four separate levels for which there are predefined codes in the permission check. A model class named province and a model class named city and a model named Student My review model is such that I should be able to give a user the membership of the central office or the membership of a province or the membership of a city in a province. The user can only be for one of these situations My models is like this class Province(models.Model): province_id = models.IntegerField(primary_key=True, serialize=True, verbose_name='ID') province_title = models.CharField(max_length=30, verbose_name=_('Province')) class Meta: ordering = ['province_id'] def __str__(self): return self.province_title class Center(models.Model): id = models.BigAutoField(auto_created=True, primary_key=True, serialize=False, verbose_name='ID') center_title = models.CharField(max_length=150, verbose_name=_('Name of the training center'), null=True) center_title_id = models.CharField(max_length=64, verbose_name=_('Code of the training center'), null=True) province = models.ForeignKey(Province, on_delete=models.CASCADE, verbose_name=_('Province')) class Meta: verbose_name = _("center") verbose_name_plural = _("centers") def __str__(self): return self.center_title` class CulturalUser(AbstractUser): pass class UserPositions(models.Model): class Position(models.TextChoices): UNIVERSITY_STUDENT = '1', _('University student') TRAINING_CENTER = '2', _('Training center') PROVINCE = '3', _('Province') CENTRAL_OFFICE = '4', _('Central office') user = models.ForeignKey(CulturalUser, on_delete=models.CASCADE, verbose_name=_('User')) position = models.CharField(max_length=2, verbose_name=_('Access level'), choices=Position.choices, default=Position.UNIVERSITY_STUDENT) province … -
Why is my HTML template in Django not rendering in browser?
I am having issues with rendering an HTML template that has variables passed to it from my views.py in the Django project. Everything seems to be working with the exception that when you visit the HTML in a browser on my local machine it renders the HTML code, instead of the designed page with content. the files are below. VIEWS.PY from django.shortcuts import render import datetime import firebase_admin from firebase_admin import credentials from firebase_admin import firestore db = firestore.Client() config = { "apiKey": "XXXXXXXXXXXXXXXXXXX", "authDomain": "XXXXXXXXXXXXXXXXXXX.firebaseapp.com", "databaseURL": "https://XXXXXXXXXXXXXXXXXXX.firebaseio.com", "projectId": "XXXXXXXXXXXXXXXXXXX", "storageBucket": "XXXXXXXXXXXXXXXXXXX.appspot.com", "messagingSenderId": "XXXXXXXXXXXXXXXXXXX", "appId": "XXXXXXXXXXXXXXXXXXX", "measurementId": "XXXXXXXXXXXXXXXXXXX", "serviceAccount": "XXXXXXXXXXXXXXXXXXX.json", } # DATABASE # Use the application default credentials. cred = credentials.ApplicationDefault() firebase_admin.initialize_app(cred) firestore_client = firestore.client() # TIME & DATE today_date = datetime.datetime.now() tomorrow_date = today_date + datetime.timedelta(days=1) games_today = today_date.date() games_tomorrow = tomorrow_date.date() games_today_formatted = games_today.strftime("%Y-%m-%d") games_tomorrow_formatted = games_tomorrow.strftime("%Y-%m-%d") def basketball_nba(request): ############################################################################ # ENTAIN (NEDS/LADBROKES) ############################################################################ # Query firestore database for NBA games nba_events = db.collection('entain_au').document('basketball_nba').collection('event_odds').stream() event_info = [doc.to_dict() for doc in nba_events] # print(event_info) # Filter NBA games by dates events_today = [event for event in event_info if event['event_odds']['Event']['StartTime'][:10] == games_today] events_tomorrow = [event for event in event_info if event['event_odds']['Event']['StartTime'][:10] == games_tomorrow] # print(events_today) # print('Tomorrow:', events_tomorrow) # … -
Assign image to a form field in django.views
I am in the middle of a project and I am stuck. I have a edit profile feature where a user can edit their profile. Everytime a profile is created with an empty profile_picture field a default value is provided. But once an image is assigned to field and then deleted. The field gets blank. What I want is everytime the field becomes None I want to reassign the default image by mentioning the file path. Heres My view where I save the model form:- if form.is_valid(): form.save(commit=False) print(form.cleaned_data) if 'avatar' in form.cleaned_data: if form.cleaned_data.get('avatar') is False: form.cleaned_data['avatar'] = image form.save() I want to mention the image path in place of image. Also suggest me some better ways for doing this. -
How to get distinct list of names from a consultation list, and show only latest consultation in Django?
What I want to accomplish is to get a unique list of the names of customers with their lastest consultation date. I have defined these models in my models.py file, using mySQL as my database: class Customer(models.Model): class ContactChoice(models.IntegerChoices): DO_NOT_CONTACT = 0 EMAIL = 1 TXT_SMS_VIBER = 2 mobile_num = models.CharField('Mobile Number', max_length=10, unique=True,) email_add = models.EmailField('Email', max_length=150, unique=True,) last_name = models.CharField('Last Name', max_length=30,) first_name = models.CharField('First Name', max_length=30,) contact_for = models.CharField('Contact For', max_length=60,) contact_on = models.IntegerField('Contact Using', choices=ContactChoice.choices, default=0,) customer_consent = models.BooleanField('With Consent?', default=False,) def __str__(self): return self.last_name + ', ' + self.first_name class Consultation(models.Model): consultation_date = models.DateTimeField('Date of Consultation', default=now) customer = models.ForeignKey(Customer, on_delete=models.SET_DEFAULT, default=1) concern = models.ForeignKey(SkinConcern, on_delete=models.SET_DEFAULT, default=1) consultation_concern = models.CharField('Other Concerns', max_length=120, null=True,) product = models.ForeignKey(Product, on_delete=models.SET_DEFAULT, default=1) user = models.ForeignKey(User, on_delete=models.SET_DEFAULT, default=1) store = models.ForeignKey(Store, on_delete=models.SET_DEFAULT, default=1) consultation_is_active = models.BooleanField('Is Active', default=True) def __str__(self): return self.customer.last_name + ", " + self.customer.first_name In my views.py, I have this for the Consultations page: distinct = Consultation.objects.values('customer').annotate(consultation_count=Count('customer')).filter(consultation_count=1) consults = Consultation.objects.filter(customer__in=[item['customer'] for item in distinct]) As mentioned, I was expecting to get a unique list of customer names with their latest consultation dates. This code results in only 1 record being shown. Can you point me in the … -
No Reverse Match at /admin/ in Wagtail
I'm getting this error while logging into my wagtail admin site. Please note, I'm just setting up the server in my Putty so it would be great to help me out on this. NoReverseMatch at /admin/ Reverse for 'wagtailadmin_explore' with arguments '('',)' not found. 1 pattern(s) tried: ['admin/pages/(?P<parent_page_id>[0-9]+)/\\Z'] Error during template rendering In template /home/ubuntu/venv/lib/python3.10/site-packages/wagtail/admin/templates/wagtailadmin/home/site_summary_pages.html, error at line 5 Reverse for 'wagtailadmin_explore' with arguments '('',)' not found. 1 pattern(s) tried: ['admin/pages/(?P<parent_page_id>[0-9]+)/\\Z'] 1 {% load i18n wagtailadmin_tags %} 2 3 <li> 4 {% icon name="doc-empty" %} 5 <a href="{% url 'wagtailadmin_explore' root_page.pk %}"> 6 {% blocktrans trimmed count counter=total_pages with total_pages|intcomma as total %} 7 <span>{{ total }}</span> Page <span class="visuallyhidden">created in {{ site_name }}</span> 8 {% plural %} 9 <span>{{ total }}</span> Pages <span class="visuallyhidden">created in {{ site_name }}</span> 10 {% endblocktrans %} 11 </a> 12 </li> 13 Page after login. I've tried migrations after dropping the table. I want the wagtail dashboard to be displayed with new pages to be added. It's not necessary to add existing data (I did try loaddata data.json method but I'm getting another issue for another time) but if there's any way to avoid this issue would be helpful. Thank you -
django queryset filter with back reference
I'm a C++ developer and noob of python, just following django tutorials. I want to know how to filter queryset by its back references' information. Below is my models. # models.py import datetime from django.db import models from django.utils import timezone class Question(models.Model): pub_date = models.DateTimeField('date published') class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) Now, I want to get query set of Question which pub_date is past from now AND is referenced by any Choice. The second statement causes my problem. Below are what I tried. # First method question_queryset = Question.objects.filter(pub_date__lte=timezone.now()) for q in question_queryset.iterator(): if Choice.objects.filter(question=q.pk).count() == 0: print(q) # It works. Only @Question which is not referenced # by any @Choice is printed. # But how can I exclude @q in @question_queryset? # Second method question_queryset = Question.objects.filter(pub_date__lte=timezone.now() & Choice.objects.filter(question=pk).count()>0) # Not works. # NameError: name 'pk' is not defined # How can I use @pk as rvalue in @Question.objects.filter context? Is it because I'm not familiar with Python syntax? Or is the approach itself to data wrong? Do you have any good ideas for solving my problem without changing the model? -
Pass a variable to another function and render an html template at the same time in django
We want to access the same variable in every function inside our views.py. Since it is not constant, we cannot use it as a global variable. Is it possible to pass a variable to another function while also rendering an HTML template? What are the alternatives if none exist? This is our login function in views.py def loginpage(request): errorMessage = '' # Applicant Login if request.method=="POST": if request.POST.get('username') and request.POST.get('pwd'): try: currentUser=Applicant.objects.get(username=request.POST['username'],pwd=request.POST['pwd']) currentUser=Applicant.objects.get(username=request.POST['username']) first = currentUser.firstname middle = currentUser.middleinitial last = currentUser.lastname AppDashboard = ApplicantDashboardPageView(currentUser, request) except Applicant.DoesNotExist as e: errorMessage = 'Invalid username/password!' return render(request, 'home.html') The currentUser variable inside our login function is the variable we want to pass in this function def ApplicantdashboardPageView(currentUser, request): appPeriod = ApplicationPeriod.objects.all() exam = ExaminationSchedule.objects.all() posts = Post.objects.all().order_by('-created_on') form = PostForm() name=userNaCurrent print('from storeCurrentUser', name) if request.method == "GET": try: posts = Post.objects.all().order_by('-created_on') form = PostForm() #applicantID=currentUser.id #applicantNotification = Applicant.objects.get(id=applicantID) return render(request, 'applicantdashboard.html', context={'UserName' : name, 'posts':posts, 'appPeriod':appPeriod, 'exam':exam}) except ObjectDoesNotExist: return render(request, 'applicantdashboard.html', context={'UserName' : name, 'posts':posts,}) return render(request, 'applicantdashboard.html', context={'UserName' : name, 'posts':posts, 'appPeriod':appPeriod, 'exam':exam}) I am new to Django so please bear with me if my question seem too basic. Thank you -
Docker file missing in volumn?
I now i using github and docker. inside the git repository include many docx and xlsx files in "app/media". When i push and pull docker image.i try to docker-compose exec -it web bash to access for inspect i see the files in 'app/media' is all missing and media folder in host is blank. How i can to solve this? version: '3.8' services: web: image: xxxx/myimage:latest command: gunicorn --workers=3 --threads=2 --worker-connections=3000 --timeout 300 project.wsgi:application --bind 0.0.0.0:8000 volumes: - ./static:/usr/src/app/static - ./media:/usr/src/app/media ports: - 8000:8000 env_file: - ./.env depends_on: - db db: image: postgres:13.0-alpine restart: always volumes: - ./database:/var/lib/postgresql/data/ environment: - POSTGRES_USER=${SQL_USER} - POSTGRES_PASSWORD=${SQL_PASSWORD} - POSTGRES_DB=${SQL_DATABASE} ports: - 5432:5432 nginx: image: nginx:1.13.0-alpine container_name: wrk-nginx restart: always ports: - "80:80" - "443:443" volumes: - ./nginx.conf:/etc/nginx/conf.d/default.conf - ./static:/home/app/web/static - ./media:/home/app/web/media - ./certbot/conf/:/etc/nginx/ssl/:ro depends_on: - web certbot: image: certbot/certbot:latest volumes: - ./certbot/conf/:/etc/letsencrypt/:rw pgbackups: container_name: Backup image: prodrigestivill/postgres-backup-local restart: always volumes: - /home/myuser/database:/backups links: - db:db depends_on: - db environment: - POSTGRES_HOST=db - POSTGRES_DB=${SQL_DATABASE} - POSTGRES_USER=${SQL_USER} - POSTGRES_PASSWORD=${SQL_PASSWORD} - POSTGRES_EXTRA_OPTS=-Z9 --schema=public --blobs - SCHEDULE=@every 0h30m00s - BACKUP_KEEP_DAYS=7 - BACKUP_KEEP_WEEKS=4 - BACKUP_KEEP_MONTHS=6 - HEALTHCHECK_PORT=81 -
How can i make a long polling api with django rest framework
I have a django backend and i'm using django rest framework for my api's, my application is a grading system application that sees change in grades in real time, I don't want to make too many requests to get updates from my server whenever a data is being updated in my server, so i heard of long polling, I've done my research and I've still not gotten any proper guide to implement long polling with django, even in the django channels documentation, please i really need help for this. i tried using polling at first and i got the real time updates but it stresses the server with too many requests, till i heard long polling was a better practice. -
Why won't my image save to my media directory?
I'm using Django. My image is saving when my form is submitted, but it is not saving to my media directory. It is only saving the file. For example, it is saving as "file.png" but not "avatars/file.png". I will note that it is saving as expected from within the admin portal. Here are my files: from django.db import models from django.contrib.auth import get_user_model class Profile(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) avatar = models.ImageField(default='avatars/Screenshot_2022-11-30_at_7.18.28_PM.png', upload_to='avatars/') header = models.FileField(default='headers/Screenshot_2022-11-30_at_7.18.28_PM.png', upload_to='headers/') followers = models.ManyToManyField(get_user_model(), related_name='followers', blank=True) from django.shortcuts import render, redirect, HttpResponseRedirect from django.contrib.auth import get_user_model from django.views.generic import ListView, DetailView, View from django.contrib.auth.mixins import LoginRequiredMixin from .models import Profile def updateProf(request): Profile.objects.filter(user_id=request.POST['user_id']).update(avatar=request.FILES['avatar']) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) {% extends 'base.html' %} {% load crispy_forms_tags %} {% block content %} <div class="signup-form"> <h2>Edit profile</h2> <form method="post" action="/update-prof" enctype="multipart/form-data"> {% csrf_token %} <input type="hidden" name="user_id" value="2"> <input type="file" name="avatar"> <button class="btn btn-success" type="submit">Save changes</button> </form> </div> {% endblock %} And my settings/urls file: MEDIA_URL = '/media/' MEDIA_ROOT = BASE_DIR / 'media' ] + static( settings.MEDIA_URL, document_root=settings.MEDIA_ROOT ) I thought that adding the enctype field/request.FILES would solve the issue, but it didn't. Anyone know how I can get the file to save to avatars/ ? -
Why isn't the number gotten from this random code generator function not being saved on the DB?
I am trying to generate a random redeem code for when a user purchases one of my products. The problem is that once the random code exists and the GetRandomRedeemCode function generates a new code, it won't get saved by Django in the DB. What could be the issue? This is the code that gets called whenever a new order is placed: def CompleteOrder(request): order_qs = Purchase.objects.filter(user=request.user, ordered=False) if order_qs: specific_order = order_qs[0] for order in specific_order.product_purchased.all(): order.item.purchased_by.add(request.user) specific_order.ordered = True specific_order.total_price = specific_order.get_total() *specific_order.redeem_code = GetRandomRedeemCode()* specific_order.save() return redirect("OrderCompletedSuccessURL") And this is the GetRandomRedeemCode() function that gets called to create a random code and to check if the random code is already in the DB, ie. uniqueness. def GetRandomRedeemCode(): random_num = str(random.randint(10000000,99999999)) if Purchase.objects.filter(redeem_code=random_num).exists(): GetRandomRedeemCode() else: return random_num -
Uncaught SyntaxError: Unexpected token '&' '
I have a django website where i want to include a js graph that plots prices against dates. I use (Plotly) https://plotly.com/javascript/ My problem is when i pass an array of dates (formatted 'yyyy/mm/dd') from my view in views.py into my html file which includes the code for my graph the dates have '&#x27 ;' either side of each date. views.py context = { "dates":['2022/12/03', '2022/12/04', '2022/12/05'], } return render(request, "App/minifig_page.html", context=context) inside html <script> ... var xArray = {{dates}}; ... </script> dates in browser view sources [&#x27 ;2022/12/03', &#x27 ;2022/12/04&#x27 ;, &#x27 ;2022/12/05&#x27 ;] This causes the dates to be improperly formatted and therefore the graph does not display. -
python collectstatic commad is not ran in Docker compose and gitlab
I am trying to run python manage.py collectstatic , in docker but nothing works, my python project misses some icons, and this command will solve the issue, but I can't know where to place the command, I have read several questions here but no luck. Below is my docker-compose.ci.stag.yml file: version: "3.7" services: web: build: context: . dockerfile: Dockerfile.staging cache_from: - guiostagingregisrty.azurecr.io/guio-tag:tag image: guiostagingregisrty.azurecr.io/guio-tag:tag expose: - 7000 env_file: .env Then my docker-compose.staging.yml file : version: '3.5' # sudo docker login -p <password> -u <username> services: api: container_name: api image: guiostagingregisrty.azurecr.io/guio-tag:tag ports: - 7000:7000 restart: unless-stopped env_file: - .env networks: - app-network watchtower: image: containrrr/watchtower volumes: - /var/run/docker.sock:/var/run/docker.sock - /root/.docker/config.json:/config.json command: --interval 30 environment: - WATCHTOWER_CLEANUP=true networks: - app-network nginx-proxy: container_name: nginx-proxy image: jwilder/nginx-proxy:0.9 restart: always ports: - 443:443 - 90:90 volumes: - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d - /var/run/docker.sock:/tmp/docker.sock:ro depends_on: - api networks: - app-network nginx-proxy-letsencrypt: image: jrcs/letsencrypt-nginx-proxy-companion env_file: - .env.prod.proxy-companion volumes: - /var/run/docker.sock:/var/run/docker.sock:ro - certs:/etc/nginx/certs - html:/usr/share/nginx/html - vhost:/etc/nginx/vhost.d - acme:/etc/acme.sh depends_on: - nginx-proxy networks: - app-network networks: app-network: driver: bridge volumes: certs: html: vhost: acme: then my Docker.staging file : # ./django-docker/app/Dockerfile FROM python:3.7.5-buster # set work directory WORKDIR /opt/app # Add current directory code to working directory … -
Passing a variable into a filter Django Rest Framework
I'm using a filter in my Django Rest Framework project to search for items in a given date range. I would like to pass variables into a url like so: /?start_date=2022-12-01&end_date=2022-12-06 but I can't seem to figure out how to insert 'start_date' and 'end_date' as variables you can search. The filter works when I do queryset = Search.objects.filter(added_date__range=["2022-12-06", "2022-12-06"]) but I would like it to be something like: queryset = Search.objects.filter(added_date__range=[start_date, end_date]) Here is the model: class Search(models.Model): added_date = models.CharField(max_length=256) added_time = models.CharField(max_length=256) id = models.BigIntegerField() name = models.CharField(max_length=256) View: class SearchViewSet(generics.GenericAPIView): def get_queryset(self): try: Search.objects.filter(added_date__range=[self.start_date, self.end_date]) except Exception as exception: return Response(response500('No Data Found', exception), status=status.HTTP_500_INTERNAL_SERVER_ERROR) def get(self, request): self.start_date = request.GET['start_date'] self.end_date = request.GET['end_date'] try: queryset = self.get_queryset() search_data = SearchSerializer(queryset, many=True) resp = {'data': search_data.data} response = Response(resp) return response except Exception as exception: return Response(response500('No Data Found', exception), status=status.HTTP_500_INTERNAL_SERVER_ERROR) Url: re_path(r'search-summary', views.SearchViewSet.as_view(), name='search-summary') -
a live stream site using reactjs and drf
hello guys i'm working on a livestream site using reactjs and drf for server side. and apparaently i want to acheieve three things. when a particular song(div) is clicked on and currently playing, i add a "play" to the class list. now when the user clicked on another song i want to remove that play from the initial div(song) that was clicked on and add it to the current div that was click ASAP. secondly, when the song is been played i'm having a delay in response(like i'd have to click twice first click will fetch the song then the second click will then play it. how can i rectify it so when i click once everything fetches and plays asap. i have used the fetch function and applied a call back yet still having same issues. when i play a song it appears on all audio tags in all divs(music) i think that due to my usesstate setup and the way i am rendering it please how can i sought it so that each music(div) handles there own audio tag when played? Thanks const Home=()=>{ const audio=document.querySelector('#audio') const music_container=document.querySelector('#music_container') const [image, setImage]=useState('') const [posts, setPosts]=useState([]) const [icon,setIcon]=useState(faPlay) const[playing,setPlaying]=useState(false) const[music,setMusic]=useState('') … -
How change the url of an image within an html page in a django project?
I'm new to Django. I have 2 images, one for NP environment and one for Production environment. I have to make each image stay in its given environment. This is to be done in an html page within Django. This html page is the body of an email. can you help me? The image looks like below. And I want to control her link according to the environment she is in <td bgcolor="#fff" align="right" style="padding: 21px 19px 18px"> <img alt="Teste" src="https://.../mail/logo.png" width="210px" /> </td> -
Django Viewset method accepts get request while it's actually a post
I defined my urlpattern as follows: urlpatterns = [ ... path('api/cluster/<int:cluster_id>/topic/save', TopicView.as_view({'post': 'save_topic'}), name='save_topic'), ... and here's my view: class TopicView(viewsets.ViewSet): permission_classes = (IsAuthenticated, IsAdminUser, ) authentication_classes = (JWTAuthentication, ) def save_topic(self, request, cluster_id): # saves specific data I can access this method via GET, but POST is not allowed. My CORS settings is as follows: CORS_ORIGIN_ALLOW_ALL=True I tried: @action(methods=['post'], detail=False) def save_topic(self, request, cluster_id): Nothing changed. What am I missing? -
Can I install Python, Django and other packages on a USB device and and run a server from this USB?
I would like to have a Django server on a Windows machine which is not connected to Internet. For that, would it be possible to install, from another Windows machine connected to Internet, Python, PyCharm, Django and other packages to a USB device that I will then connect to the other Windows machine in order to start the application ? Would it work without problems ? Thanks ! - -
django translation doesn't work although dgango_language cookie is set
It's been 3 days and I'm getting tired of this. Here's my setting file: from pathlib import Path from django.utils.translation import gettext_lazy as _ # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/4.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = "django-insecure-z$__b9aa(_3!czi7ssop9cr2lae^9)f^!_kq+y_n=+6u=ul!%q" # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # Application definition INSTALLED_APPS = [ "django.contrib.admin", "django.contrib.auth", "django.contrib.contenttypes", "django.contrib.sessions", "django.contrib.messages", "django.contrib.staticfiles", "mainapp", ] 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.locale.LocaleMiddleware', "django.middleware.clickjacking.XFrameOptionsMiddleware", ] ROOT_URLCONF = "soroushprojects.urls" TEMPLATES = [ { "BACKEND": "django.template.backends.django.DjangoTemplates", "DIRS": ['templates'], "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", 'django.template.context_processors.i18n', ], }, }, ] WSGI_APPLICATION = "soroushprojects.wsgi.application" # Database # https://docs.djangoproject.com/en/4.1/ref/settings/#databases DATABASES = { "default": { "ENGINE": "django.db.backends.sqlite3", "NAME": BASE_DIR / "db.sqlite3", } } # Password validation # https://docs.djangoproject.com/en/4.1/ref/settings/#auth-password-validators AUTH_PASSWORD_VALIDATORS = [ { "NAME": "django.contrib.auth.password_validation.UserAttributeSimilarityValidator", }, {"NAME": "django.contrib.auth.password_validation.MinimumLengthValidator",}, {"NAME": "django.contrib.auth.password_validation.CommonPasswordValidator",}, {"NAME": "django.contrib.auth.password_validation.NumericPasswordValidator",}, ] # Internationalization # https://docs.djangoproject.com/en/4.1/topics/i18n/ LANGUAGE_CODE = "en" TIME_ZONE = "UTC" USE_I18N = True USE_TZ = True LAGUAGES = ( ('en', _('English')), ('fa', _('Persian')), ) LOCALE_PTHS = [ BASE_DIR / … -
Why this DeleteView doesn't actually delete the entry in Django?
In my Django app the delete view doesn't work. When I click on an entry the page just refreshes and nothing happens. The entry is not deleted from the database. Creating and updating entries works fine. Is there something wrong with any of the files? microtarjetas/views.py: class DeleteCardView(DeleteView): model = Card template_name = 'microtarjetas/delete_card.html' form_class = CardForm success_url = '/cards/' templates/microtarjetas/delete_card.html: {% extends 'base.html' %} {% load static %} {% block content %} <h2>Delete card</h2> <p>Are you sure you want to delete "{{ object }}"?</p> <form method="post">{% csrf_token %} <input type="submit" value="Confirm" /> </form> {% endblock %} a snippet from templates/microtarjetas/cards.html: <tbody> {% for card in cards %} <tr> <td>{{ card.word_en }}</td> <td>{{ card.word_es }}</td> <td><a href="{% url 'update_card' card.pk %}">update</a></td> <td><a href="{% url 'delete_card' card.pk %}">X</a></td> </tr> {% endfor %} </tbody> forms.py: from django import forms from .models import Card class CardForm(forms.ModelForm): class Meta: model = Card fields = "__all__" models.py: class Card(models.Model): word_en = models.CharField(max_length = 30) word_es = models.CharField(max_length = 30) def get_absolute_url(self): return "/cards" def __str__(self): return f"{self.word_en} --- {self.word_es}" urls.py: from django.urls import path from . import views urlpatterns = [ path('', views.HomeView.as_view(), name='home'), path('cards/', views.CardsView.as_view(), name='cards'), path('cards/new', views.CreateCardView.as_view(), name='create_card'), path('cards/<pk>/delete/', views.DeleteCardView.as_view(), name='delete_card'), path('cards/<pk>/update/', views.UpdateCardView.as_view(), … -
nginx 502 bad gateway error with Django webapp hosted on AWS EC2
Ever since rebooting my Ubuntu EC2 instance, I have an issue with nginx giving a 502 error for my site. I didn't change any settings before the reboot and the site was working fine before then. Error from /var/log/nginx/error.log: 2022/12/06 21:10:54 [error] 1503#1503: *4 connect() failed (111: Unknown error) while connecting to upstream, client: ###.##.##.###, server: ##.#.###.###, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8000/favicon.ico", host: "##.#.###.###", referrer: "http://##.#.###.###/" Here is my config in /etc/nginx/sites-available/: server_tokens off; access_log /var/log/nginx/esms.access.log; error_log /var/log/nginx/esms.error.log; # This configuration will be changed to redirect to HTTPS later server { server_name .##.#.###.###; listen 80; location / { proxy_pass http://127.0.0.1:8000; proxy_set_header Host $host; } location /static { autoindex on; alias /home/ubuntu/ESMS/esms/static/; } } And the output of netstat -plnt: sudo netstat -plnt Active Internet connections (only servers) Proto Recv-Q Send-Q Local Address Foreign Address State PID/Program name tcp 0 0 0.0.0.0:22 0.0.0.0:* LISTEN 664/sshd: /usr/sbin tcp 0 0 0.0.0.0:80 0.0.0.0:* LISTEN 1567/nginx: master tcp 0 0 127.0.0.53:53 0.0.0.0:* LISTEN 420/systemd-resolve tcp6 0 0 :::22 :::* LISTEN 664/sshd: /usr/sbin tcp6 0 0 :::80 :::* LISTEN 1567/nginx: master -
Nginx 400 Error - client sent plain HTTP request to HTTPS port while reading client request headers
I recently added a SSL certificate to my website using Let's Encrypt and have noticed that when I try to access my website using either HTTP or HTTPS, the site will load correctly most of the time, but sometimes it will return a 400: Bad Request error. Refreshing the page after that will usually return me to the working HTTPS site, but I am having trouble understanding why this error only occurs sometimes. The current site is using Django, Gunicorn, Nginx, and AWS EC2 with a load balancer and the SSL certificate is for the EC2 instance, if this makes a difference. nginx.conf user www-data; worker_processes auto; pid /run/nginx.pid; include /etc/nginx/modules-enabled/*.conf; events { worker_connections 768; # multi_accept on; } http { ## # Basic Settings ## sendfile on; tcp_nopush on; tcp_nodelay on; keepalive_timeout 65; types_hash_max_size 2048; # server_tokens off; # server_names_hash_bucket_size 64; # server_name_in_redirect off; include /etc/nginx/mime.types; default_type application/octet-stream; ## # SSL Settings ## ssl_protocols TLSv1.2 TLSv1.3; # Dropping SSLv3, ref: POODLE ssl_prefer_server_ciphers on; ## # Logging Settings ## access_log /var/log/nginx/access.log; error_log /var/log/nginx/error.log info; ## # Gzip Settings ## gzip on; ## # Virtual Host Configs ## include /etc/nginx/conf.d/*.conf; include /etc/nginx/sites-enabled/*; } sites-enabled .conf file server { listen 80; server_name … -
How to retrieve attributes from a foreign key related model to another foreign key related model?
I'm using django 4.1.2 with python 3.10.8. I have three models one for user management, one for questions and another for answers. They are described below: class User(AbstractUser): phone_number = models.CharField(max_length=14, unique=True) first_name = models.CharField(max_length=40) father_name = models.CharField(max_length=40) email = models.EmailField(unique=True, required=True) age = models.CharField(max_length=3) username = models.CharField(max_length=8, required=True) class Question(models.Model): question = models.CharField( max_length=500, null=False, unique=True ) creating_staff = models.ForeignKey( User, null=False, on_delete=models.PROTECT, to_field="phone_number", ) options = models.JSONField(null=False) correct_option = models.CharField(max_length=250, null=False) question_ts = models.DateTimeField(auto_now_add=True, null=False) class Meta: verbose_name = "Question" def __str__(self) -> str: return f"{self.question}" class Answer(models.Model): answer = models.CharField(max_length=500, null=False) question_answered = models.ForeignKey( Question, null=False, on_delete=models.PROTECT, related_name="question_answered" ) answering_user = models.ForeignKey( User, null=False, on_delete=models.PROTECT, to_field="phone_number", related_name="answerer" ) status = models.BooleanField(null=False) answer_ts = models.DateTimeField(auto_now_add=True, null=False) class Meta: verbose_name = "Answer" def __str__(self) -> str: return f"{self.answer} -- {self.answering_user}" This is the urls.py file: from django.urls import path from commons.views import (AnswerView) app_name = "commons" urlpatterns = [ path("play/", AnswerView.as_view(), name="play"), ] What I'm trying to do is whenever a user has logged in a wants to answer a set of questions by going to /commons/play/, on the GET request I want to parse out all the previous questions that user has answered and always display new questions. …