Django community: Django Q&A RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Automatically create a subdomain and associate it with its own front-end (Reactjs) and back-end (django)
I'm trying to build a SaaS website. The user registers an account and then automatically creates a subdomain, and based on his plan, the main site automatically links it with a react js frontend and an independent backend using Django After searching I found that I have to use the django_tenants library and Wildcard domain But the problem is that this only achieves the first part, which is only the creation of the subdomain, and I did not find any way to transfer the files and the independence of the subdomain with its files -
Django Form Not Rendering on Html
#forms.py from django import forms from django.forms import ModelForm from .models import Account class SignupForm(forms.ModelForm): class Meta: model = Account fields = ['first_name', 'last_name'] -
how can i create a cycle of comments and replies?
I wonder how can I make a cycle of comments and replies : I wanted to make a replyable comment but replies also need to be replyable to make a better communication but I'm just a student and don't have much experience here is my models : class Comment(models.Model): #comments model post = models.ForeignKey(Post, on_delete=models.CASCADE) text = models.CharField(max_length=300) user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) class Meta(): verbose_name_plural = 'Comments' ordering = ['date'] def __str__(self): return self.test[:50] class Reply(models.Model): #replying to comments comment = models.ForeignKey(Comment,on_delete=models.CASCADE) text = models.CharField(max_length=300) user = models.ForeignKey(get_user_model(),on_delete=models.CASCADE) date = models.DateTimeField(auto_now_add=True) class Meta(): verbose_name_plural = 'Replies' ordering = ['date'] def __str__(self): return self.text[:50] problem is that if i use this models i have to make a new model for every reply and it's not in cycle. also I tried to check if replyable comment works or not and i got a problem with view: I couldn't add both forms(comment, reply) in the same get_context_data() class PostDetailView(FormView, DetailView): #detail page of items template_name = 'pages/post_detail.html' model = Post form_class = CommentForm, ReplyForm def get_context_data(self, **kwargs): context = super(PostDetailView, self).get_context_data(**kwargs) context['form'] = self.get_form() return context def post(self,request, *args, **kwargs): form = CommentForm(request.POST) if form.is_valid(): form_instance = form.save(commit=False) form_instance.user = self.request.user … -
Axios CORS unable to see any response header
Hi I have a frontend being served for testing from localhost making request to backend running at api.whatify.io which is an Nginx server fronting a Django backend. The client app code is: const axiosApi = axios.create({ baseURL: API_URL, withCredentials: true, }) export async function post(url, data, config = {}) { return axiosApi .post(url, {...data }, {withCredentials: true}) .then(response => response.data) .then(response => { console.log("response is", response); console.log("WOW GOT", response.headers); console.log("CUSTOM", response.headers.get("Cache-Control")); }) } The request and response headers are as follows as seen from browser: Request URL: https://api.whatify.io/auth/login Request Method: POST Status Code: 302 Remote Address: 54.194.218.202:443 Referrer Policy: strict-origin-when-cross-origin Response Headers: access-control-allow-credentials: true access-control-allow-origin: http://localhost:5173 access-control-expose-headers: accept, accept-encoding, authorization, content-type, dnt, origin, user-agent, x-csrftoken, x-requested-with, cache-control, pragma, Set-Cookie content-length: 0 content-type: text/html; charset=utf-8 cross-origin-opener-policy: same-origin date: Sun, 05 Feb 2023 01:21:28 GMT location: / referrer-policy: same-origin server: nginx/1.21.6 set-cookie: csrftoken=zaBGdsPdVSEm1ZRvgNKuGxQcr2mRJvhh; expires=Sun, 04 Feb 2024 01:21:28 GMT; Max-Age=31449600; Path=/; SameSite=None; Secure set-cookie: sessionid=z3gygehf6gcwuc5pdq2v8kzff61ipcss; expires=Sun, 19 Feb 2023 01:21:28 GMT; HttpOnly; Max-Age=1209600; Path=/; SameSite=None; Secure vary: Origin, Cookie x-content-type-options: nosniff x-frame-options: DENY Request Headers :authority: api.whatify.io :method: POST :path: /auth/login :scheme: https accept: application/json, text/plain, */* accept-encoding: gzip, deflate, br accept-language: en-US,en;q=0.9 content-length: 44 content-type: application/json origin: http://localhost:5173 referer: http://localhost:5173/ sec-ch-ua: … -
Cannot runserver from Pycharm using Vagrant Interpreter. Path for manage.py is wrong, don't know where to fix it
I'm trying to configure correctly Pycharm (for a Django project) + Vagrant, to launch the runserver remotely from my host machine (and thus enable debugging). The command for such seems simple but the path is wrong, so it fails. It tries to run /home/vagrant/.virtualenvs/[myprojname]/bin/python /vagrant/[myprojname]/manage.py runserver 0.0.0.0:8000 Second parameter is wrong, it's missing either the initial /home/ or it isn' a relative path. My run configuration I'm running a host windows machine, and a vagrant ubuntu 20.10 guest VB. I setup my remote interpreter with what I suppose are the right parameters. In my vagrantfile I have setup the shared folder as following (Project name is PoeMogul) config.vm.synced_folder "PoeMogul", "/home/vagrant/PoeMogul" In my vagrant box, everything is setup fine (I think). I have my venv. In my /home/vagrant/PoeMogul dir i can see my working directory from PyCharm. I can manually (through vagrant ssh) run the server. But i cannot make Pycharm invoke the manage.py file correctly, it tries to access "/vagrant/..." and not "/home/vagrant/...". -
How to paginate multiple queries in a single function-based-view or class-based-view in django?
I have a search function that queries multiple models. I have the expected results displayed in a html template and so far all is fine. The problem is that I want to paginate the results using django's built in Pagination class. Pagination with multiple models is where I'm now stuck. I have other class based views working well paginating single models. def search_results(request): if request.method == 'POST': searched = request.POST['searched'] books = Book.objects.filter(description__icontains=searched, title__icontains=searched).order_by('-id') sermons = Sermon.objects.filter(description__icontains=searched, title__icontains=searched).order_by('-id') other_sermons = SermonsByOtherFathers.objects.filter(description__icontains=searched, title__icontains=searched).order_by('id') other_books = BooksByOtherFathers.objects.filter(description__icontains=searched, title__icontains=searched).order_by('-id') context = { 'searched': searched, 'sermons': sermons, 'other_sermons': other_sermons, 'books': books, 'other_books': other_books, } if searched == "": return HttpResponse('Please type something in the search input.') return render(request, "search_results.html", context) This is a simplified version of my html template. {% for book in books %} <tr> <td> <a href="{{ book.book_instance.url }}"> {{ book.title }} </a> <p> {{book.author}} </div> <p> {{ book.category }} </p> <p> {{ book.description }} </p> </td> </tr> {% endfor %} <-- ...and the same loops goes for the rest of the other querysets. --> {% for book in other_books %} <-- code here --> {% endfor %} {% for sermon in sermons %} <-- code here --> {% endfor %} {% … -
issues with serving 2 django applications with apache in ubuntu server using wsgi
i'm trying to host a second domain in my ubuntu vps (domain2), i read online that is possible to host 2 domains in one vps (with one ip adress) yet i'm having some issues with it. i have this configuration in apache2 ubuntu under /etc/apache2/sites-enabled/000-default-le-ssl.conf: Define wsgi_daemon1 "domain1" Define wsgi_daemon2 "domain2" <IfModule mod_ssl.c> <VirtualHost *:443> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /home/my_linux_user/myproject/static <Directory /home/my_linux_user/myproject/static> Require all granted </Directory> <Directory /home/my_linux_user/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> <IfDefine !wsgi_init> WSGIDaemonProcess ${wsgi_daemon1} python-path=/home/my_linux_user/myproject python-home=/home/my_linux_user/myproject/myprojectenv WSGIProcessGroup ${wsgi_daemon1} WSGIScriptAlias / /home/my_linux_user/myproject/myproject/wsgi.py Define wsgi_init 1 </IfDefine> ServerName domain1.tn SSLCertificateFile /etc/letsencrypt/live/domain1.tn/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/domain1.tn/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> <VirtualHost *:443> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error_project2.log CustomLog ${APACHE_LOG_DIR}/access_project2.log combined Alias /static /home/my_linux_user/project2/static <Directory /home/my_linux_user/project2/static> Require all granted </Directory> <Directory /home/my_linux_user/project2/django_project> <Files wsgi.py> Require all granted </Files> </Directory> <IfDefine !wsgi_init> WSGIDaemonProcess ${wsgi_daemon2} python-path=/home/my_linux_user/project2 python-home=/home/my_linux_user/project2/project2ENV WSGIProcessGroup ${wsgi_daemon2} WSGIScriptAlias / /home/my_linux_user/project2/django_project/wsgi.py Define wsgi_init 1 </IfDefine> ServerName domain2 SSLCertificateFile /etc/letsencrypt/live/domain2/fullchain.pem SSLCertificateKeyFile /etc/letsencrypt/live/domain2/privkey.pem Include /etc/letsencrypt/options-ssl-apache.conf </VirtualHost> </IfModule> the first domain is served correctly but the second domain (domain2) is not, it actually still pointing to the default apache2 index page i tried restarting apache2 with: apachectl restart and with apachectl graceful checking the DNS configuration, the domaain … -
modelformset update multiple instance of model
I am trying to update multiple instance of a model using modelformset_factory to render out the said instances im my forms at one but it doesn't work. views.py: def approve(request,pk): user = User.objects.get(id=pk) requests = PendingRequest.objects.filter(member=user) RequestFormset = modelformset_factory(PendingRequest, form=Approve ,extra=0) if request.method == "POST": formset = RequestFormset(request.POST, queryset=requests) if formset.is_valid(): for form in formset: form.save() else: formset = RequestFormset(queryset=requests) return render(request, "books/approve.html",{"formset":formset, "users":requests}) forms.py: class Approve(forms.ModelForm): class Meta: model = PendingRequest exclude = ["member", "book_request", "not_approved"] models.py: class PendingRequest(models.Model): book_request = models.ForeignKey(BorrowBook, on_delete=models.CASCADE, null=True) member = models.ForeignKey(User, on_delete=models.CASCADE, default="", null=True) book = models.ForeignKey(Books, on_delete=models.CASCADE, default="", null=True) approved = models.BooleanField(default=False) not_approved = models.BooleanField(default=False) approval_date = models.DateTimeField(auto_now=True, null=True) template <body> <form method="post" action="{% url 'approve' pk=users.0.member.id %}"> {% csrf_token %} {% for form in formset.management_form %} {{form}} {% endfor %} <table> <thead> <tr> <th>Book Title</th> <th>Approved</th> <th>Not Approved</th> </tr> </thead> <tbody> {% for form in formset %} <tr> <td>{{ form.book }}</td> <td>{{ form.approved }}</td> </tr> {% endfor %} </tbody> </table> <button type="submit">Update</button> </form> </body> Whenever i click on the submit button in my template, it doesn't post any data to database. Any ideas on how to fix it. I also want to be able to set not_approved field to false if … -
Django: How to go to a URL with select option using views.py GET or POST instead of a JavaScript function
I show two solutions, one with GET, the other with POST. In both I have errors. GET case In templates I have the following form (I omit the JavaScript call that submits the form) <form id="myform" action="{% profiles:profile-detail slug=x.user %}" method="GET"> <select> <option value="view">View</option> </select> </form> In views.py I have class ProfileView(DetailView): model = Profile def get_object(self, *args, **kwargs): slug = self.kwargs.get('slug') user = User.objects.get(username=slug) profile = Profile.objects.get(user=user) return profile This approach takes me to the profile page of {{x.user}}=user1, however when I click the backward button in the browser, it goes from mypath/user1 to mypath/user1?. I don't like this ?. To go back to the previous page I would need to click the backward button twice. I would like to click it only once and remove this ? transition step. POST case In templates: <form id="myform" action="{% profiles:profile-detail slug=x.user %}" method="GET"> {% csrf_token %} <input type="hidden" name="slug" value={{x.user}}> <select> <option value="view">View</option> </select> </form> In views.py class ProfileView(LoginRequiredMixin, DetailView): model = Profile def post(self,request,slug): myslug = request.POST.get(slug) User = get_user_model() user = User.objects.get(username=myslug) profile = Profile.objects.get(user=user) return profile This shows the error DOESNOTEXIST. User matching query does not exist. the error page shows myslug=None and slug=user1. What would be an … -
How to use the OpenAI stream=true property with a Django Rest Framework response, and still save the content returned?
I'm trying to use the stream=true property as follows. completion = openai.Completion.create( model="text-davinci-003", prompt="Write me a story about dogs.", temperature=0.7, max_tokens=MAX_TOKENS, frequency_penalty=1.0, presence_penalty=1.0, stream=True, ) Unfortunately, I don't know what to do from here to return it to my React frontend. Typically, I've used standard response objects, setting a status and the serializer.data as the data. From my readings online, it seems I have to use the StreamingHttpResponse, but I'm not sure how to integrate that with the iterator object of completion, and actually save the outputted data once it is done streaming, as the view will end after returning the iterator to the endpoint. Any help? -
How to fix? Error 500: No WSGI daemon process called... (Apache/ Django)
I have an internal Server Error 500 on my Django Server. When I check the error.log, I get the following error: No WSGI daemon process called "..." has been configured: "..." I hope someone can help me to fix this Error. Here is my Apache config: <VirtualHost *:80> ServerAdmin ADMIN ServerName DOMAIN ErrorLog /home/USER/PROJECT/site/logs/error.log CustomLog /home/PROJECT/PROJECT/site/logs/access.log combined Alias /static /home/USER/PROJECT/static <Directory /home/USER/PROJECT/static> Require all granted </Directory> <Directory /home/USER/PROJECT/src/social> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess PROJECT python-path=/home/USER/PROJECT/ python-home=/home/USER/PROJECT/VIRTUALENV WSGIProcessGroup PROJECT WSGIScriptAlias / /home/USER/PROJECT/src/social/wsgi.py </VirtualHost> -
Django runserver not working; Did I miss something?
It's been a while since I posted anything here, and now my problems have become more advanced. For reference, I'm running on Win10. I'm trying to use the Django framework. Python's been installed on my computer forever; it's the latest version, and it's installed on environment variables/added to system paths. I think those are enabled by default, but I did make sure that they were checked when I reinstalled it. pip's been updated too. Django installed successfully. I managed to get all the way to installing my new project with django-admin startproject PROJECTNAME, but when I try to run python3 manage.py runserver I'm getting this error: Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. ...Interesting. If I type in python --version, I get a response (Python 3.11.0). Here's what I get if I do pip freeze: asgiref==3.6.0 Django==4.1.6 sqlparse==0.4.3 tzdata==2022.7 Python IDLE runs fine; all .py files run fine. Alright. So, with that in mind and in accordance to a lot of popular advice I've seen floating around, I added the Path to my Environment Variables. For space-saving reasons, my Python is installed on … -
Defaulting to user installation because normal site-packages is not writeable : While nstallinng DjangoCorsHeaders
$ pip3 install django-cors-headers $ Defaulting to user installation because normal site-packages is not writeable I got this Error . I tried $ python3.10 -m pip install django-cors-headers But it's not works for mycase . -
Issue importing application in Django in urls.html
My src directory's layout is the following: Learning innit.py settings.py urls.py wsgi.py pages innit.py admin.py apps.py models.py tests.py views.py Views.py has this code from django.shortcuts import render from django.http import HttpResponse def home_view(*args,**kwargs): return HttpResponse("<h1>Hello World, (again)!</h1>") urls.py has this code """Learning URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/4.1/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the include() function: from django.urls import include, path 2. Add a URL to urlpatterns: path('blog/', include('blog.urls')) """ from django.contrib import admin from django.urls import path from pages.views import home_view urlpatterns = [ path("", home_view, name = "home"), path('admin/', admin.site.urls), ] The part where it says 'pages.views' in 'from pages.views import home_view' has a yellow/orange squiggle underneath it meaning that it is having problems importing the file and it just doesn't see the package/application called 'pages' and doesn't let me import it even though the package has a folder called 'innit.py'. Even worse is the fact that the tutorial I … -
Django ALLOWED_HOSTS settings
I developing a mobile application, using react-native like a front-end and python Django REST framework like a back-end. The question is what I should write in Django settings.py ALLOWED_HOSTS, besides my server's adress? I don't use any website like a front-end, because my application is on App Store and Google Play. If I will write ['*'], it certainly will work, but it is not a safe method -
Unable to load fixture for through model django
What I am trying to do? I have created a fixture for my through model and now I want to load it in my database. What is the problem? While loading the fixture using Django loaddata command for through model I get this error: django.core.serializers.base.DeserializationError: Problem installing fixture '<fixture-path>/fixtures/m.json': ['“Dave Johnson” value must be an integer.']: (room.membership:pk=None) field_value was 'Dave Johnson' models.py class Person(models.Model): name = models.CharField(max_length=100, unique=True) def natural_key(self): return self.name class Group(models.Model): name = models.CharField(max_length=100, unique=True) members = models.ManyToManyField(Person, through='Membership') def natural_key(self): return self.name class Membership(models.Model): person = models.ForeignKey(Person, on_delete=models.CASCADE) group = models.ForeignKey(Group, on_delete=models.CASCADE) joined_on = models.DateTimeField(auto_now_add=True) def natural_key(self): return self.person.name, self.group.name I am creating fixture like this: python manage.py dumpdata room.Membership --pks='12' --natural-foreign --natural-primary > m.json which creates the following json: [ { "model": "room.membership", "fields": { "person": "Dave Johnson", "group": "Django Learning", "joined_on": "2020-12-03T13:14:28.572Z" } } ] I have also added get_by_natural_key method in the manager for through model like this: class MembershipManager(models.Model): def get_by_natural_key(self, person_name, group_name): return self.get(person__name=person_name, group__name=group_name) But loading the fixture like below gives the above error python manage.py loaddata m.json Loading of fixtures for other models is working fine but it only happens with through model. -
showing two model in same page Django
I have two models : class Post(models.Model): title= models.CharField(max_length=255) author = models.ForeignKey(User, on_delete=models.CASCADE) body = models.TextField() postimage = models.ImageField(null= True, blank= True, upload_to="images/") created_date = models.DateTimeField(default=timezone.now) published_date = models.DateTimeField(blank=True, null=True) def publish(self): self.published_date = timezone.now() self.save() def __str__(self): return self.title + " | "+ str(self.author) def get_absolute_url(self): return reverse('article_deatil', args=(str(self.id))) class AboutMe(models.Model): title1= models.CharField(max_length=255, default="About Me") body = models.TextField() skill1= models.CharField(max_length=255) skill1body = models.TextField() skill2= models.CharField(max_length=255) skill2body = models.TextField() skill3= models.CharField(max_length=255) skill3body = models.TextField() edu1=models.CharField(max_length=255) edu1body = models.TextField() edu2=models.CharField(max_length=255) edu2body = models.TextField() edu3=models.CharField(max_length=255) edu3body = models.TextField() def __str__(self): return self.title1 I want to show both of them in my home.html class HomeView(ListView): model = Post template_name = 'home.html' queryset = Post.objects.order_by('-published_date')[:3] url.py urlpatterns = [ path('',HomeView.as_view(), name="home"), path('',PostViewList.as_view(), name="postlist"), ] I'm new to django and not sure how to show case two model in one template. I did put the post.body and other tags in my html but it not showing the About me part. I really appreciate your help. thank you -
facing this error while trying to get request invalid literal for int() with base 10: b'10 00:00:00'
i was trying to do get request to the url http://127.0.0.1:8000/books/list/ but im now facing an erorr invalid literal for int() with base 10 `i was trying to do get request to the url http://127.0.0.1:8000/books/list/ but im now facing an erorr invalid literal for int() with base 10` #my views.py from django.shortcuts import render from book_api.models import Book from django.http import JsonResponse from book_api.serializer import BookSerializer from rest_framework.response import Response from rest_framework.decorators import api_view # Create your views here. @api_view(['GET']) def book_list(request): books=Book.objects.all() serializer=BookSerializer(books,many=True) return Response(serializer.data) @api_view(['POST']) def book_create(request): serializer=BookSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data) else: return Response(serializer.errors) #my serializer.py from rest_framework import serializers from book_api.models import Book class BookSerializer(serializers.Serializer): id=serializers.IntegerField(read_only=True) title=serializers.CharField() number_of_pages=serializers.IntegerField() publish_date=serializers.DateField() quantity=serializers.IntegerField() def create(self,data): return Book.objects.create(**data) #book_api.urls from django.contrib import admin from django.urls import path from book_api.views import book_list,book_create urlpatterns = [ path('',book_create), path('list/',book_list) # book/urls.py """BOOK URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.2/topics/http/urls/ Examples: Function views 1. Add an import: from my_app import views 2. Add a URL to urlpatterns: path('', views.home, name='home') Class-based views 1. Add an import: from other_app.views import Home 2. Add a URL to urlpatterns: path('', Home.as_view(), name='home') Including another URLconf 1. Import the … -
Multilingual site django
I need to make a multilingual website and have found instructions on how to do this. I did everything according to the instructions but when I write /en/ for example nothing happens settings.py 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.0/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # LOGIN_URL = '/users/login' AUTH_USER_MODEL = 'users.User' LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' # Application definition SITE_ID = 1 INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'MainConv', 'users', 'modeltranslation', 'gettext', ] LANGUAGES = [ ('en', _('English')), ('ru', _('Russian')), ] LOCALE_PATHS = [ BASE_DIR / 'locale/', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'Converter.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 = 'Converter.wsgi.application' # Database # https://docs.djangoproject.com/en/4.0/ref/settings/#databases DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'sxgc1', … -
Apach24 and Django in Windows
I would be very grateful if anyone can help. I am trying to start Apache server on my laptop with Windows 11. I entered command "mod_wsgi-express module-config" and got next: LoadFile "C:/Program Files/WindowsApps/PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0/python310.dll" LoadModule wsgi_module "C:/Users/Sergey/ProgPython/CabeeFashion/my_env1/lib/site-packages/mod_wsgi/server/mod_wsgi.cp310-win_amd64.pyd" WSGIPythonHome "C:/Users/Sergey/ProgPython/CabeeFashion/my_env1" All these I added to httpd.conf file, but when I am trying to start httpd.exe, I am getting next error:cannot load httpd.exe: Syntax error on line 539 of C:/Users/Sergey/ProgPython/CabeeFashion/Apache24/conf/httpd.conf: Syntax error on line 1 of C:/Users/Sergey/ProgPython/CabeeFashion/Apache24/conf/extra/httpd-wsgi.conf: Cannot load C:/Program Files/WindowsApps/PythonSoftwareFoundation.Python.3.10_3.10.2288.0_x64__qbz5n2kfra8p0/python310.dll into server: \xce\xf2\xea\xe0\xe7\xe0\xed\xee \xe2 \xe4\xee\xf1\xf2\xf3\xef\xe5. I used extart file httpd-wsgi.conf and included it in httpd.conf Include conf/extra/httpd-wsgi.conf How can I fix this. Why http.exe says me cannot lod file, if it exists. I have checked version of Apache and wsgi modules, all of them are 64. VC is installed. -
ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' (render.com)
I'm trying to deploy a simple CRUD Django app suing the service of render.com. I have set up the config based on their documentation, but when I try to deploy it, the error ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' comes up. Build error Feb 4 10:45:16 AM ==> Cloning from https://github.com/user/django-crud-app... Feb 4 10:45:20 AM ==> Checking out commit ed701ede6bde3f7c7abd1378f656c7763b063917 in branch main Feb 4 10:45:24 AM ==> Using Python version: 3.7.10 Feb 4 10:45:28 AM ==> Running build command 'pip3 install -r requirements.txt'... Feb 4 10:45:29 AM ERROR: Could not open requirements file: [Errno 2] No such file or directory: 'requirements.txt' Feb 4 10:45:29 AM WARNING: You are using pip version 20.1.1; however, version 23.0 is available. Feb 4 10:45:29 AM You should consider upgrading via the '/opt/render/project/src/.venv/bin/python -m pip install --upgrade pip' command. Feb 4 10:45:29 AM ==> Build failed 😞 Feb 4 10:45:29 AM ==> Generating container image from build. This may take a few minutes... I have generated my requirements.txt See Image Here asgiref==3.6.0 autopep8==2.0.1 dj-database-url==1.2.0 Django==4.1.5 gunicorn==20.1.0 psycopg2-binary==2.9.5 pycodestyle==2.10.0 sqlparse==0.4.3 whitenoise==6.3.0 No sure what el to do. I try to deploy a Django app with render.com -
Updating a django form involving 2 seperate functions (template function & form specific function)
I am trying to a update a form from a separate function. By clicking on button "Add" the existing form is updated by adding a user to the form. Adding the user to the form works fine. However I am loosing the text input from the initial form when submitting my update. The reason why I am using 2 functions is because I have multiple forms on the same template: each form is redirected to a specific url defined in action="{% url %}" The usual way I use to update a form is as follows: def function(request, id) instance = get_object_or_404(Model, pk=id) data = Model(request.POST or None, instance = instance) This is not working in this case because I need to provide the instance_id on the parent function, but the id parameter is provided on the function that supports the form. (child function) I suppose there is 2 options/questions: Can I access the form_id from the parent function? Should I deal with this in the form function? and in this case how do I keep the existing text when updating form? model class UserProfile(models.Model): user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) class Model(models.Model): user = models.ManyToManyField(User, blank=True) text = models.TextField('text', blank=True) template … -
Failed to change read-only flag pycharm in ubuntu
When I try to write something in file it show error "Failed to change read-only flag from pycharm in ubuntu" -
Google one tap Login With Django ( The given origin is not allowed for the given client ID issue )
I'm trying to connect Google One Tap Login with Django framework, but I'm having issue. I'm not sure why this is displaying an issue. I followed all of the guidelines described in the Google documentation. issue - The given origin is not allowed for the given client ID Here is my Google API client configuration for the javascript origin url. Here is the login html template code. <!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> </head> <body> <h1>Hi Reddit</h1> <script src="https://accounts.google.com/gsi/client" async defer></script> <div id="g_id_onload" data-client_id="i don't want to shere" data-context="signin" data-ux_mode="popup" data-login_uri="http://localhost:8000/google/login/" data-auto_select="true" data-itp_support="true"> </div> <div class="g_id_signin" data-type="standard" data-shape="pill" data-theme="outline" data-text="continue_with" data-size="large" data-logo_alignment="left"> </div> </body> </html> </body> </html> I'm not sure why this is displaying an issue. Is it possible to load Google One Tap Javascript in Django? What should I do to load Google One Tap Javascript in Django? -
Django if statement is not working inside a html tag
(https://i.stack.imgur.com/tGf0u.jpg) I am trying to execute if statement in html file inside Js block in which I am writing JavaScript code. When I am trying to insert if statement is showing Expression Expected but if statement is written outside tag it is working. I tried to write it outside tag it is working but inside tag it is not working.