Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Run Django Website with different mod_wsgi than default
I have an Apache2 server hosting multiple Django websites. All except one use Django 3.8, using a mod_wsgi compiled on Python 3.7. The outlier (let's call it SiteX) uses Django 4.0, which requires Python 3.8+. I want SiteX to use a virtual environment with these newer versions of Python and Django, while the other sites keep using their default versions. For SiteX, I've created a virtual environment venv in its directory. But from what I understand, the current mod_wsgi installed is not compatible with its version of Python, so specifying WSGIPythonHome in the conf file won't do anything. the current mod_wsgi (4.7/python 3.7) is loaded in /etc/apache2/mods-available/wsgi.load with the line LoadModule wsgi_module /usr/lib/apache2/modules/mod_wsgi.so I've tried creating a new mod_wsgi, this time using the Python module mod_wsgi, which I've installed in venv. In the .conf file for a group of Django sites (that include SiteX) I tried specifying this unique version of the mod_wsgi above the <VirtualHost> block with the line: LoadModule wsgi_module "/var/www/html/app/SiteX/venv/lib/python3.9/site-packages/mod_wsgi/server/mod_wsgi-py39.cpython-39-x86_64-linux-gnu.so" but running $ apachectl configtest says: module wsgi_module is already loaded, skipping. I found a solution for multiple mod_wsgi's using WSGIDaemonProcess but the solution's .conf looks slightly different that mine. Below is a snippet of the relevant … -
Django filter by category
i want to see specific category wise post, i created category app and blog app.i want show top 5 or 10 post in home.html.that's why i need 4 specific category. but i can't filter(category) from post model.i cant access category because i created it another app.. i want to filter by category. model.py for category class Category(models.Model): parent = models.ForeignKey('self', related_name='children', on_delete=models.CASCADE, blank = True, null=True) category_name = models.CharField(max_length=50,unique=True) slug = models.SlugField(allow_unicode=True,max_length=100,unique=True) description =models.TextField(max_length=300,blank=True) cat_image = models.ImageField(upload_to = 'photo/categories',blank = True) created_at = models.DateTimeField(auto_now_add=True) model.py for blog class Post(models.Model): title = models.CharField(max_length=200, unique=True) slug = models.SlugField(allow_unicode=True, unique=True, max_length=250, null=True, blank=True) subtitle = models.CharField(max_length=255, blank=True) heder_image = models.ImageField(null=False,blank=True,upload_to="images/") heder_image_url = models.CharField(null=True,blank=True,max_length=200) heder_image_Under_line = models.TextField(null=True,default="image") # author = models.ForeignKey(Profile, on_delete=models.PROTECT) author = models.ForeignKey(User, on_delete=models.CASCADE) updated_on = models.DateTimeField(auto_now= True) created_on = models.DateTimeField(auto_now_add=True) body = RichTextField(max_length=100000) status = models.IntegerField(choices=STATUS, default=0) meta_description = models.TextField(max_length=300, blank=True,default='') category = models.ForeignKey(Category,on_delete= models.CASCADE) views.py def home(request): category = Category.objects.all().filter(parent=None) post_by_category = Post.objects.filter(published=True).order_by('-created_on')#filter by category name slider = Post.objects.filter(slider=True).order_by('-created_on') context = { 'category':category, 'post_by_category':post_by_category, 'slider':slider, 'counter':Counter, } return render(request,'home.html',context) -
How to save JavaScript sessionStorage to django
I have an Sdk to call which returns an applicationID that I need to store in my django application so that if the user is approved can then move to the next page. I trying to save in JS sessionStorage than pass the data to another html page where I'm using ajax to pass it to my django views, the problem is that I need to have this data unique for the user that is logged in. How can I link this data to the current user logged in and so on? const widget = window.getidWebSdk.init({ apiUrl: '', sdkKey: '', containerId: "targetContainer", flowName: '', onComplete: (data) => { console.log(JSON.stringify(data)) let appId = data; console.log(data) sessionStorage.setItem("appId", JSON.stringify(appId)) window.location.href = "/kycsubmit"; return; }, onFail: ({ code, message}) => { console.log("something went wrong: " + message )}, }); second html page let application = JSON.parse(sessionStorage.getItem("appId")); let kycStatus = application.applicationId $.ajax({ type: "GET", dataType: "json", url: `api/application/${kycStatus}`, headers: { 'Content-Type': 'application/json', 'X-API-Key': '', }, success: function(data) { document.getElementById("test").innerHTML = data.overallResult.status document.getElementById("test-1").innerHTML = application.applicationId console.log(data.overallResult.status) } }) -
Accessing items in a list through template tags in Django template tags
Template tag screenshot and possible solution options First time, posting to stack-overflow. Please excuse if formatting is not ideal. html <tbody> {% for list in todolist %} <tr> <td> <a href="{% url 'todo_detail' list.pk %}">{{ list.name }}</a> </td> <td> {{ list.items.all|length }} </td> <td> {% comment %}need this to be allCompleted[list.id - 1] #allCompleted.0 works. allCompleted[0] or allCompleted['0'] does not.{% endcomment %} {% if allCompleted == True %} {{ allCompleted|getindex:list.id }} Yes {% else %} No {% endif %} </td> </tr> {% endfor %} </tbody> Views.py: class TodoListListView(ListView): model = TodoList context_object_name = "todolist" template_name = "todos/list.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) allCompletedList = [] for list in TodoList.objects.all(): allCompleted = True for item in list.items.all(): if item.is_completed == False: allCompleted = False allCompletedList.append(allCompleted) context['allCompleted'] = allCompletedList print ('context: ', context) return context Models.py class TodoList(models.Model): name = models.CharField(max_length=100, blank=False) created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name class TodoItem(models.Model): task = models.CharField(max_length=100) due_date = models.DateTimeField(null=True, blank=True) is_completed = models.BooleanField(default=False) list = models.ForeignKey("Todolist", related_name="items", on_delete=models.CASCADE) def __str__(self): return self.task When printing context: I get 'allCompleted': [False, True] This is accurate as I have some items in housing chores not completed but I triple checked to make sure all my coding … -
Django ORM group list of values by date
I'm attempting to perform a group by on a date field, and return values matching that date in a single query. There seem to be many related questions here but they all are aggregating based upon a Count. Given I have a model like this: class Book(models.Model): name = models.CharField(max_length=300) pubdate = models.DateField() I would like to run an ORM query which returns distinct name values for pubdate. How can I get a result which looks like { '2022-05-04': ['John', 'Sara', 'Bill'], '2022-05-06': ['Sara', 'Kevin', 'Sally'] ... } -
use functions from another file inside of a class
I have a file, called tst_pro_ac.py. It contains many classes, with many methods inside of these classes. The classes are part of test cases used by Django, to do unit tests. Exemple of a class inside tst_pro_ac.py class LoginRequiredActiveCheck(TestCase): """Login Required for project_active Page""" def test_status_code_200(self): """project_active Response status 200""" self.assertEqual(self.response.status_code, 200) Some of these methods are used many times, hence redundant. The idea is to put these methods in a separate file like comm_function.py and call them when needed. I've created the file comm_function.py and put the often used functions inside def test_status_code_200(self): """project_active Response status 200""" self.assertEqual(self.response.status_code, 200) Yet, when I call them in my new file like this from comm_function import test_status_code_200 class LoginRequiredActiveCheck(TestCase): """Login Required for project_active Page""" test_status_code_200() Yet, when I run the test through a python manage.py test stuff.tests.some_tests.tests_pro_active I have the following error raise AttributeError(item) AttributeError: assertEqual Not sure if my understanding of the class is correct and if something doable in Django. PS: If the question is not appropriate, let me know, I will delete it. -
How to pass config setting in Django and keep module decoupled?
In a Python Django project, I have a module with a class (let's say SomeDataStore) that abstracts file storage behaviour and requires a config setting with the correct path (different for development, prod, ...) Currently, I've done it like this: # settings.py RELEVANT_PATH = os.environ.get("DJANGO_RELEVANT_PATH", "/some/default") ... # datastore.py from django.conf import settings class SomeDataStore: def list_files(self): p = Path(settings.RELEVANT_PATH) files = p.glob("*.csv") return files ... # views.py from datastatus import SomeDataStore def show_files(request): files = SomeDataStore().get_files() ... Goal: I'd like to decouple the datastore.py module completely from django, so that it can easily be used standalone. That would mean to get rid of the django.conf.settings usage in datastore.py One obvious way to do it would be to provide the path as an init parameter to the DataStore class. # datastore.py class SomeDataStore: def __init__(self, path) -> None: self.path=path ... However, I use this DataStore in many Django views, and that would require me to always specify the path when instantiating the class, e.g. like so # views.py from datastatus import SomeDataStore def show_files(request): files = SomeDataStore(settings.RELEVANT_PATH).get_files() ... def show_something_else(request): somethings = SomeDataStore(settings.RELEVANT_PATH).get_something_else() ... I'd like to avoid the need in each instantiation to always specify the config setting for … -
Is Asp.net Core Inspired by Django framework and are they the same
I have now understood the Asp.net Core Framework and it seems just like how Django works. I feel asp.net core is greatly inspired by django. They are literally the same. Are they internally also the same? Are the developers of Django behind the development of asp.net core? -
Custom Login Setup django-microsoft-auth Django
I am using django-microsoft-auth in my Django project. I followed this guide. Now, I'm able to log in through Microsoft account(address: http://localhost:8000/admin ) but I don't know how to add a view that will say "Login using Microsoft" and how to link that view with Microsoft authentication page. It will be great if someone can tell me how to do this. You can see this picture. Here Microsoft button is automatically added for login. How to set up a button like this on the home page? -
Django: How to autogenerate a random 6 digit string
I would like to generate a unique 6 digit code each time a user clicks "generate code". Error AttributeError at /subjects/ 'Manager' object has no attribute 'make_random_password' i have added the templates, models and views used for it. ps. Still a beginner in django Views.py class SubjectView(TemplateView): template_name='subjects.html' # context='subjects' random_number = Subject.objects.make_random_password(length=10, allowed_chars='123456789') while Subject.objects.filter(attendcode__temp_password=random_number): random_number = Subject.objects.make_random_password(length=10, allowed_chars='123456789') def get_context_data(self, *args, **kwargs): context = super().get_context_data(*args, **kwargs) context['Attendance code']=Subject.objects.all() context['subjects'] =Subject .objects.all() context['students']=Student.objects.all() context['attendace_code']=Subject.objects.get("attendance_code") obj = CourseRegistration.objects.filter(subject_code__gt=0) no_students=obj.count() # no_students=CourseRegistration.objects.all().count() context['no_students']=no_students return context def get_success_url(self): print(self.kwargs['slug']) return reverse('subject', args=(self.kwargs['slug'],)) Template {% for subject in subjects %} <tbody class="list" style="text-transform:capitalize;"> <tr> <th scope="row"> <div class="media align-items-center"> <a href="#" class="avatar rounded-circle mr-3"> {% if subject.thumbnail %} <img alt="Logo" src="{{subject.thumbnail.url}}"> {% endif %} </a> <div class="media-body"> <span class="name mb-0 text-sm">{{subject.subject_name}}</span> </div> </div> </th> <td class="budget"> {{subject.subject_code}} </td> <td> <div class="d-flex align-items-center"> <span class="completion mr-2">{{no_students}}</span> </div> </td> <td> <div class="d-flex align-items-center"> <span class="completion mr-2">{{attendace_code}}</span> </div> </td> </tr> </tbody> {% endfor %} Models.py class Subject(models.Model): subject_name=models.CharField(max_length=1000,unique=True) subject_code=models.CharField(max_length=7,primary_key=True) lecturer_ID=models.ForeignKey(Lecturer, related_name="subj1_FK",on_delete=models.PROTECT) thumbnail=models.ImageField(blank=True,null=True,upload_to=get_thumbnail) -
automate file upload in django
I want to monitor a folder (which receives new csv file weekly)and add that file to my django model . The purpose simply is to automize upload procedure , any help would be appreciated from django.db import models class FilesAdmin(models.Model): adminupload=models.FileField(upload_to='media') title=models.CharField(max_length=50) def __str__(self): return self.title -
Django Ajax sending value to View function. No errors but no reception either
I have a table and at the end of each row a button that gets the ID and should send it to a View function. Once the view function gets the ID it should send more values just below the table, so staying on the same page. The issue is that while developer tools in Firefox seems to show that the value has been POSTED, I am not getting any confirmation from the view function that is supposed to receive it. I am not getting errors either, and the console.log(data) does show the correct ID $(document).ready(function(){ // open document ready $('.botontest').on('click',function(){ // opening click function var name = $(this).val() alert(name); $.ajax({ // opening ajax obviously url:'{% url 'makingqueries' %}', type:'POST', data:{'name':name, csrfmiddlewaretoken: '{{csrf_token}}'},// closes data field datatype:'text' }); // closing ajax group console.log(name); }); // closing the click function });// closing document ready The View function is simplified because I first wanted to see if it gets anything: def makingqueries(request): if request.method == 'POST': print("got posted id") And the URL is: path('dashboard', views.makingqueries, name='makingqueries'), -
NameError: name 'Bscs' is not defined
enter image description here[please help me, I'm new to making table for database and I don't know how to fix this][2] -
React Django URL Not Found
I'm building a Twitter clone with Django and React. Up until now, I have set up the login and tweet creation, and they work fine. For the Like button, this is my implementation: React: const handleLike = (id)=>{ let posts_list = posts const post_indx = posts_list.findIndex((post=> post.id==id)) posts_list[post_indx].likes++ axios({ method: 'post', headers: { 'Content-Type': 'application/json' }, url: 'http://127.0.0.1:8000/api/tweets/action/', data: { id: post_indx, action:"like" } }).then(function(response){ setPosts(posts_list) // console.log(this.state.posts) } ) } Django URLs: urlpatterns = [ path('admin/', admin.site.urls), path('', home_view), path('api/tweets/', include('tweets.urls')), path('api/token/', MyTokenObtainPairView.as_view(), name='token_obtain_pair'), path('api/token/refresh/', TokenRefreshView.as_view(), name='token_refresh'), ] Tweets App URLs: urlpatterns = [ path('', tweet_list_view), path('<int:tweet_id>/', tweet_detail_view), path('create/', tweet_create_view), path('<int:tweet_id>/delete/', tweet_delete_view), path('action/', tweet_action_view), ] now I know the create tweet works perfectly fine, but the action URL gets the error: Not Found: /api/tweets/action/ Is the problem something other than routing? -
Practical way to render form widget for a OneToMany relation in django. (Need to nest fields of multiple models in one auto generated form)
Let's say we have the following pseudo database structure: models.py class Order(models.Model): ... class OrderItem(models.Model): order = models.ForeignKey(Order, on_delete=models.CASCADE) ... So each Order may contain one or more OrderItems. By default, if I render the default form for these models, we will end up with two separate forms, where the user will have to create the Order first in one form, and then navigate to another form for OrderItem to start creating OrderItems for that Order. Unless I create my own custom form from scratch (which is not integrated with any models) and then write the code to connect it with data models in the server-side. However, this is a very common use case so there has to be a way to handle such a scenario without having to rebuild so much from scratch. Django already has a ManyToManyField which allows us to handle a similar kind of operation where what the user sees in the auto-generated form is simple, yet it involves interaction with multiple data models. How come there's no way to handle such form representation of data without having to do so much from scratch? For example, in Django Rest Framework we can use Nested Relationships to … -
Django filter for ForeignKey included in ManyToMany
I don't know if I'm tired or if the answer is simple but I don't see it I have a model like this: class Company(models.Model): name = models.CharField(max_length=32, unique=True) class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) company_admin = models.ManyToManyField(Company) # ... class GroupData(models.Model): name = models.CharField(max_length=32) company = models.ForeignKey( Company, on_delete=models.CASCADE) If in a view I do: print(request.user.userprofile.company_admin.all()) ...I get a QS with of all the companies to which the user belongs, and are Ok. What I need is to get a filter for GroupData where company 'is included' into this QS in order to get only objects of GroupData based on user 'company_admin' right. Can anyone help me to understand how to get this filter? Great thanks -
Virtual Environment SyntaxError
I just started learning about virtual environments and DJango on JetBrains Academy. The site told me to install DJango by creating a virtual environment first. I tried this in my IDLE Shell and this is the error I keep getting: python -m venv Classroom SyntaxError: invalid syntax python3 -m venv Classroom SyntaxError: invalid syntax Can anyone tell me how I can properly set up a virtual environment and install DJango? Thank you. -
Django docker could not access MYSQL in host server (using docker-compose)
I have a working django application run via docker to be used for production. Currently, its also using a mysql database which is also hosted using docker. This actually works fine. However, as what I learned, hosting mysql database on docker may not be a preferable way to do it in production. Which is why I wanted to use my host server, which has mysql running instead. My problem is, I can't seem to make it my django app connect to the host server's mysql server. This is my docker-compose file. version: '3.9' networks: default: external: true name: globalprint-shared-network services: #db: # image: mysql:5.7 # ports: # - "3307:3306" # hostname: globalprint-db # restart: always # volumes: # - production_db_volume:/var/lib/mysql # env_file: # - .env.prod app: build: context: . ports: - "8001:8000" volumes: - production_static_data:/vol/web hostname: globalprint-backend restart: always env_file: - .env.prod # depends_on: # - db proxy: build: context: ./proxy hostname: globalprint-backend-api volumes: - production_static_data:/vol/static restart: always ports: - "81:80" depends_on: - app volumes: production_static_data: production_db_volume: I actually have tried adding this in app service and made but still it did not work: extra_hosts: host.docker.internal:host-gateway My django settings for database is also this one. Its actually referencing to an … -
Use a variable with extends in Djano
I want to create a Django project with dynamic template (theme). I defined my active template name in setting.py like below. # GLOBAL VARIABLE FOR TEMPLATE ACTIVE_TEMPLATE = "presento" I want to use this variable my project. For example when I use this variable in extends I get an error like this. {% extends "frontend/{{ACTIVE_TEMPLATE}}/base/base.html" %} This is error. TemplateDoesNotExist at / frontend/{{ACTIVE_TEMPLATE}}/base/base.html What is your advice to solve this issue? -
Remove password field from django admin panel
I have implemented search and filtering for Post class in Django admin panel. Post class has no password filed but a password field appeared in admin panel. I want to remove it from admin panel. # admin.py from django.contrib import admin from django.contrib.auth.admin import UserAdmin from django.db import models from .models import Post, Comment class PostAdmin(UserAdmin): ordering = ('created_at',) list_display = ('author', 'blood_group', 'required_bags', 'contact_number', 'created_at', 'is_resolved', 'admin_approved') search_fields = ('author__name', 'blood_group', 'is_resolved',) # Can not add author as it is a foregin key to post readonly_fields = ('created_at',) exclude = ('password',) filter_horizontal = () list_filter = () fieldsets = () admin.site.register(Post, PostAdmin) admin.site.register(Comment) I have tried to remove the password field using exclude = ('password',) in admin.py of post app. It worked for my User model that actually had password field. But it is not working for Post model. Here is code for forms.py # forms.py from django.forms import ModelForm from .models import Post, Comment from django import forms class PostForm(ModelForm): class Meta: model = Post fields = ['description', 'address', 'blood_group', 'required_bags', 'deadlineDate', 'deadlineTime', 'contact_number', 'is_resolved'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for name, field, in self.fields.items(): field.widget.attrs.update({'class' : 'form-control'}) self.fields['deadlineDate'].widget.input_type = 'date' self.fields['deadlineTime'].widget.input_type = 'time' self.fields['contact_number'].widget.input_type = 'number' … -
How to filter queryset by string field containing json (Django + SQLite)
I have the following situation. The Flight model (flights) has a field named 'airlines_codes' (TextField) in which I store data in JSON array like format: ["TB", "IR", "EP", "XX"] I need to filter the flights by 2-letter airline code (IATA format), for example 'XX', and I achieve this primitively but successfully like this: filtered_flights = Flight.objects.filter(airlines_codes__in='XX') This is great but actually not. I have flights where airlines_codes look like this: ["TBZ", "IR", "EP", "XXY"] Here there are 3-letter codes (ICAO format) and obviously the query filter above will not work. PS. I cannot move to PostgreSQL, also I cannot alter in anyway the database. This has to be achieved only by some query. Thanks for any idea. -
Cors problem with nginx/django from react app on docker
I have a question about cors implementation in django. Having a problem with setting the correct cors values. My deployment is on docker. I have a deployed 3 containers: backend: Django + DRF as backend (expose 8000 port) Nginx to server my backend (use exposed 8000 port and set it to 1338) frontend React app used with nginx (uses port 1337) Everything is on localhost. I use axios from frontend to call get/post requests. (I call to 1338 port then I think it is redirected to internal service on 8000 port) For backend I had to install django-cors-headers package to work with CORS. I think I set up it correctly. But there are scenarios where it does not work. In settings.py INSTALLED_APPS = [ ... "corsheaders", ] ... MIDDLEWARE = [ ... "corsheaders.middleware.CorsMiddleware", "django.middleware.common.CommonMiddleware", ... ] First scenario In settings.py CORS_ALLOW_ALL_ORIGINS = True No get/post requests work. Get message: CORS Multiple Origin Not Allowed Second scenario In settings.py CORS_ALLOWED_ORIGINS = ["http://localhost:1337"] Works with get requests, but does not work with post requests. For post requests: options with error: CORS Missing Allow Header post with error: NS_ERROR_DOM_BAD_URI It works if I am not using nginx for backend. I am not sure … -
Why does the Stripe-Signature header never match the signature of request.body?
I'm using Python with Django and am trying to receive webhook events correctly from stripe. However I constantly get this error: stripe.error.SignatureVerificationError: No signatures found matching the expected signature for payload This is the code: WEBHOOK_SECRET = settings.STRIPE_WEBHOOK_SK @csrf_exempt def webhook(request): sig_header = request.headers.get('Stripe-Signature', None) payload = request.body try: event = stripe.Webhook.construct_event( payload=payload, sig_header=sig_header, secret=WEBHOOK_SECRET ) except ValueError as e: raise e except stripe.error.SignatureVerificationError as e: raise e return HttpResponse(status=200) I have also tried modifying the request body format like so: payload = request.body.decode('utf-8') # and also payload = json.loads(request.body) And yet no luck. The error is coming from the verify_header() class method inside the WebhookSignature class. This is the part of the method where it fails: if not any(util.secure_compare(expected_sig, s) for s in signatures): raise error.SignatureVerificationError( "No signatures found matching the expected signature for payload", header, payload, ) So I printed out exptected_sig and signatures before this line and found that regardless of what format request.body is in, signatures is always there (which is good), but they never match the signature from the header. Why is this? -
Adding input tools to a textarea
Am creating a blog website in Django where bloggers are not familiar with Markdown/Markup. So am planning to add these tools to my textarea.(image below). Please suggest an easy way to achieve this. -
Docker Django WhiteNoise, CSS are loaded but not visible
I have succesfuly created image of django, postgresql. I also used whitenoise to serve static files. They have loaded without problem. I see them in inspect mode, also via going directly to link of style 127.0.0.1:8000/static... It have worked without docker before. My problem is that even if they are loaded, no style is applied. Do you fellows have some ideas? Thanks for any help.