Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Patch request in Django Rest Framework
I am creating a backend for online shopping. GET, POST are working fine but I am unable to configure PATCH request. I want to have it in the detailed view of an item with the url endpoint <int:item_id>/ Here is models.py: from django.db import models # Create your models here. class Item(models.Model): name = models.TextField() category = models.TextField() brandName = models.TextField() deleted = models.BooleanField(default=False) image = models.ImageField(upload_to='item_cover', blank=True, null=True) The views.py: class ItemList(APIView): # permission_classes = (IsAuthenticated,) def get(self, request, *args, **kwargs): items = Item.objects.all() serializer = listSerializer(items, many=True) return Response(serializer.data) def post(self, request, *args, **kwargs): serializer = itemSerializer(data=request.data) if serializer.is_valid(): serializer.save() else: print(serializer.errors) return Response({"Status": "Added"}) class detailedItem(APIView): def get(self, request, item_id, *args, **kwargs): items = Item.objects.filter(pk=item_id) serializer = listSerializer(items, many=True) return Response(serializer.data) def patch(self, request): try: obj = ?? serializer = itemSerializer(obj, data=request.data, partial=True) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=200) And the urls.py: urlpatterns = [ path('', views.ItemList.as_view(), name='item-list'), path('<int:item_id>/', views.detailedItem.as_view()), path('search/<str:search_query>/', views.FilteredItemList.as_view()), ] What shall I write in the object= to make it work? I have tried reading example of PATCH requests but still unable to get the things the way I want. -
Better alternative for passing complex object from template to views.py on POST call
In views.py on GET call, I create a random list of questions (its a complex object, list of dictionaries) and I send that list to the template (HTML) file using return render(request, 'some_page.html', args). I show one question at a time and once user enters the answer and clicks next, the next question is shown and so on. On every 'next' click, the answer has to be stored back in the database. What are my options on how can I send the answer to the backend while directing the user to the next question? An important thing to note here is that once that list of questions is generated, I cannot generate it again. I have to either save that list somewhere for this instance or pass it to and from views.py and template on every call. I think passing the list on every call is not an ideal solution and looking for a better suggestion. I show the questions in HTML one by one and there is a current index variable which i managed using JS. This is what the end of my GET function in views.py looks like: final_data = [very, complicatedly, ordered, list] final_data = json.dumps(final_data) args … -
Does Django admin support regex url?
I writed something like this: url(r'^oog\d{3}/', admin.site.urls) But when I open admin site, then visit some model. It show me the url is 0.0.0.0:8000/oog000/app... and it could not open. Thanks. -
Retrieving database object in Django using get_absolute_url method of a model
I'm working on a blog website where am using the get_absolute_url method to generate a url for the detail view of a blog post. Then I noticed that all post objects published around 00:00 to 01:00am have the date of the previous day. But when the date and time for the publication of the post is display on the browser it reads the correct date. The bug only appears on the url generated by the get_absolute_url which is used in the views.py file to retrieve the details of the post from the database. I have tried changing the Timezone setting in the settings.py file from my timezone to UTC and nothing. -
Avoid having to pass arguments to update
Is it possible in django to replace: MyModel.objects.get_stuff_to_close_query_set(time).update( status="closed", open_time=None, opener=None ) with: MyModel.objects.my_custom_query_set(time).close() where close() is doing the same thing as update in the first statement? If so, how do I implement close()? Additionally, is it possible to hide the query set by doing something like: MyModel.objects.close_stuff(time) -
Remove Margin from Paragraphs in CKEditor5
I am working on a project where I am utilizing the django-ckeditor package and wish to remove the margin on top and below paragraph elements. Unfortunately, I am having a lot of difficulty doing so. To add context, I am working with CKEditor 5. Is there a way to affect the styling using the configuration available with the django-ckeditor package, or some other way via CSS? I initially thought to try targeting the element via traditional CSS: .cke_editable p { margin: 0 !important; } However this caused no change. -
React and Django REST Framework login system
I'm trying to create a simple login system using React and Django Rest Framework. The userLogin function works but the userLogout doesn't and returns an error. Error details: POST http://127.0.0.1:8000/api/logout/ 403 (Forbidden) Uncaught (in promise) Status: 403 "CSRF Failed: Origin checking failed - http://127.0.0.1:3000 does not match any trusted origins." AuthContext.js import React, { createContext, useState, useEffect } from "react"; import axios from "axios"; const AuthContext = createContext(); export default AuthContext; export const AuthProvider = (props) => { axios.defaults.xsrfCookieName = "csrftoken"; axios.defaults.xsrfHeaderName = "X-CSRFToken"; axios.defaults.withCredentials = true; const api = axios.create({ baseURL: "http://127.0.0.1:8000/api/", }); const [user, setUser] = useState( () => JSON.parse(localStorage.getItem("user")) || null ); const [error, setError] = useState(null); const userLogin = async (email, password) => { try { const { data } = await api.post("login/", { username: email, password: password, }); if (data.error) { setError(data.error); } else { localStorage.setItem("user", JSON.stringify(data)); setUser(data); } } catch (error) { return; } }; const userLogout = async () => { await api.post("logout/"); localStorage.removeItem("user"); setUser(null); }; const authContextData = { api, user, userLogin, userLogout, error, }; return ( <AuthContext.Provider value={authContextData}> {props.children} </AuthContext.Provider> ); }; views.py # --------------------------------------------- # # ------------------- Login ------------------- # # --------------------------------------------- # @api_view(['POST']) @permission_classes([AllowAny]) @authentication_classes([SessionAuthentication]) def user_login(request): if request.method … -
Django Template and Static folders arrangement
I know that similar topics exist but for a half of the day i haven't found a single answer which could clear my doubts. So the question is : I've just started to practice with Django 3.2. But i have an issue with loading a templates and static files from specified folders. ├───project │ ├───first_app │ ├───migrations │ ├───static │ │ └───core │ ├───templates │ │ └───core │ └───__pycache__ ├───project │ ├───static │ └───css └───templates So i want to keep some "global" templates and static files in "project_root/templates" / "project_root/static" and some specific templates/statics within an assigned app (example of path: "project_root/app_name/templates/app_name/index.html" and "project_root/app_name/static/app_name/index.css". The option to keep templates and static files within an app works just well. But when i try to render some .html file from "project_root/templates/" in view.py it doesn't work. Is it correct to store templates/statics in such a way? How to arrange the file structures to make it work? How to point django which exactly template i want to render: from an app folder or from a root folder? Thanks for any response in advance! -
Error While Changing a field From CharField to ForeignKey
models.py from django.db import models from django.contrib.auth.models import User from django.core.validators import MaxValueValidator from django.core.validators import MinValueValidator # Create your models here. class student(models.Model): username = models.ForeignKey(User, on_delete=models.CASCADE) student_name = models.CharField(max_length=100) semester = models.IntegerField(default=1, validators=[MaxValueValidator(8), MinValueValidator(1)]) stream = models.CharField(max_length=50) address = models.CharField(max_length=200) date_of_birth = models.DateField(auto_now=False, auto_now_add=False) roll_number = models.CharField(max_length=20) This is the model I have also registered the model in admin.py and in settings.py. When I am trying to see the student table it hits me with this error, after changing the username coloumn from CharField to ForeignKey, When I change back to Charfield the problem gets fixed. I cleared all the data using python manage.py flush. Then used makemigration and migrate. But the problem exists still. -
Django redirecting to home after login does not work
I am trying to redirect to homepage after login with no sucess settings.py LOGIN_REDIRECT_URL = 'home' LOGOUT_REDIRECT_URL = 'home' urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', home, name='home'), path('defaultsite', home, name='home'), ] views.py def home(request): return render(request, 'general/index.html') ] I do not have a personalized Django login system (usying system default) but nothing seems to work. Changing LOGIN_REDIRECT_URL = 'home' to LOGIN_REDIRECT_URL = '/' does not work either. Strangely, LOGOUT_REDIRECT_URL = 'home' works like a charm. Any help? Using Django 4.1.7 & python 3.10.5 -
Is it possible to mock SimpleUploadedFile?
I have a function like this: def my_func(): [...] with open(full_path, "rb") as file: image.image = SimpleUploadedFile( name=image.external_url, content=file.read(), content_type="image/jpeg", ) image.save() print(f"{file_name} - Saved!") I would like mock the "SimpleUploadedFile" for a test (calling print...). Is it possible? A little bit of context: the function download and upload files. Maybe the test is not necessary... -
How to update articles in Python Django?
I made a blog using Django. I watched a lot of videos to make a function that the user can update/edit own articles. But I did not get it work. I'm new in Django, so if anyone can help me, I would be thankful. Here is my views.py: from django.shortcuts import render, redirect from .models import Article from django.http import HttpResponse from django.contrib.auth.decorators import login_required from . import forms #from django.core.paginator import Paginator from django.core.paginator import Paginator, EmptyPage, PageNotAnInteger @login_required(login_url="/accounts/login/") def article_list(request): articles = Article.objects.all().order_by('-date') paginator = Paginator(Article.objects.all().order_by('-date'), 6) page = request.GET.get('page') try: items = paginator.page(page) except PageNotAnInteger: items = paginator.page(1) except EmptyPage: items = paginator.page(paginator.num_pages) index = items.number - 1 max_index = len(paginator.page_range) page_range = paginator.page_range[0:max_index] return render(request, 'articles/article_list.html', {'articles':articles, 'items':items, 'page_range':page_range}) @login_required(login_url="/accounts/login/") def article_details(request, slug): article = Article.objects.get(slug=slug) return render(request, 'articles/article_details.html', {'article':article}) @login_required(login_url="/accounts/login/") def article_create(request): if request.method == 'POST': form = forms.CreateArticle(request.POST, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('articles:list') else: form = forms.CreateArticle() return render(request, 'articles/article_create.html', {'form':form}) @login_required(login_url="/accounts/login/") def article_edit(request, slug): article = Article.objects.get(slug=slug) form = forms.CreateArticle(request.GET, request.FILES) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return redirect('articles:list') return render(request, 'articles/article_edit.html', {'form':form}) I was trying to do the view in article_edit. Here … -
Django Session works in localhost but not in remote server
I have set a session value during my login view upon successful user authentication. However, this session value is returning None in another view while i am trying to access it(The same code works in my local environment) login_view @csrf_excempt @api_view(['POST']) def login_view(request): # Authenticate user - upon success authentication request.session['username'] = username request.session['password'] = password # Able to print the stored session value here as well print(request.session.get('username')) **Redirect to landing.html** Once the user is authenticated and the landing page is loaded upon session check. def index(request): print("the session value is : ", request.session.get('username')) #this returns None if request.session.get('username') return render(request, 'landing.html') # if session present, render the landing.html page else: return render(request, 'auth.html') #if session not present, reload the login page again what am i missing here? I tried a lot to debug, but to no avail. while running in my local environment, i can see the cookies in the browser while i inspect the page, but it is not the case while i run it over my apache server. Also, i am using file based sessions and i have set the SESSION_ENGINE and SESSION_FILE_PATH accordingly. I also tried looking at similar questions already being asked on the same, … -
When QuerySet is evaluated when get_queryset is overridden
Have not understand very well how QS is evaluated when overriden. Based on leedjango question, we are able to override get_queryset in a view class. In this same example, I have not been able to understand when the get_queryset method is returning the QS evaluated. We know how QS are evaluated in general, as it is explained in eugene question. For instance, I have the following components: Front End sending GET request to the appropriate URL: //Dashboard.js: export default function Dashboard() { const [tableData, setTableData] = useState([]); const getUserSchools = () => { getUser({ email: keycloak.email }).then((response) => { const { data: users } = response; if (users.length) { const appUser = users[0]; axios .get(`/api/school/list/?user_id=${appUser.id}`) .then((data) => { setTableData(data.data.results); }) .catch((err) => { /* eslint-disable-next-line */ console.error(err); setTableData([]); }); } }); }; Then, it hits the school-urls.py looking for which view is related to that URL: urlpatterns = [ url(r"^list/$", SchoolsList.as_view()), ] SchoolsList is the appropriate View which is overriding get_queryset and returns the queryset: #list.py class LargeResultsSetPagination(pagination.PageNumberPagination): page_size = 10 page_size_query_param = 'page_size' max_page_size = 100 class SchoolsList(generics.ListAPIView): pagination_class = LargeResultsSetPagination serializer_class = SchoolGetSerializer def get_queryset(self): queryset = School.objects.all() user_id = self.request.query_params.get('user_id', None) if (user_id is not None): queryset … -
How to load the display name when using `values()` of a `CharField` when using `models.TextChoices` in Django
I have a model that looks like this: models.py class Client(models.Model): class Status(models.TextChoices): CD = "CD", "Closed" UC = "UC", "Under Contract" status = models.CharField( max_length=2, choices=Status.choices, default=Pipeline.CD, ) and a view that looks like this: views.py class ClientsListView(generic.ListView): queryset = Client.objects.all() If I wanted to grab the display name of the status field, it would look something like this: clients.html {% for client in object_list %} {{ client.get_status_display }} {% endfor %} I want to change the ClientsListView class in views.py to use values() so I can limit the number of fields that are loaded so I changed it to this: class ClientsListView(generic.ListView): def get_context_data(self, **kwargs): context = super().get_context_data() context["clients"] = Clients.objects.all().values() return context But now I don't have access to the display name of status. How would I go about loading that into what is returned in values()? -
my registration view is not saving user data to database django python (only through admin panel)
I just started learning Django and got somewhat into it so far, but I've been stuck on why my views are not saving the model data successfully to the database (I'm using postgres). I found out that I'm able to add the models through the admin panel so I believe the fields are fine, I think it may be due to configuration? I'm not too confident on that, any help would be appreciated! Here's the project structure and code below Project Structure views.py from django.contrib.auth import authenticate, login, logout from django.shortcuts import render, redirect from .forms import RegistrationForm, LoginForm from django.contrib import messages from django.http import * from .models import newUser, userEvents def registerView(request): if request.method == 'POST': form = RegistrationForm(request.POST) if form.is_valid(): # if the form is filled and data is valid if User.objects.filter(username=form.cleaned_data['user_name']).exists(): # Check if the record exists # in the DB already # redirects to the success page redirect('login/') else: createUser = newUser(user_name=form.cleaned_data['user_name'], first_name=form.cleaned_data['first_name'], last_name=form.cleaned_data['last_name'], email_address=form.cleaned_data['user_email'], date_of_birth=form.cleaned_data['date_of_birth']) createUser.save() # save the user to the database User.objects.create_user(createUser.user_name, createUser.email_address, form.cleaned_data['user_pass']) return render(request, 'login.html') # if a GET (or any other method) we'll create a blank form else: form = RegistrationForm() # TODO: Create register.html template and then test! … -
Django tutorial, Page not found <int:question_id>
My views.py from django.http import HttpResponse, Http404 from django.shortcuts import render, get_object_or_404 from .models import Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, question_id): question = get_object_or_404(Question, pk=question_id) return render(request, 'polls/detail.html', {'question': question}) My urls.py from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('/', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), ] When I going at 'http://127.0.0.1:8000/polls/1/' I receive 'Page not found' error but I definitely have this question_id, I can see this question_id in shell, it doesn't matter what ID I have write I always receive the same issue. -
Django session is lost after redirection to the same host
I've a class based django view where at some certain point I've some variables in the request.session, the user has been logged in in that view (just a few lines before), and I make a redirection to /sth/ . When the browser reaches /sth/, it has none of the previously set variables, they're gone, and no idea why. Checking the browser, the sessionid is different, but no idea why. Anyone would have an idea what can be problem, what to check? Thanks. -
Reverse for 'products_category' with keyword arguments '{'products_po_category': <QuerySet [<Product: Maybach>]>}' not found
Hi I need to implement the following: I have a form with a category selection, and based on the selected category, I need to redirect the user to a page with products for this category. URLS.PY from django.urls import path from first.views import productsHTML, productHTML, products_category urlpatterns = [ path("products_category", products_category, name = "products_category"), path("productsHTML/<str:uuid>", productHTML, name = "productHTML"), path("productsHTML/", productsHTML, name = "productsHTML"), ] VIEWS.PY from django.shortcuts import render, redirect from .models import Product from .forms import CategoryChoice def productsHTML(request): form = CategoryChoice(request.POST or None) if request.method == 'POST' and form.is_valid(): category = form.cleaned_data['category'] products_po_category = Product.objects.filter(category=category) return redirect('products_category', products_po_category=products_po_category, permanent=True) all_products = Product.objects.all() context = { 'form': form, 'products': all_products, } return render(request, "products.html", context) def products_category(request,products_po_category): context = { "products_po_category": products_po_category } return render(request, "product_category.html", context) Through form.cleaned_data['category'] I get data about the selected category and then, through Product.objects.filter(category=category) I get the objects of this category and after all this I redirect to the page with the products of this category, passing the list of objects of the selected categories. FORMS.PY from django import forms from .models import Product class CategoryChoice(forms.ModelForm): class Meta: model = Product fields = ('category',) widgets = { 'category': forms.Select(), } full text … -
Celery raises an Received unregistered task of type 'default.add error
I have a simple Django based Celery application. The folder structure is: celery_poc | |--db |----celery.py |----settings.py | |--demoapp |----apps.py |----models.py |----tasks.py The content of celery.py is : import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "db.settings") app = Celery("db") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() The content of settings.py is: INSTALLED_APPS = [ 'django_celery_results', 'demoapp', ] CELERY_BROKER_URL = "amqp://guest@localhost//" CELERY_RESULT_BACKEND = 'django-db' The content of tasks.py is: from celery import shared_task @shared_task def add(x, y): return x + y if __name__ == "__main__": add.delay(4, 4) I'm using RabbitMQ as the broker and Postgres as the results backend. When I ran tasks.py I get the following error from Celery: [2023-03-23 15:33:37,528: ERROR/MainProcess] Received unregistered task of type 'default.add'. The message has been ignored and discarded. Did you remember to import the module containing this task? Or maybe you're using relative imports? Please see http://docs.celeryq.org/en/latest/internals/protocol.html for more information. The full contents of the message body was: '[[4, 4], {}, {"callbacks": null, "errbacks": null, "chain": null, "chord": null}]' (81b) Thw full contents of the message headers: {'lang': 'py', 'task': 'default.add', 'id': '65488acd-5591-441a-b7d6-f5ff73a564e1', 'shadow': None, 'eta': None, 'expires': None, 'group': None, 'group_index': None, 'retries': 0, 'timelimit': [None, None], 'root_id': '65488acd-5591-441a-b7d6-f5ff73a564e1', 'parent_id': None, 'argsrepr': '(4, 4)', 'kwargsrepr': '{}', … -
Django No records found on query
I'm trying to filter web search results of apartments on django3 but it doesn't matter what I put on the filters while filling the form, It shows the message "no records found" no mater how do I fill the form. The database is already populated. my views.py def apartments_list(request): name = request.GET.get('name') address = request.GET.get('address') status = request.GET.get('status') price_range = request.GET.get('price_range') no_of_person = request.GET.get('no_of_person') bed_type = request.GET.get('bed_type') query = Q() if name: query &= Q(title__icontains=name) if address: query &= Q(apartmentaddress__city__icontains=address) if no_of_person and no_of_person.isdigit(): query &= Q(persons=int(no_of_person)) if bed_type: query &= Q(bed=bed_type) if price_range: min_price = price_range.split('-')[0] max_price = price_range.split('-')[1] query &= Q(price__gte=min_price) query &= Q(price__lte=max_price) page = request.GET.get('page', 1) apartments = Apartment.objects.filter(query).order_by('price') paginator = Paginator(Apartment.objects.filter(query), 10) try: apartments = paginator.page(page) except PageNotAnInteger: apartments = paginator.page(1) except EmptyPage: apartments = paginator.page(paginator.num_pages) context = {} context['apartments'] = apartments context['name'] = name context['address'] = address context['no_of_person'] = no_of_person context['bed_type'] = bed_type context['price_range'] = price_range My models.py class Apartment(models.Model): APARTMENT_CHOICES = ( ("Available", "Available"), ("Booked", "Booked") ) clean_status = models.BooleanField(default=False) inspected_status = models.BooleanField(default=False) title = models.CharField(max_length=100) apartment_status = models.CharField( max_length=255, choices=APARTMENT_CHOICES, default='Available') services = models.CharField(max_length=255) capacity = models.IntegerField() bed = models.CharField(max_length=100) price = models.IntegerField() persons = models.IntegerField() category = models.ForeignKey(ApartmentCategory, on_delete=models.CASCADE) owner = … -
Better approach to serialize data that contains multiple related Models using Django Rest Framework
Background I am new to Django and DRF and I am currently writing a view that handles a GET request. The view will return a JSON that contains data associated with 5 related models. Here is a visualization of my database . And this is what I expect to get [ { "word": "hello", "entries": [ { "tag": null, "link": "", "value": "TEST" }, { "tag": null, "link": "", "value": "STUFF" } ] }, { "word": "Hello", "entries": [] } ] Problem My current approach is to use Django query to construct a self defined object and then define a DRF serializer to serialize it. The code looks like this # Inner Object class DetailEntry(): def __init__(self, tag, link, value): self.tag = tag self.link = link self.value = value # Outer Object class ReviewEntry(): def __init__(self, word, entries): self.word = word self.entries = entries class GetReview(APIView): def get(self, request, format=None): # get current user currentUser = User.objects.get(id=request.user.id) records = Record.objects.filter(user_id=currentUser) reviewEntries = [] for record in records: word = record.word_id quotes = Quote.objects.filter(record_id=record) detailEntries = [] for quote in quotes: tag = quote.tagAssignment_id link = quote.link value = quote.value detailEntries.append(DetailEntry(tag, link, value)) reviewEntries.append(ReviewEntry(word, detailEntries)) s = ReviewSerializer(reviewEntries, many=True) return Response(s.data) … -
How to send django template form to telegram bot in Django
I can't find way to send django template form to telegram bot in Django like send message to telegram bot via website! I don't know how to do this so i need help with explaining -
i have creating my app django but i can't use it
i'm using django i create my app with this commande django-admin startapp Bplan first it look everythings is right the new folder was added with all his fles i also add it in INSTALLED_APP [ ...'Bplan',...] but when i try to check the list off installed app with this commande : "python manage.py shell -c "from django.apps import apps; print([app.name for app in apps.get_app_configs()])" it show only the default app also when i try to migrate to database with python3 manage.py migrate every this look ok in the terminal but i cant see the new tables on my postgresql can you help me please -
django-fsm can't transition state
Why do I get the error below when I tried to do the transition? Is this a bug? Thanks >>> t = Task.objects.first() >>> t.state "(0, 'Open')" >>> t.to_in_progress() Traceback (most recent call last): File "<console>", line 1, in <module> File "/Users/dingli/projects/personal/django_history_fsm_guardian/lib/python3.11/site-packages/django_fsm/__init__.py", line 573, in _change_state return fsm_meta.field.change_state(instance, func, *args, **kwargs) ^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^^ File "/Users/dingli/projects/personal/django_history_fsm_guardian/lib/python3.11/site-packages/django_fsm/__init__.py", line 339, in change_state raise TransitionNotAllowed( django_fsm.TransitionNotAllowed: Can't switch from state '(0, 'Open')' using method 'to_in_progress' Here is the model. STATES = ('Open', 'In Progress', 'Resolved', 'Re Opened', 'Closed') STATES = list(enumerate(STATES)) class Task(models.Model): title = models.CharField(max_length=100, null=False) description = models.TextField() state = FSMField(default=STATES[0], choices=STATES) def __str__(self): return f'{self.title}: {self.description}' @transition(field=state, source=['Open', 'Re Opened'], target='In Progress') def to_in_progress(self): pass @transition(field=state, source='In Progress', target='Resolved') def to_resolved(self): pass I also tried the following approach, but got the same error. @transition(field=state, source=[(0, 'Open'), (3, 'Re Opened')], target=(1, 'In Progress')) def to_in_progress_1(self): pass