Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resolve 2 libraries need different versions of the same dependancy in python
Im trying to install 2 packages: package A requires version <0.16 of package C package B requires version >=0.17 of package C how can such conflict be resolved? -
Why is my CSP header middleware not working in Django?
I have an issue with the CSP Header and how-to parameters in the setting.py in my Django apps. Do you know how to set up for script and style source? and how to put the 'unsafe-inline' and 'style-src-elem' ? can someone explain how parameters works ? setting.py MIDDLEWARE = [ 'csp.middleware.CSPMiddleware', ...] CSP_DEFAULT_SRC = ("'none'", ) CSP_STYLE_SRC = ("'self'", "'unsafe-inline'", "fonts.googleapis.com", "'unsafe-inline'", 'https://stackpath.bootstrapcdn.com') CSP_SCRIPT_SRC = ("'self'", "'unsafe-inline'", "ajax.googleapis.com", "www.googletagmanager.com", "www.google-analytics.com", 'https://cdn.jsdelivr.net','https://code.jquery.com', "'unsafe-inline'", 'https//ajax.cloudflare.com', "'unsafe-inline'", 'http://cdnjs.cloudflare.com/ajax/libs/highlightjs-line-numbers.js/') CSP_IMG_SRC = ("'self'", "data:", "www.googletagmanager.com", "www.google-analytics.com") CSP_FONT_SRC = ("'self'", "'unsafe-inline'", "fonts.gstatic.com",'https://fonts.cdnfonts.com', 'https://stackpath.bootstrapcdn.com') CSP_CONNECT_SRC = ("'self'", ) CSP_OBJECT_SRC = ("'none'", ) CSP_BASE_URI = ("'none'", ) CSP_FRAME_ANCESTORS = ("'none'", ) CSP_FORM_ACTION = ("'self'", ) CSP_INCLUDE_NONCE_IN = ('script-src','script-src-elem') CSP_REPORT_ONLY = True Error return from google chrome localhost console Do you what should I do? is there an easier way? -
bootstrap dropdown menu bar not functional
I am trying to create a dropdown bar using bootstrap in a Django website. Basically what I want to do is that I want a bar with the title of a class and when someone clicks the bar the class video will open as a dropdown menu. But for some reason it's not working. The {{ item.title }} is appearing on the bar but the dropdown is not working. So users can't see the video. Can anyone help me solve this? My html file: {% extends "class/base.html" %} {% load crispy_forms_tags %} {% block content %} <h1>{{ object.title }}</h1> {% for item in object.classes.all %} <div class="dropdown"> <button class="btn btn-secondary dropdown-toggle" type="button" id="dropdownMenu2" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {{ item.title }} </button> <div class="dropdown-menu" aria-labelledby="dropdownMenu2"> <button class="dropdown-item" type="button"><video controls width="250"> <source src="{{ item.video.url }}" type="video/mp4"> Sorry, your browser doesn't support embedded videos. </video></button> </div> </div> {% endfor %} {% endblock content %} Thanks in advance! -
django remove next if nor more authenticated
When a session finished and the user is no more authenticated, Django redirects to whatever is defined in LOGIN_URL. But there is also a next param, like: http://127.0.0.1:8000/accounts/login/?next=/catalog/import/ For most use cases this makes sense, but in my case I don't want it. Is it possible that the redirect is done without the 'next' param? -
How to get url of multiple images stored in folder in Django
I am developing a django app which converts pdf to images.I am using FileField for this purpose and using ModelForms. Once uploaded the pdf files will get converted into .png and stored in a separate folder. The upload and converting pdf to png works fine but now I want to display the converted images. I know I can use url of the uploaded image to display it but the issue is I am uploading a pdf file and hence cannot use the url to display it. I know how to display an uploaded image using url of that image. But I am uploading a pdf file, converting into image and finally storing it into separate folder. So how can I display the images stored? Below is the code I am using: forms.py from django import forms from django.forms import ClearableFileInput from app1.models import UserUploadModel class UserUploadForm(forms.ModelForm): class Meta: model = UserUploadModel fields = ['file'] widgets = { 'file' : ClearableFileInput(attrs = {'multiple': True}), } models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class UserUploadModel(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, null = True) file = models.FileField(upload_to = 'file_uploads') views.py from django.shortcuts import render, redirect … -
How to deal with date change in a django query
I have a model of a kind of todo list that, amongst others, contains fields for the weekday and the time the task has to be completed. Let's say I have a night shift. Some tasks have to be performed before midnight, others after. Now I want to list tasks that, for example, have to be completed on a Friday in the todo list of the shift starting Thursday. One possibility is to reflect that on the model side, i.e., to enter tasks that should be finished Mon-Fri morning with weekdays Sun-Thu. Then the query is rather straightforward, but one has to be careful when entering new tasks. Is there also a way to enter the "correct" weekdays and deal with the date change on the query side? I saw approaches with union and itertools.chain, but then I'm limited in further operations on the queryset (like another filter or annotate). Is there another way? -
Bootstrap datepicker is not functioning properly?
I used datetimepicker to select month and year. On the first click of the page load ,datetimepicker shows months and year.But when I click on the same date field again to change the month, datetimepicker displays dates instead of months. Here I also used select2 in my code.I implemented it in Django web framework. <script> $(function(){ $('#id_from_date').datetimepicker({ format: 'MM/YYYY', }); $('#id_to_date').datetimepicker({ format: 'MM/YYYY', }); }); $(document).ready(function() { $('select').select2(); }); </script> html code: <div class="col-lg-3 col-sm-12"> <h4><b>From Month :</b></h4> {{form.from_date}} </div> <div class="col-lg-3 col-sm-12"> <h4><b>To Month :</b></h4> {{form.to_date}} </div> Can anyone suggest a solution to solve this issue? -
How to return more than one object in django detailview
Is there a way to make django-generic- detailview return more than one object -
trying to delete an item from a list of items
I am trying to delete an item from a list of items, but it deletes all the items in the list when page loads, i am sure its because of the map, i cant think of a way to fix this without making a detail page for the todos but i dont want to make a detail page for the todo item, any help will be appreciated let deleteTodo = async(id) => { console.log(id) fetch(`http://localhost:8000/api/delete/${id}/`, { method: "DELETE", headers: { "Content-Type": "application/json" }, }) } return ( <div className="App"> <div> <div> <form onSubmit={handleSubmit}> <label> Title: <input type="text" placeholder='Title here' onChange={handleInputChange} name="title" value={values.title} /> </label> <br></br> <br></br> <label> Body: <input type="text" placeholder='Body here' onChange={handleInputChange} name="body" value={values.body} /> </label> <br></br> <br></br> <input type="submit" value="Submit" /> </form> </div> <div> {todos.map((todo, index) => ( <div key={index}> <h1>{todo.title}</h1> <h4>{todo.body}</h4> <button onClick={deleteTodo(todo.id)}>delete</button> </div> ))} </div> </div> </div> ); } -
how to make sure a certain django url path is only checked if all the other paths have been checked
I am building an app where users can access their archives through a simple slug, as follows: lekha.cc/<archive_slug> This is exactly as instagram does it. However, whenever I go to any other page, such as lekha.cc/dashboard The code for the archive view runs, saying that it has not found an archive with that slug. This is an issue for 2 reasons: we dont want any excess code to run, and if a user chooses to name their archive 'dashboard', the entire website would potentially break down since no one would be able to access their dashboard. My urls.py folder is as follows: urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls'), name='index'), path('onboarding/', account_views.onboarding, name='onboarding'), path('register/', account_views.register, name='register'), path('login/', auth_view.LoginView.as_view(authentication_form=LoginForm, template_name='accounts/login.html'), name="login"), path('logout/', account_views.logout_view, name='logout'), path('dashboard/', archival_views.dashboard, name='dashboard'), path('account_settings/', account_views.account_settings, name='account_settings'), path('<str:slug>/', main_views.archive, name='archive'), path('item/<str:slug>/', main_views.work, name='work'), ] Does anyone have any solutions to this issue? -
Transform list of dict (with 2 keys/values) in a single dict where values of first key is the key of the second value
I want to make aggregations and use annotate with Count (group by). But I would like to transform my result as below mygroupby = Mymodel.objects.all().values('field1').annotate(total=Count('field1')) result = [wound_stat for wound_stat in wound_stats] currently result [ {'field1': 'A', 'total': 1}, {'field1': 'B', 'total': 4}, {'field1': 'C', 'total': 2}, {'field1': 'D', 'total': 2}, {'field1': 'E', 'total': 2} ] expected result {'A': 1, 'B': 4, 'C': 2, 'D': 2, 'E': 2} what is the best way? regards -
How to build an Online compiler on Django and Python
I have a Blog website, and I want to add the online compiler feature to it. The website's backend is built on Django and Python, and I have no idea how I can integrate an Online compiler into it. The website is hosted on a Linux server with Cpanel, so can anyone suggest how I can start to build an Online Compiler from scratch or integrate the existing ones, and do I have to change any settings on the server? -
How to set Serializer for displaying parent and children as a list DRF?
I'm making an app which is about News News have an attribute called Category which can be nested For example: Human: --BodyOrgans: ----Hand Just to make the issue more clear We need to prepare a way so when making news when we choose Human category,we can access the child which is "BodyOrgan" and when choosing this, accessing "Hand" or other children it might have This is my models file: ``` class News(models.Model): PUBLISH_STATUS = ( ('P', 'Published'), ('W', 'Waiting for approval'), ('D', 'Draft'), ) title = models.CharField(max_length=255) slug = models.SlugField(null=True, blank=True) sign_image = models.ImageField(upload_to='images', null=True, blank=True) summary = models.TextField(null=True, blank=True) description = models.TextField() created = models.DateTimeField(auto_now_add=True) modified = models.DateTimeField(auto_now=True) publish_status = models.CharField(max_length=1, choices=PUBLISH_STATUS, default='D') publish_time = models.TimeField(null=True, blank=True, default=None) publish_date = models.DateTimeField(null=True, blank=True, default=None) author = models.ForeignKey(get_user_model(), on_delete=models.CASCADE) category = models.ManyToManyField('Category') tag = models.ManyToManyField('Tag') def __str__(self): return self.title class Category(models.Model): PUBLISH_CHOICES = ( ('A', 'Active'), ('I', 'Inactive'), ) parent = models.ForeignKey('Category', on_delete=models.PROTECT, null=True, blank=True) name = models.CharField(max_length=50, null=True) publish_status = models.CharField(max_length=1, choices=PUBLISH_CHOICES, default='A') description = models.TextField(null=True, blank=True) tag = models.ManyToManyField('Tag') def __str__(self): return self.name ``` And also Serializer: class CategorySerializer(ModelSerializer): class Meta: model = Category fields = ['name', 'parent'] list = ListSerializer( fields=['name', 'parent'], source='get_parent' ) @staticmethod def get_parent(obj): return … -
Monkey patch datetime.now() in an entire Django app with unittest.mock
I have a Django project with this file structure: . ├── app │ ├── __init__.py │ ├── admin.py │ ├── apps.py │ ├── child_app │ │ └── my_calendar.py │ ├── migrations │ ├── models.py │ ├── tests.py │ └── views.py ├── manage.py └── mock_django ├── __init__.py ├── asgi.py ├── settings.py ├── urls.py └── wsgi.py In my views.py, I have a call to datetime.now(): from datetime import datetime def time_now(): return datetime.now().strftime("%Y-%m-%d %H") And in child_app/my_calendar.py, I have another call to datetime.now(): from datetime import datetime def another_method(): return datetime.now().strftime("%Y-%m-%d %H") This is a simple example, but in real life this Django app has a lot of child apps with many calls to datetime.now(), and I'm trying to write a test to mock all of them. Looking at this answer, I can use this to mock datetime.now() in a module: from django.test import TestCase from unittest import mock from datetime import datetime from views import time_now class TestApp(TestCase): @mock.patch("views.datetime", wraps=datetime) def test_datetime_now(self, views_datetime): views_datetime.now.return_value = datetime(2022, 9, 10, 14) self.assertEqual(time_now(), "2022-09-10 14") This test passes, and I can do the same for the other module: from django.test import TestCase from unittest import mock from datetime import datetime from views import time_now … -
How to use Django sessions
I'm new to Django and i'm trying to build a Todo app with user authentication but i want to add sessions to it whereby everyone can have different tasks attached to their accounts but i don't know how to go about it. I've checked the Django documentation on it but i still don't get it. Here's my models.py from django.db import models from django.contrib.auth.models import AbstractUser # Create your models here. class Task(models.Model): name = models.CharField(max_length=15) completed = models.BooleanField(default=False) def __str__(self): return self.name class User(AbstractUser): name = models.CharField(max_length=200, null=True) email = models.EmailField(unique=True, null=True) bio = models.TextField(null=True, blank=True) profile_image = models.ImageField( null=True, blank=True, default="avatar.png", upload_to='images/') USERNAME_FIELDS = "email" REQUIRED_FIELDS = [] Then here's my view.py from django.shortcuts import render, redirect from .models import Task, User from .forms import AddTaskForm @login_required(login_url="loginPage") def home(request): tasks = Task.objects.all() context = {"tasks": tasks, } return render(request, "task/home.html", context) -
How can I change the Attribute within the parent class while keeping it working as the following figure in django
''' #This is the parent class and I want to change the value of query_param from the child class #without affecting its work class SearchMixin(object): query_param = "q" def get_query_param(self): return self.query_param def get_query(self, request): return request.GET.get(self.get_query_param(), "").strip() def get(self, request, *args, **kwargs): self.query = self.get_query(request) return super(SearchMixin, self).get(request, *args, **kwargs) #child class I'm writing and it's not working class SearchView_(SearchMixin): query_param = "qu" def get_query_param(self): SearchMixin.query_param = self.query_param def get_query(self, request): return request.GET.get(self.get_query_param(), "").strip() def get(self, request, *args, **kwargs): self.get_query_param() self.query = self.get_query(request) return super(SearchView_, self).get(request, *args, **kwargs) ''' -
reverse_lazy with no arguments not found
reverse_url is workin fine with a url that has-no/int:pk but does not work with a url that has /int:pk throws an error NoReverseMatch: Reverse for 'read_bty' with no arguments not found. 1 patterns tried:['read_bty/(?P[0-9]+)$']. The first (class=HBTYIndex) lists all customers created from the (class=HBTYCreateView) and the (class=HBTYReadView) displays the customers order records, the last (class=HBTYOrderView) is supposed to create an order and reverse_lazy to the url 'read_bty' but it keeps on throwing the above error when creating an order. Tried to change from int:pk to int:id still getting the same error. if i change the reverse_lazy to point to a url with no int:pk the record gets added and i get redirected to that page instead of staying on the same page and showing the new added record. Thank You All In Advance Much Appreciate The Knowledge. Views.py class HBTYIndex(generic.ListView): model = HbtyCustomers context_object_name = 'bty' paginate_by = 100 template_name = 'accounts/modals/bty/clientindex.html' ordering = ['-id'] success_url = reverse_lazy('btylist') def get_queryset(self): qs = self.model.objects.all() p_f = CustomerFilter(self.request.GET, queryset=qs) return p_f.qs def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['filter'] = CustomerFilter(self.request.GET, queryset=self.get_queryset()) return context # Create Customer class HBTYCreateView(BSModalCreateView): template_name = 'accounts/modals/bty/create_hbty.html' form_class = btyForm success_message = 'Success: Client was created.' success_url = … -
send POST request in wso2 api manager 4.1.0
I want to send POST request with a body in WSO2.actually I have a django rest frame work with some APIs and I want send requests in wso2 api manager. it's all OK for GET, DELETE but when I want to POST some request I'll receive a bad request from django server. django server is running on : http://localhost:8000/user-api/users/ in wso2 api publisher api's URL is : http://localhost:8243/users/1.0.0 endpoint in wso2 is : http://localhost:8000/user-api/users/ the below picture is what I receive when I send GET request: response on GET request I send POST request with this json as body: post request's json and here is what I receive when I send POST request: servers response on POST request every thig is ok when I check server's url in my browser. sorry for my bad English. thanks for your helps. -
Django ORM deduplication counter
class Country(models.Model): name = models.CharField(max_length=255) class City(models.Model): country = models.ForeignKey(Country, on_delete=models.CASCADE) name = models.CharField(max_length=255) class Score(models.Model): city = models.ForeignKey(City, on_delete=models.CASCADE) I need the deduplicated count of city.country in the score model. canada = Country.objects.create(name="Canada") USA = Country.objects.crerate(name="USA") ottawa = City.objects.create(name="Ottawa", country=cannada) washington = City.objects.create(name="Washington", country=usd) new_york = City.objects.create(name="New York", country=usd) Score.objects.create(city=ottawa) Score.objects.create(city=ottawa) Score.objects.create(city=washington) Score.objects.create(city=new_york) I want Canada 1 point US 2 points like this. city = City.objects.annotate(point= ???) city[0].point ==> 1 city[1].point ==> 1 city[2].point ==> 1 -
How to make the links generated on sitemap with https protocol instead of http - Python script (Django framework)
I have a Python script (Django framework) it automatically generates links in sitemap but it only generates HTTP links, I want the links to be HTTPS this is what sitemap.py have from django.contrib.sitemaps import Sitemap from .models import Theme class ThemeSitemap(Sitemap): changefreq = 'weekly' priority = 0.8 def items(self): return Theme.objects.all().order_by('-id') I tried to add protocol = "https" but it did not work How can I fix that? -
reverse list in the python
I'm trying to reverse a integer and using the below code but the resultant list value in None. The code: int_a= [1,2,3,4,5,6] rev_word = int_a.split() rev_number = rev_number.reverse() rev_number= "".join(rev) it return the TypeError. Why? -
Make a Web App, With Django at the backend and using SQLite as DB and React/Angular/Vue on the front end
Assignment: Make a Web App, With Django at the backend and using SQLite as DB and React/Angular/Vue on the front end. Tables:https://easyupload.io/m/21b2yk equities returns For each equity given in the equities.csv file, there is a time series of returns in the daily_returns.csv file. Objective of App: To create a graphical time series representation of returns for any equity in the DB. Build an upload screen, which should be capable of ingesting any new equities/ returns updation for existing equities. Addition of returns to be done by upload of csv file. Screen to view all equities and returns in the DB. Feature to update/delete data should be present. Instructions: You can use any charting library which you are comfortable with. Use of rest- framework is recommended. Please upload all the work into a GitHub public repo and share the link. Please upload a proper readme to the GitHub repo with instructions to run the repo on local. Having multiple commits when creating the project is recommended to show progress of the project. link for csv file: https://easyupload.io/m/21b2yk contact:sohampal36@gmail.com -
How can I add attrs to image in the code given below
widgets = { 'img':forms.ImageInput(attrs={'class':'box'}), 'title':forms.TextInput(attrs={'class':'box'}), 'title':forms.TextInput(attrs={'class':'box'}), 'title':forms.TextInput(attrs={'class':'box'}), } 'img':forms.ImageInput(attrs={'class':'box'}), this line gives me error. -
Wrap DRF serializer constructor
Let's say I have the following Django REST Framework serializer: class MySerializer(serializer.ModelSerializer): items = serializers.SerializerMethodField() users = UserSerializer(many=True) class Meta: model = MyModel fields = ("id", "items", "users") I want to wrap the serializer constructor in queries_disabled from django-zen-queries to ensure all data has been prefetched and there are no N+1 violations. How can I do this? -
How auth variable is verifying the token?
I want to verify the token id my code its working, but why is working? i setup good? i have that doubt because auth variable does not know the credentials to verify the token, the variable who know the credentials is firebase_app, how auth variable is verifying the token? from firebase_admin import auth from django.conf import settings firebase_creds = credentials.Certificate(FIREBASE_CONFIG_credentials) firebase_app = firebase_admin.initialize_app(firebase_creds) def login(request): token = 'eyJhbGciO...' try: decoded_token = auth.verify_id_token(token)