Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to access the model class object in form_valid in django's create view?
the below code is for my model: class Book(models.Model): name = models.CharField(max_length=50) picture = models.ImageField() author = models.CharField(max_length=30, default="Anonymous") email = models.EmailField(blank=True) describe = models.TextField(default="Good Book") user = models.ForeignKey(User, on_delete=models.CASCADE,null=True) def __str__(self): return self.name the below is my form: class BookCreate(ModelForm): class Meta: model = Book exclude = ('user',) the below is my Create View here's the problem: i want to access the modal object , that's why i did the self.modal object but it seems to be giving none . Isn't that's how you access it ? How can i access it? class Upload(CreateView): model = Book form_class = BookCreate template_name = "libraryapp/upload_form.html" success_url = reverse_lazy('libraryapp:index') def form_valid(self, form): print("The model object =",self.object) return super().form_valid(form) -
djongo, cannot connet to server on mongodb.com
i think below setting will work for the djongo to connect to the remote mongodb on mongodb.com but, the error message shows its still trying to connect to the localhost DATABASES = { 'default': { 'ENGINE': 'djongo', 'HOST': 'mongodb+srv://<username>:<password>@cluster-name/<dbname>?retryWrites=true&w=majority', } below is the error traceback Traceback (most recent call last): File "/usr/lib/python3.6/threading.py", line 916, in _bootstrap_inner self.run() File "/usr/lib/python3.6/threading.py", line 864, in run self._target(*self._args, **self._kwargs) File "venv/lib/python3.6/site-packages/django/utils/autoreload.py", line 54, in wrapper fn(*args, **kwargs) File "venv/lib/python3.6/site-packages/django/core/management/commands/runserver.py", line 120, in inner_run self.check_migrations() File "venv/lib/python3.6/site-packages/django/core/management/base.py", line 453, in check_migrations executor = MigrationExecutor(connections[DEFAULT_DB_ALIAS]) File "venv/lib/python3.6/site-packages/django/db/migrations/executor.py", line 18, in __init__ self.loader = MigrationLoader(self.connection) File "venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 49, in __init__ self.build_graph() File "venv/lib/python3.6/site-packages/django/db/migrations/loader.py", line 212, in build_graph self.applied_migrations = recorder.applied_migrations() File "venv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 73, in applied_migrations if self.has_table(): File "venv/lib/python3.6/site-packages/django/db/migrations/recorder.py", line 56, in has_table return self.Migration._meta.db_table in self.connection.introspection.table_names(self.connection.cursor()) File "venv/lib/python3.6/site-packages/django/db/backends/base/introspection.py", line 48, in table_names return get_names(cursor) File "venv/lib/python3.6/site-packages/django/db/backends/base/introspection.py", line 43, in get_names return sorted(ti.name for ti in self.get_table_list(cursor) File "venv/lib/python3.6/site-packages/djongo/introspection.py", line 47, in get_table_list for c in cursor.db_conn.list_collection_names() File "venv/lib/python3.6/site-packages/pymongo/database.py", line 856, in list_collection_names for result in self.list_collections(session=session, **kwargs)] File "venv/lib/python3.6/site-packages/pymongo/database.py", line 819, in list_collections _cmd, read_pref, session) File "venv/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1454, in _retryable_read read_pref, session, address=address) File "venv/lib/python3.6/site-packages/pymongo/mongo_client.py", line 1253, in _select_server server = topology.select_server(server_selector) … -
django-heroku and psycopg2 installed but shows "import django_heroku ModuleNotFoundError: No module named 'django_heroku'"
Firstly i installed psycopg2 then django_heroku. setting.py import django_heroku import os --- --- django_heroku.settings(locals()) Here are my requirements which are installed in virtual environments. requirements.txt asgiref==3.2.7 certifi==2020.4.5.1 chardet==3.0.4 dj-database-url==0.5.0 Django==3.0.5 django-contrib-comments==1.9.2 django-heroku==0.3.1 gunicorn==20.0.4 idna==2.9 psycopg2==2.7.5 pytz==2020.1 requests==2.23.0 six==1.15.0 sqlparse==0.3.1 urllib3==1.25.9 whitenoise==5.1.0 After pushing in heroku master it shows. Activity Log File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "/tmp/build_e4e9cada1e303d2ab0fdd618bffc8af4/covid19/covid19/settings.py", line 13, in <module> import django_heroku ModuleNotFoundError: No module named 'django_heroku' ! Error while running '$ python covid19/manage.py collectstatic --noinput'. See traceback above for details. You may need to update application code to resolve this error. Or, you can disable collectstatic for this application: $ heroku config:set DISABLE_COLLECTSTATIC=1 https://devcenter.heroku.com/articles/django-assets ! Push rejected, failed to compile Python app. ! Push failed Other Problem arrives here that, "ModuleNotFoundError: No module named 'covid19.wsgi'". But I used it in my Procfile. Procfile web: gunicorn covid19.wsgi -
Why is button not toggling
i am working on a website where users can send friend request, accept request and cancel request. I have a problem on button toggling, when a user send me a friend request the botton on my side displays 'follow back', when i click on the 'follow back' button the button supposed to change to 'following', but it does not. I will attached an image to make my question a bit more specific. Note: Both images are from different template and views, the first image is where the problem is at. As you can see in my first image, the button still remain on FOLLOW BACK when it is clicked, when clicked the button should change to FOLLOWING but it not. What am i missing in my code? Model: class FriendRequest(models.Model): to_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='to_user') from_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='from_user') date = models.DateTimeField(auto_now_add=True, null= True) class Meta: verbose_name = 'Friend request' verbose_name_plural = 'Friend requests' ordering = ['-date'] def __str__(self): return "from {}, to {}".format(self.from_user.username, self.to_user.username) Views.py: @login_required def following_view(request, username): p = FriendRequest.objects.filter(from_user__username=username).exclude( Q(from_user__profile__friends__blocked_by__user__username=username)| Q(from_user__profile__blocked_users__user=request.user)| Q(to_user__profile__blocked_users__user=request.user)) all_profile_users = [] button_status_list = [] for user_obj in p: u = user_obj.to_user all_profile_users.append(u) friends = Profile.objects.filter(user=request.user, friends__id=user_obj.id).exists() button_status = 'none' if not friends: button_status … -
Django upload file mechanism
I'm trying to upload files use a different FileStorage system other than the default provided by Django. But i need to understand which protocol does django follow while uploading files using FileField. From request to saving files to the file system. -
Using Django Rest Framework how to generate PDF files from Html Template
I have a template HTML file, that I will populate with data from a model. I need an endpoint to : Create those pdf, I'll be looping on each model and apply the generate pdf function. download single pdf ( detail view ) download bulk ( all pdf ) views.py class GeneratePdf(View): def get(self, request, *args, **kwargs): data = { 'today': datetime.date.today(), } pdf = render_to_pdf('pdf/report.html', data) return HttpResponse(pdf, content_type='application/pdf') urls.py router.register('pdf', GeneratePdf.as_view, basename='pdf' error : AttributeError: 'function' object has no attribute 'get_extra_actions' Question : Why do I get this error? is this the right way to do it? Thanks ! -
javascript pop up form with django inlineformset
i want to submit child form with javascript pop up ,if number_of_cars = 3 it will pop up a form with 3 input fields for Car car_name , i have dont it from front end , but i dont know to add them to the pop up form class Car(models.Model): car_name = models.CharField(max_length=20,unique=True) owner = models.ForeignKey(Creator,on_delete=models.CASCADE) class Creator(models.Model): owner = models.CharField(max_length=15,unique=True) number_of_cars = models.IntegerField(default=1) forms.py class CarForm(ModelForm): class Meta: model = Car fields = ['car_name'] class Creator(ModelForm): class Meta: model = Creator fields = '__all__' InlineformsetCarNames = inlineformset_factory = (Creator,Car,form=CarForm,extra=1) and this is my views.py inside CreatView def get_context_data(self,*args,**kwargs): context = super(CreateCarView,self).get_context_data(*args,**kwargs) if self.request.POST: context['car_name'] = InlineformsetCarNames(self.request.POST) else: context['car_name'] = InlineformsetCarNames() return context def form_valid(self,form): context = self.get_context_data() context = context['car_name'] with transaction.atomic(): self.object = form.save() if context.is_valid(): context.instance = self.object context.save() return super(CreateCarView,self).form_valid(form) and this my template <form method="POST">{% csrf_token %} <div class=" col-12 "> <div class="col-12 col-sm-9 col-md-12 divColor mt-2 mx-auto row " > <div class=" col-12 col-sm-9 mx-auto row p-0"> <div class="col-12 col-md-6 p-0 mx-auto text-center"> <br> {{form.owner | add_class:'form-control col-12 col-sm-10 mx-auto'}} {{form.number_of_cars | add_class:'form-control col-12 col-sm-10 mx-auto' | attr:'id:qua'}} <input type="button" class="btn btn-light col-12 col-sm-10 mx-auto" name="" id="CARBTN" value="CAR" data-target="#CAR" data-toggle="modal"> </div> </div> <button class="col-4 … -
Django detail view test model gives AssertionError: 404 != 200 in django test, but works fine in the browser
I am new to Django and test-driven approach, I am trying below shown test.py file but it gives Assertion Error. But code runs fine on web browser chrome. My backend is PostgreSQL. Whats is the problem with my code. Test.Py from django.contrib.auth import get_user_model from django.test import TestCase from django.urls import reverse from .models import Post from django.test import Client class BlogTests(TestCase): def setUp(self): self.client = Client() self.user = get_user_model().objects.create_user( username='testuser', email='test@email.com', password='secret' ) self.post = Post.objects.create( title='A good title', body='Nice body content', author=self.user, ) def test_post_detail_view(self): response = self.client.get('/post/1/') no_response = self.client.get('/post/100000/') self.assertEqual(response.status_code, 200) self.assertEqual(no_response.status_code, 404) self.assertContains(response, 'A good title') self.assertTemplateUsed(response, 'post_detail.html') I am receiving this error on shell : AssertionError: Creating test database for alias 'default'... System check identified no issues (0 silenced). .F.. ====================================================================== FAIL: test_post_detail_view (blog.tests.BlogTests) ---------------------------------------------------------------------- Traceback (most recent call last): File "D:\\tests.py", line 50, in test_post_detail_view self.assertEqual(response.status_code, 200) AssertionError: 404 != 200 ---------------------------------------------------------------------- Ran 4 tests in 0.894s FAILED (failures=1) Destroying test database for alias 'default'... Below shown is my views.py file : views.py from django.views.generic import ListView, DetailView from .models import Post class BlogListView(ListView): model = Post template_name = 'home.html' class BlogDetailView(DetailView): model = Post template_name = 'post_detail.html' And this si the urls.py … -
What are the default namespaces for django authentication URLs?
I changed my app's urls.py to have a namespace app_name = 'somename'. And then did these, Changed reverse('url-name') to reverse('somename:url-name'). Changed {% url 'url-name' %} to {% url 'somename:url-name' %}. Changed a {% if request.resolver_match.url_name == "url-name" %} to {% if request.resolver_match.url_name == "somename:url-name" %}. For accounts app, I only have two custom views for login and signup. So a reverse like reverse('accounts:login') is working but reverse('accounts:password_reset') (part of default django auth) is not working. Here is what I tried, Replaced reverse('accounts:password_reset') with reverse('auth:password_reset'). Replaced reverse('accounts:password_reset') with reverse('password_reset'). Solution 1 did not work. Solution 2 is working. I also tried changing path('accounts/', include('django.contrib.auth.urls')) in my project's urls.py to path('accounts/', include('django.contrib.auth.urls', namespace='auth')) and path('accounts/', include('django.contrib.auth.urls, namespace='accounts')). Neither worked. project/urls.py urlpatterns = [ path('', include('core.urls')), path('admin/', admin.site.urls), path('accounts/', include('accounts.urls')), path('accounts/', include('django.contrib.auth.urls')), path('books/', include('library.urls')) ] accounts/urls.py app_name = 'accounts' urlpatterns = [ path('signup/', views.CustomSignup.as_view(), name='signup'), path('login/', views.CustomLogin.as_view(), name='login'), ] Why namespacing password_reset with accounts and auth fail? Is there a documentation page that has default namespaces that can be used? -
Uploading Images from Ckeditor to Google Drive
I am using Django Google Drive Storage from this repo to store and serve my media files in Django. I am using this because i want to deploy it on Heroku but don't have a credit card for Amazon S3 account. I did the setup exactly as they said in the documentation. The images I upload through ImageField models are working fine but those I send through Django-Ckeditor are not getting sent. I am using a Ckeditor RichTextUploadingField to store the images in a uploads folder. This is my settings.py file with the necessary configuration This is the traceback of the error produced [04/Jun/2020 15:28:10] "POST /ckeditor/upload/ HTTP/1.1" 200 156 Internal Server Error: /media/uploads/2020/06/04/opera-snapshot_2020-06-04_151851_127001.png Traceback (most recent call last): File "C:\Users\Lenovo\.conda\envs\tensor\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\Lenovo\.conda\envs\tensor\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\Lenovo\.conda\envs\tensor\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\Lenovo\.conda\envs\tensor\lib\site-packages\django\views\static.py", line 37, in serve if fullpath.is_dir(): File "C:\Users\Lenovo\.conda\envs\tensor\lib\pathlib.py", line 1348, in is_dir return S_ISDIR(self.stat().st_mode) File "C:\Users\Lenovo\.conda\envs\tensor\lib\pathlib.py", line 1158, in stat return self._accessor.stat(self) File "C:\Users\Lenovo\.conda\envs\tensor\lib\pathlib.py", line 387, in wrapped return strfunc(str(pathobj), *args) OSError: [WinError 123] The filename, directory name, or volume label syntax is incorrect: 'C:\\Users\\Lenovo\\PycharmProjects\\LeafyAI(GDrive)\\https:\\drive.google.com\\drive\\folders\\1spvHiP6Im3xiMvrGGoVqO2o8IRC8caed\\uploads\\2020\\06\\04\\opera-snapshot_2020-06-04_151851_127001.png' [04/Jun/2020 15:28:10] "GET /media/uploads/2020/06/04/opera-snapshot_2020-06-04_151851_127001.png … -
How do I tell python to use a variable with the name of the value of another variable?
In my code I define multiple variables with names that are equal to the value I get when calling field.name, so I though that I could pass them in with this for loop: if formReminders.is_valid(): needsImprovement = formReminders.cleaned_data["needsImprovement"] hasFallacies = formReminders.cleaned_data["hasFallacies"] hasEmotionalDeficiency = formReminders.cleaned_data["hasEmotionalDeficiency"] isNecessaryToObtain = formReminders.cleaned_data["isNecessaryToObtain"] doesAReallyCauseB = formReminders.cleaned_data["doesAReallyCauseB"] areAllStepsPresent = formReminders.cleaned_data["areAllStepsPresent"] isCauseSufficient = formReminders.cleaned_data["isCauseSufficient"] areAllClausesIdentified = formReminders.cleaned_data["areAllClausesIdentified"] isCausalityCertain = formReminders.cleaned_data["isCausalityCertain"] languageIsEnglish = formReminders.cleaned_data["languageIsEnglish"] isTautologyPresent = formReminders.cleaned_data["isTautologyPresent"] for field in ImprovementAbstraction._meta.fields: need.field.name = field.name so if field.name is equal to "needsImprovement" I want to use the variable needsImprovement, how can I achieve this in python? -
Dynamic django serializer
im learning to use DRF and i realize there's alot of code that is being repeated within the serializer , and im wondering if im doing the right thing. Here's an example. I have 2 main models : The 2 main models class SalesProject(models.Model): sales_project_name = models.CharField(max_length=100) customer_information = models.ManyToManyField('CustomerInformation') sales_department = models.ForeignKey('SalesDepartment', on_delete=models.CASCADE) #bunch of isolated fields not stated here class Ticket(models.Model): title = models.CharField(max_length=255) customerInformation = models.ForeignKey('CustomerInformation', null=True , blank = True, on_delete = models.CASCADE) salesProject = models.ForeignKey('SalesProject', null=True , blank = True, on_delete = models.CASCADE) #bunch of isolated fields not stated here These models have varying depth which i wish to access in different scenarios. For example , When wanting to access the detail page for Ticket i would wish to exclude certain infomation i would otherwise get from using a general serializer that i defined for SalesProject and CustomerInfomation. This would then lead me to my issue , which is to rewrite a specialized foreign key serializer for SalesProject , of which all i am doing is just excluding the fields from the main general serializer for SalesProject. As illustrated here : class SalesProjectDetailSerializer(serializers.ModelSerializer): #general serializer which contains all fields and has depth of 2. This … -
DRF Serializer Prevent Instance Update if Foreign Keys aren't Updated Properly
I have a model serializer for a model with some foreign keys. My understanding is that to add objects to the foreign fields, you first save your instance and then add the fields. However, if I happen to have an error in the data I am adding to the foreign keys, this will save the updated instance but not the foreign key data (obviously, as it has an error). But if the foreign key doesn't save, I don't want the updated instance to save either. Do I have to verify the proper data before calling serializer.save()? Example: In the code below, I have a MatchModel that contains foreign keys of MatchResultVote and MatchTeams. If a match is started, I send a put request with updated data that changes isAvailable to false, isStarted to true and adds a MatchTeam The code below works fine, but if I end up accidentally passing bad data for the MatchTeam I want to add, it will still update the instance (i.e. changing isAvailable to false and isStarted to true) even though I don't want this to happen unless the MatchTeam data is also valid I'm thinking I am probably supposed to validate the MatchTeam data … -
Write XML Python - Special characters error in list of string
I have a list of string which I want to write in a XML file. My code looks like this : from jinja2 import Environment, PackageLoader, select_autoescape import os env = Environment(loader = PackageLoader(path), autoescape = select_autoescape(['html', 'xml'])) list_data = ['<managedObject class="test" operation="test"/>', '<managedObject class="test" operation="test"/>'] template = env.get_template('template.xml') output_from_parsed_template = template.render(scripts=list_data) path = os.path.join("output_file.xml") with open(str(path), "wb") as fh: fh.write(output_from_parsed_template.encode('utf-8')) My template.xml looks like this : <?xml version="1.0" encoding="UTF-8"?> {% for script in scripts %} {{ script }} {% endfor %} And I get the following error in the output_file.xml : <?xml version="1.0" encoding="UTF-8"?> &lt;managedObject class=&#34;test&#34; operation=&#34;test&#34;/&gt; &lt;managedObject class=&#34;test&#34; operation=&#34;test&#34;/&gt; Do you know how to write all special characters (double quotes and inf/supp sign) in the XML ? I'm using the same function to write a txt file and I don't have this problem. Thanks for your help -
QUERYSET: How can I filter by field in a list (case insensitive)
I want to filter field using __in but i also want it to be case insensitive when i pass it to the query This is something Ive tried: fields = ['Banana','Water Melon','grapes'] MyModel.objects.filter(field__icontains__in=fields).values() and returned an error (of course). I want it to be something like that. Any help/enlightenment would be appreciated, Thank you in advance for the help -
How can I solve the "Cookie csrftoken will be soon rejected because it has the sameSite attribute set to none" warning on my Django 2.0 application?
I am using version 2.0 and I just noticed on my firefox developer tools this message: Cookie “csrftoken” will be soon rejected because it has the “sameSite” attribute set to “none” or an invalid value. It seems that django 2.0 does not store SameSite attribute along with this cookie. (for example something like this: Set-Cookie: CookieName=CookieValue; SameSite=Lax;) Is there a workaround for this? Or am I doing something wrong? -
Jquery UI autocomplete with pictures in Django
I have ab autocomplete enabled in my Django project. It works fine. But I would like to add pictures to the suggestions. I tried the official docs but information is parsed: https://jqueryui.com/autocomplete/#custom-data My JS: $(function() { $(".prod").autocomplete({ source: "/finder/search_auto", maxShowItems: 5, open: function() { $('.ui-menu') .width(250); } , select: function (event, ui) { AutoCompleteSelectHandler(event, ui) }, minLength: 2, }); }); function AutoCompleteSelectHandler(event, ui) { var selectedObj = ui.item; } My view: def search_auto(request): if request.is_ajax(): q = request.GET.get('term', '') products = Product.objects.filter(real_name__icontains=q) results = [] for pr in products: product_json = {} product_json = pr.real_name results.append(product_json) data = json.dumps(results) else: data = 'fail' mimetype = 'application/json' return HttpResponse(data, mimetype) I can't figure out how to pass my product picture url into my dataan how to display it. -
DOCKER does not run manage.py
somebody can explain why docker does not wanna run Django server Thats my structure of project: app bankproject env docker-compose.yml Dockerfile manage.py requirements.txt There is my file Docker: # pull official base image FROM python:3.8.0-alpine # set work directory WORKDIR .app/ # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install dependencies RUN pip install --upgrade pip COPY ./requirements.txt requirements.txt RUN pip install -r requirements.txt # copy project COPY . /app CMD["python", "manage.py", "runserver", "0.0.0.0:8000"] and my docker-compose.yml version: '3.7' services: web: build: ./ command: python manage.py runserver 0.0.0.0:8000 volumes: - ./app/:/app ports: - 8000:8000 env_file: - ./.env.dev Actually in folder env I have file .env.dev and it is consist : DEBUG=1 SECRET_KEY=foo DJANGO_ALLOWED_HOSTS=localhost 127.0.0.1 [::1] The mistake I got : web_1 | python: can't open file 'manage.py': [Errno 2] No such file or directory app_web_1 exited with code 2 -
How to change the storage default location in Scorm xblock
I am using hawthorn version open edX, Also using scorm xblock https://github.com/overhangio/openedx-scorm-xblock for upload the scorm. by default, it is using /edx/var/edxapp/media/scorm/ path. I want to change the storage location. For this, I have tried two solutions. First solution:- In the lms.env.json and cms.env.json change the path. MEDIA_ROOT = /my/new/path/media/ MEDIA_URL = /media/ Also, added below the line in url.py urlpatterns = patterns('',# ... the rest of your URLconf goes here ...) + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) It is uploaded successfully in this path /my/new/path/media/, but when I try to get in the LMS, it is showing a 404 error. Second solution:- As par scorm xblock, We can change to default location by give the path in below code. XBLOCK_SETTINGS["ScormXBlock"] = { "LOCATION": "/my/new/path/media/",} I have added the code in comman.py and scormxblock.py, But it is not working. Or, Please correct me if I am adding the code in the wrong place. -
Django: TemplateDoesNotExist at /
I am using Django 3.0.7 and have a project named starling and an app named piggybank. I placed my index.html inside templates/starling inside the piggybank directory The following urls.py is inside piggybank: from django.urls import path from django.contrib.auth import views as auth_views from . import views urlpatterns = [ path("", views.index, name="index"), ] The urls.py in starling (project) is: """starling URL Configuration The `urlpatterns` list routes URLs to views. For more information please see: https://docs.djangoproject.com/en/3.0/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, include urlpatterns = [ path("", include("piggybank.urls")), path('admin/', admin.site.urls), ] My full settings.py: """ Django settings for starling project. Generated by 'django-admin startproject' using Django 3.0.7. For more information on this file, see https://docs.djangoproject.com/en/3.0/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/3.0/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, … -
Hosting multiple sub domains on the same windows 10 server running django application
I need to host multiple sites with subdomains all pointing to the same windows10 server. virtual hosts for different sub-domains points to different WSGI files. Venv activation is added in wsgi file. The issue happening is first Django settings file which is invoked is applied to all sub-domains. eg. company1.example.com -> /company1_wsgi.py -> company1_settings.py company2.example.com -> /company2_wsgi.py -> company2_settings.py Now, company1_settings is applied for both company1.example.com and company2.example.com. I see right WSGI files are called based on the sub-domain but for some reason os.environ['DJANGO_SETTINGS_MODULE'] is not being updated dynamically based on the subdomains and always uses the first value wsgi file python_home= 'E:/app/demo/env' activate_this = 'E:/app/demo/env/Scripts/activate_this.py' exec(open(activate_this).read(),dict(__file__=activate_this)) import os import sys from django.core.wsgi import get_wsgi_application import site # Add the site-packages of the chosen virtualenv to work with site.addsitedir('E:/app/demo/env/Lib/site-packages') # Add the app's directory to the PYTHONPATH sys.path.append('E:/app/demo/crm') sys.path.append('E:/app/demo/crm/appointment_scheduler') os.environ['DJANGO_SETTINGS_MODULE'] = 'appointment_scheduler.settings.preprod' application = get_wsgi_application() <VirtualHost *:443> ServerName demo.crmbaylyn.com WSGIScriptAlias / "E:/app/demo/crm/appointment_scheduler/wsgi_win.py" WSGIPassAuthorization On WSGIScriptReloading On <Directory "E:/app/demo/crm/appointment_scheduler"> <Files wsgi.py> Order deny,allow Allow from all Require all granted </Files> Order allow,deny Allow from all Require all granted </Directory> Alias /static "E:/app/demo/crm/static" <Directory "E:/app/demo/crm/static"> Require all granted </Directory> SSLEngine on SSLCertificateFile "C:/Apache24/conf/crmbaylyn.cert" SSLCertificateKeyFile "C:/Apache24/conf/crmbaylyn.key" </VirtualHost> <VirtualHost *:80> RewriteEngine On RewriteCond %{HTTP:X-Forwarded-Proto} … -
AttributeError no attribute 'delete'
i am working on a website where users can send friend request, accept request, cancel request. I have an error AttributeError object has no attribute 'delete'. This happens when i cancel friend request. This my code i tried: Model: class FriendRequest(models.Model): to_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='to_user') from_user = models.ForeignKey(settings.AUTH_USER_MODEL,on_delete=models.CASCADE, related_name='from_user') date = models.DateTimeField(auto_now_add=True, null= True) class Meta: verbose_name = 'Friend request' verbose_name_plural = 'Friend requests' ordering = ['-date'] def __str__(self): return "from {}, to {}".format(self.from_user.username, self.to_user.username) Views.py: @login_required def cancel_friend_request_view(request, id): user = get_object_or_404(User, id=id) frequest = FriendRequest.objects.filter(from_user=request.user, to_user=user).first() frequest.delete() print(frequest) return HttpResponseRedirect(request.META.get('HTTP_REFERER')) -
Django ORM extract weekday as string from queryset
What I'm trying to do is annotate a queryset with the weekday strings ("monday", "tuesday" etc). I understand how to get the int values: queryset = queryset.annotate( weekday_int=ExtractWeekDay("date"), ) But I'm having trouble getting the string values themselves. I've tried using an ExpressionWrapper, but F objects don't seem to play well with Date objects. I'm using postgres as my underlying database but can't find a related lookup_name for the generic Extract. -
How to show total number of selected object on template after selecting object on field which have OneToMany relations with other table
I am new in web app development, so not being able to do so. Please help me. My models.py contains: class Entexaminfo(models.Model): entexamses = ( ("June Session", "June Session"), ("December Session", "December Session"), ) approve_choice = ( ("Pending", "Pending"), ("Accepted", "Accepted"), ("Rejected", "Rejected"), ) ename = models.CharField(max_length=16, choices=entexamses) enrollno = models.OneToOneField(Student, on_delete=models.CASCADE) #programs = models.ManyToManyField(Programs, related_name='proNames', default=0) program = models.ManyToManyField(Programs, default=0) center = models.ForeignKey(Excenter, on_delete=models.CASCADE) remarks = models.CharField(validators=[max_len_check], max_length=256, default="-") #status = models.BooleanField() status = models.CharField(max_length=8, choices=approve_choice, default="Pending") created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) objects = models.Manager # for admin pannel to display for correction def __str__(self): return self.ename def get_absolute_url(self): return reverse('show', kwargs={'pk': self.pk}) EntexaminfoForm class contains: class EntexaminfoForm(forms.ModelForm): class Meta: model = Entexaminfo fields = ['enrollno', 'ename', 'program', 'center'] widgets = { 'program': forms.CheckboxSelectMultiple(attrs={'class': 'list-unstyled list-unline'}), } help_texts = { 'ename': '[Select Exam Session]', 'enrollno': '[Select Your Enroll Number]', 'program': '[Put Tick Mark on Program you want to join. {More than one program can be choosen.}]', 'center': '[Select Center]', } error_messages = {} labels={ 'ename': 'Exam Name:', 'enrollno': 'Enroll No.', 'program': 'Program:', 'center': 'Center:', 'remarks': 'Remarks:' } My views.py where I have created FormView, View, CreateView, I have not created manual form. I want to show total number … -
the data from view function is not passed to the html file in django
The data from the view function was not passed to the HTML file in Django. I am new to Django. To add a new page: I created an HTML page. I added a function to process in data in the view function I have added a URL to urls.py Let me know if I am missing something. Please find my code below View.py def approval_user(request): msg = "Pending User Request" print(msg) approval = [] if request.method == "POST": users = User.objects.all() for user in users: if user.groups.exists(): approval.append(user) return render(request, "approval.html", {"approval":approval,"msg" : msg}) aproval.html {% extends 'layouts/base.html' %} {% block title %} Approval {% endblock title %} {% block stylesheets %}{% endblock stylesheets %} {% block content %} <!-- (Almost) A blank page --> <div class="row gap-20 masonry pos-r"> <div class="masonry-sizer col-md-6"></div> <div class="masonry-item w-100"> <div class="row gap-20"> <!-- Pending Approvals ==================== --> <div class="col-md-12"> <div class="layers bd bgc-white p-20"> <div class="layer w-100 mB-10"> {% if msg %} <h5 class="lh-1">{{ msg }}</h5> {% endif %} </div> {% for user in approval %} <div class="layer w-100"> <div class="peers ai-sb fxw-nw"> <div class="peer peer-greed"> <h6 class="lh-1">{{ user.name }}</h6> </div> <div class="peer peer-greed"> <h6 class="lh-1">{{ user.mailid }}</h6> </div> <div class="peer"> <button class="d-ib …