Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to exclude certain system checks from running on `manage.py migrate`?
I have created a series of checks using Django's System check framework. Some of the checks are used to confirm that fixtures are set up correctly. For example, I have a check that confirms if all users have at least one group. @register(Tag.database) def check_users_have_group(app_configs, **kwargs): errors = [] users = UserModel.objects.all() for user in users: if not user.groups.exists(): message = f'{user} has no permission groups set.' errors.append( Error( message, obj='account', id=f'check_user_{user.id}_permission_groups' ) ) return errors Django's default is to run checks on migration. If I deploy the app without an existing database, then when I run migrate to set up the database the above check will cause a ProgrammingError because the table is not yet created: django.db.utils.ProgrammingError: relation "accounts_account" does not exist How can I exclude this test from running on python manage.py migrate? I want to run this after the migration is complete. -
How to use an absolute path in AJAX with Django?
I use AJAX in my Django project. I would like this AJAX request works for all pages of my project. But it works only for one page and I see that AJAX use the relative path. $.ajax({ type: 'POST', url: {% url 'check_message_st_ajax' %}, headers: {'X-CSRFToken': csrftoken}, data: review_data, dataType: 'json', success: function (response) { const new_messages = JSON.parse(response.mes_list); var number_mes = new_messages.length $('#number_mes').text(new_messages.length); }, }) -
How to use variable in a double underscore method in python / django
I am using the django framework to create a website where i have to do some filtering on my database. I have created a function where you can filter upon any field in the database. I need to use the __gte method to find all records which is greater than or equal to a particular field. I pass the desired field as attribute inside my function. How can i find all records greater than or equal to any field that i pass into my function? def top_percentiles(attribute, web_name, player_id): #filters to find desired player e.g Ronaldo searched_player = PlayerInfo.objects.filter(web_name=web_name, id=player_id) #gets the value of the desired attribute e.g price = 10.0 players_attribute = getattr(searched_player[0], attribute) #filters for all the players with a greater value e.g 10.5, 11.0 players_with_greater_attribute = PlayerInfo.objects.filter(attribure__gte=players_attribute) Error message: Cannot resolve keyword 'attribute' into field. Choices are: assists, bonus, bps... -
How to deal with `Migration is applied before its dependency`
I have been assigned the task to work on project involving react UI and django backend. There are two versions of this app: older version which runs on older versions of react and python (v2) newer version which runs on newer versions of react and python (v3) I have been tasked to move some functionality from older version to newer version and test it with postgres database dump from a live environment running older version. The challenge could be differences in the database schema of newer and older versions. (But, most possibly there wont be much differences if some minor ones.) So I proceeded to take the database dump, attached it to the database running on my laptop and specified its name in my django's settings.ini. But when I started my django app, it gave me error You have 7 unapplied migration(s). Your project may not work properly until you apply the migrations for app(s): admin, auth, lab, otherlabs. Run 'python manage.py migrate' to apply them. When I ran python manage.py migrate, it gave me an error: Migration abc.0001_initial is applied before its dependency auth.0011_xyz on database 'default'. So, I deleted record corresponding to abc.0001_initial from django_migrations table and reran … -
django activate link/button if the path startes with `<path>`
I'm building a Django app and I have a link on my navbar that I want to activate it(means add a css class) if the path starts with <base_url>/accounts/ I tried the following and it doesn't work {% url 'accounts:profile' as pro %} {% url 'accounts:setting' as set %} {% url 'accounts:anotherpage' as ano %} This doesn't work {% if request.path == pro or request.path == set or request.path == ano %} active {% endif %} -
Django not auto populating current user foreign key
I'm inserting entries into my database from the front end but the current logged in user foreign key is not populating. It get's entered as null. here is my model: from django.db import models from django.contrib.auth.models import User # Create your models here. class WordsAndPhrases (models.Model): word_or_phrase = models.CharField(max_length=20000) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) added_by = models.ForeignKey(User, null=True, on_delete=models.DO_NOTHING) def __str__(self): return self.word_or_phrase here is my views.py code snippet. def upload(request): if request.method == 'POST': wordOrPhrase = request.POST['word-or-phrase'] currentUser = request.user print(currentUser) newEntry = WordsAndPhrases(word_or_phrase = wordOrPhrase) addedBy = WordsAndPhrases(added_by = currentUser) newEntry.save() return render(request, 'display_words_phrases_app/upload.html') Thanks in advance. -
Why I'm getting name 'request' is not defined in python django 4.1 while rendering a template
name 'request' is not defined Request Method: GET Request URL: http://127.0.0.1:8000/gatepass/gatepass_approve/23/1 Django Version: 4.1 Exception Type: NameError Exception Value: name 'request' is not defined -
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.