Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django DRF - Only allow access to view if user is at a specific physical location
I'm working on a game (react front-end, DRF back-end) that requires users to visit physical locations to win digital prizes. I want to make sure the participants physically visit the locations and don't just make a request from their home to the prize endpoint using curl or postman. What is the best strategy for this? Haven't tried anything yet; not sure where to start. -
Why is my Django rest framework api returning an empty list?
Hello I am working on an Django Rest Framework api and one of the views is returning an empty list. here's my view: @api_view(['GET']) def post_search(request): form = SearchForm() query = None results = [] if request.method == 'GET': if 'query' in request.GET: form = SearchForm(request.GET) if form.is_valid(): query = form.cleaned_data['query'] results = Paper.objects.annotate( search=SearchVector('abstract', 'title'),).filter(search=query) serializer = PaperSerializer(results, many=True) return Response(serializer.data) here is the form: class SearchForm(forms.Form): query = forms.CharField() and here are my urls: path('search/', views.post_search, name='post_search'), So on the shell I ran: Paper.objects.annotate(search=SearchVector('abstract', 'title'),).filter(search='Type') and I got the results I wanted but when do this: import requests url = 'http://127.0.0.1:8000/api/search/?search=Type' re = requests.get(url) re.json # -> [] # or import json json.loads(re) # ->raise TypeError(f'the JSON object must be str, bytes or bytearray, ' TypeError: the JSON object must be str, bytes or bytearray, not Response Any help will be appreciated; thanks -
How do I "flatten" a nested serializer in DRF?
We have a nested serializer that we would like to "flatten". But I'm not having much luck finding how to achieve this in the docs. Here is the current output. { "user_inventory": "UOHvaxFa11R5Z0bPYuihP0RKocn2", "quantity": 1, "player": { "card_id": "c69c0808328fdc3e3f3ee8b9b7d4a7f8", "game": "MLB The Show 22", "name": "Jesus Tinoco", "all_positions": [ "CP" ] } } Here is what I'd like: { "user_inventory": "UOHvaxFa11R5Z0bPYuihP0RKocn2", "quantity": 1, "card_id": "c69c0808328fdc3e3f3ee8b9b7d4a7f8", "game": "MLB The Show 22", "name": "Jesus Tinoco", "all_positions": [ "CP" ] } Here is how the serializers are setup: class PlayerProfileSerializer(serializers.ModelSerializer): class Meta: model = PlayerProfile fields = ( 'card_id', 'game', 'name', 'all_positions', ) class UserInventoryItemSerializer(serializers.ModelSerializer): player = PlayerProfileSerializer() class Meta: model = UserInventoryItem fields = ( 'user_inventory', 'quantity', 'player', ) Here is the view: class OwnedInventoryView(viewsets.ModelViewSet): serializer_class = UserInventoryItemSerializer filterset_class = UserInventoryItemFilter def get_queryset(self): order_by = self.request.query_params.get('order_by', '') if order_by: order_by_name = order_by.split(' ')[1] order_by_sign = order_by.split(' ')[0] order_by_sign = '' if order_by_sign == 'asc' else '-' return UserInventoryItem.objects.filter(user_inventory=self.kwargs['user_inventory_pk']).order_by(order_by_sign + order_by_name) return UserInventoryItem.objects.filter(user_inventory=self.kwargs['user_inventory_pk']) -
Python - Django - Form fields not showing on HTML page
I am learning Django and am trying to set up a simple form HTML with form fields which I can send via POST method. However, if I load HTML page the fields are not visible The HTML page is create.html {% extends 'main/base.html' %} {% block title %} Create a task {% endblock %} {% block content %} <h1>Create a task</h1> <form method="post"> {% csrf_token %} {{ form.title }} {{ form.task }} <button type="submit" class="btn btn-success">Add</button> <span>{{ error }}</span> </form> {% endblock %} <input type="text" placeholder="Enter name" class="form-control"><br> <textarea placeholder="Enter description" class="form-control"></textarea><br> My forms.py file is as follows: from .models import Task from django.forms import ModelForm, TextInput, Textarea class TaskForm(ModelForm): class Meta: model = Task fields = ["title", "task"] widgets = { "title": TextInput(attrs={ 'class': 'form-control', 'placeholder': 'Enter name' }), "task": Textarea(attrs={ 'class': 'form-control', 'placeholder': 'Enter description' }), } and views.py is as this: from django.shortcuts import render, redirect from .models import Task from .forms import TaskForm def index(request): tasks = Task.objects.order_by('id') return render(request, 'main/index.html', {'title': 'Main page of this website', 'tasks': tasks}) def about(request): return render(request, "main/about.html") def create(request): error = '' if request.method == 'POST': form = TaskForm(request.POST) if form.is_valid(): form.save() redirect('home') else: error = 'The form has … -
django.db.utils.IntegrityError: null value in column "id" violates not-null constraint superuser
I'm writing a site on django. And I ran into a problem, when I want to add a superuser, the following error occurs: django.db.utils.IntegrityError: null value in column "id" violates not-null constraint DETAIL: Failing row contains (pbkdf2_sha256$390000$gajFrJerChyUlrAwZWzfkS$gmZ4GQTavfwqlV5jaPl+..., null, t, admin_dima, , , t, t, 2023-01-07 22:12:28. 743122+00, null, , dima1@gmail.com, , ). I think it has something to do with the fact that I'm using a model that inherits from AbstractUser Here is my model: class JobseekerRegisterInfo(AbstractUser): id = models.IntegerField(primary_key=True) phone_number = PhoneNumberField() email = models.EmailField(unique=True) full_name = models.CharField(max_length=120) hashed_password = models.CharField(max_length=200) def __str__(self): return self.full_name And I commented for a while in the settings.py file and the main urls.py file the link to the admin page, and before that, how to create a superuser, I uncommented it again -
DatabaseError when trying to print all flatpages in Django template
I have a Django app that I have just added flatpages to. The issue I am running into is printing out the list of all flatpages that I have created. The reason I want to do this is so that I can print them out in a header navigation template so that they will appear automatically as I create/remove them. Else I would manually have to update the html file to add a new link. I have this added in my views.py urlpatterns += [ re_path(r'^(?P<url>.*/)$', views.flatpage), ] Right now I am using the flatpages default template as my test file. Error: DatabaseError at /aaa/ No exception message supplied Request Method: GET Request URL: http://214.191.20.123/aaa/ Django Version: 3.2 Exception Type: DatabaseError Exception Location: /home/django/parser/venv/lib/python3.8/site-packages/djongo/cursor.py, line 59, in execute Python Executable: /home/django/parser/venv/bin/python Python Version: 3.8.10 Python Path: ['/home/django/parser', '/home/django/parser/venv/bin', '/usr/lib/python38.zip', '/usr/lib/python3.8', '/usr/lib/python3.8/lib-dynload', '/home/django/parser/venv/lib/python3.8/site-packages'] Server time: Sat, 07 Jan 2023 22:01:23 +0000 Error: Environment: Request Method: GET Request URL: http://214.191.20.123/aaa/ Django Version: 3.2 Python Version: 3.8.10 Installed Applications: ['adobeparser', 'cbs_parser', 'segment_parser', 'parsers', 'crispy_forms', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'django.contrib.flatpages'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.contrib.flatpages.middleware.FlatpageFallbackMiddleware'] Template error: In template /home/django/parser/parsers/templates/flatpages/default.html, error at line 25 (Could not … -
django-admin startproject error (version conflict?)
When I run "django-admin startproject myproject" I get the following error: Traceback (most recent call last): File "/System/Volumes/Data/Library/Frameworks/Python.framework/Versions/3.11/bin/django-admin", line 5, in from django.core.management import execute_from_command_line File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/core/management/init.py", line 17, in from django.conf import settings File "/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/site-packages/django/conf/init.py", line 14, in from pathlib import Path File "/opt/anaconda3/lib/python3.9/site-packages/pathlib.py", line 10, in from collections import Sequence ImportError: cannot import name 'Sequence' from 'collections' (/Library/Frameworks/Python.framework/Versions/3.11/lib/python3.11/collections/init.py) I'm assuming the problem is due to problems involving multiple locations and versions. Does that seem to be the correct assumption? Suggestions for how to fix this? -
Django-Stripe how to get the product data in the checkout session
I am still new to django and I am working on a django website whereby users can purchase goods and pay through Stripe. I have been following a tutorial and the tutorial has managed to make a payment but the problem is that the figures they are using are hard coded. My issue currently is how to get the values of what I am selling from the database. Here is my views.py: def bookService(request, gig_id): gig = Gig.objects.get(gig_id = gig_id) context = {'gig':gig} return render(request, 'payments/book.html', context) @csrf_exempt def create_checkout_session(request): #Updated- creating Order object order=Order(email=" ",paid="False",amount=0,description=" ", buyer=request.user.profile) order.save() session = stripe.checkout.Session.create( client_reference_id=request.user.id if request.user.is_authenticated else None, payment_method_types=['card'], line_items=[{ 'price_data': { 'currency': 'usd', 'product_data': { 'name': 'Intro to Django Course', }, 'unit_amount': 10000, }, 'quantity': 1, }], #Update - passing order ID in checkout to update the order object in webhook metadata={ "order_id":order.id }, mode='payment', success_url=YOUR_DOMAIN + '/success.html', cancel_url=YOUR_DOMAIN + '/cancel.html', ) return JsonResponse({'id': session.id}) Here is the URLs file urlpatterns = [ path('seller/<str:gig_id>/', views.bookService, name='home'), path('create-checkout-session/', views.create_checkout_session, name='checkout'), path('success.html/', views.success,name='success'), path('cancel.html/', views.cancel,name='cancel'), ] And here is the template whereby I am viewing the details and also whereby the button that redirects users to pay is located: <script type="text/javascript"> // … -
How can I Render Data To Main Template In Other Extended View From Main Template?
First of all, hello everyone. I apologize to everyone for my bad English, I will try my best. I am making a video site, in this site there are three main views, they are single-video-view, index-view and main-view. All other views extends from main-view (%extends 'base/main.html' %). There is a sidebar that should appear on all pages. In this sidebar, the categories of pre-loaded videos should be listed. My urls.py: urlpatterns = [ path('',views.index,name="index"), path('main/',views.main,name="main"), path('video/<slug:slug>/',views.video,name="video"), #path('test/',views.category,name="setcategory"), path('apivideo/',views.apivideo,name="apivideo"), ] If I visit main.html directly working fine Single video view, categories not listing Index view, categories not listing View.py: def index(request): # q = request.GET.get('q') # if request.GET.get('q') != None: if 'q' in request.GET and request.GET['q']: page = request.GET.get('page', 1) q = request.GET['q'] videos = Video.objects.filter( Q(video_title__icontains=q) | Q(video_tags__icontains=q)) paginator = Paginator(videos, 24) videos = paginator.page(page) return render(request, 'base/index.html', {'videos': videos, 'q': q}) else: main(request) videos = Video.objects.all().order_by("-id") paginator = Paginator(videos, 24) page_number = request.GET.get('page') videos = paginator.get_page(page_number) return render(request, 'base/index.html', {'videos': videos}) def main(request): setcategory = [] category = Video.objects.values_list('video_tags', flat=True) for i in range(0, len(category)): for x in range(0, len(category[i])): categorycount = Video.objects.filter(Q(video_title__icontains=str( category[i][x]).lower()) | Q(video_tags__icontains=str(category[i][x]).lower())).count() if (categorycount >= 10): print("if: " + str(categorycount)) setcategory.append(str(category[i][x]).lower()) else: print("else: " + … -
I can't run the command : python manage.py runserver
I can't run the command 'python manage.py reunserver' on my terminal. I dont know why, here is what the terminal shows me : enter image description here Can please someone help me ? I tried to execute the django dev server but it didn't worked. Normally, it show something like this : enter image description here -
Why are we inheriting here in django?
This is my first post here. I am a beginner in django and I am almost done reading through django for beginners by William S. Vincent. In chapter 8, he goes over the custom user model and creates the following code for the forms needed: from django.contrib.auth.forms import UserCreationForm, UserChangeForm from .models import CustomUser class CustomUserCreationForm(UserCreationForm): class Meta(UserCreationForm): model = CustomUser fields = UserCreationForm.Meta.fields + ("age",) class CustomUserChangeForm(UserChangeForm): class Meta: model = CustomUser fields = UserChangeForm.Meta.fields My question is why are we using class Meta here and why is the first class Meta inheriting from "UserCreationForm", but the second class Meta doesn't. Thanks! -
sort feed by engagement count django
I would like to sort my feed containing image posts by the engagement (number_of_dislikes + number_of_likes), so that the most popular post is on top. But I'm pretty unsure of how to do it. Please have a look at what I have so far and help me out. There are two main problems: one, I have the engagement-post in the html displayed in the same way as the like or dislike, which only reveals the number on click. I tried to change that by just displaying the engagement_count but it only showed the numbers of the posts I´ve clicked on before when the button was still there. How do I display an always counting number of engagement? secondly, i need to sort the feed by that count... thanks a lot. index.html (homepage) {% for post in posts %} <div class="bg-white shadow rounded-md -mx-2 lg:mx-0"> <!-- post header--> <div class="flex justify-between items-center px-4 py-3"> <div class="flex flex-1 items-center space-x-4"> <a href="#"> <div class="bg-gradient-to-tr from-yellow-600 to-pink-600 p-0.5 rounded-full"> <img src="{% static 'assets/images/avatars/user.png' %}" class="bg-gray-200 border border-white rounded-full w-8 h-8"> </div> </a> <span class="block capitalize font-semibold "><a href="/profile/{{ post.id }}">@{{ post.id }} </a></span> </div> <div> <a href="#"> <!-- <i class="icon-feather-more-horizontal text-2xl hover:bg-gray-200 rounded-full … -
Redirect user in django after form submission using JavaScript
Using JS to add some interactivity to the form and now would like to redirect the user to a different url and be able to do it dynamically. Using plain JS as of now, need ideas. Adding sample code below. book.addEventListener('submit', (e) => { e.preventDefault(); const submitButton = document.getElementById('book'); submitButton.disabled = true; submitButton.innerHTML = 'Booking...'; setTimeout(() => { submitButton.innerHTML = `<i class="fa-solid fa-check" style="color: white; text-align: center;"></i>`; }, 1000); // return user to profile page }); Not really sure what to try as I am new to using JavaScript. -
In Django's auth contrib module, how do I validate a token submitted from a reset password form?
I'm using Django 3.1 with its auth contrib module. I have an API-only application, in which I initiate a password reset using the following Django view class ResetPasswordView(SuccessMessageMixin, PasswordResetView): reset_password_template_name = 'templates/users/password_reset.html' email_template_name = 'users/password_reset_email.html' subject_template_name = 'users/password_reset_subject' success_message = "We've emailed you instructions for setting your password, " \ "if an account exists with the email you entered. You should receive them shortly." \ " If you don't receive an email, " \ "please make sure you've entered the address you registered with, and check your spam folder." success_url = reverse_lazy('users-home') @method_decorator(csrf_exempt) def dispatch(self, request, *args, **kwargs): request.csrf_processing_done = True return super().dispatch(request, *args, **kwargs) def post(self, request, *args, **kwargs): email = json.loads(request.body).get('username') try: if User.objects.get(email=email).is_active: form = PasswordResetForm({'email': email}) print("form valid? %s" % form.is_valid()) if form.is_valid(): request = HttpRequest() request.META['SERVER_NAME'] = socket.gethostbyname('localhost') #'127.0.0.1' request.META['SERVER_PORT'] = 8000 # calling save() sends the email # check the form in the source code for the signature and defaults form.save(request=request, use_https=False, from_email="laredotornado@yahoo.com", email_template_name='../templates/users/password_reset_email.html') print("email: %s " % email) return super(ResetPasswordView, self).post(request, *args, **kwargs) except Exception as e: print("\n\nerror ...\n\n") print(e) # this for if the email is not in the db of the system return super(ResetPasswordView, self).post(request, *args, **kwargs) This generates an email … -
How to remove the folder structure generated when building multiple html entry points using Vite.js?
My current vite.config.js looks sorta of like this: export default defineConfig({ plugins: [react()], build: { assetsDir: './', rollupOptions: { input: { main: fileURLToPath(new URL('./src/html/main.html', import.meta.url)), mobile: fileURLToPath(new URL('./src/html/mobile.html', import.meta.url)), config: fileURLToPath(new URL('./src/html/config.html', import.meta.url)), }, output: { dir: 'dist', }, }, }, }); So my project's current folder structure for organization reasons is: src/ |- components |- hooks |- pages `- Config `- index.tsx `- Main `- index.tsx `- Mobile `- index.tsx |- html/ | `- config.html | `- main.html | `- mobile.html My build(dist) folder structure is: dist |- [...bunch of js files] | src/ |- html/ | `- config.html | `- main.html | `- mobile.html My ideal final folder structure goal would be: dist |- [...bunch of js files] |- config.html |- main.html |- mobile.html I know I can just re-structure the project folder structure by putting the HTML files outside the src folder, in the root folder. But I'm aiming at being organized. I know this is possible using Webpack and I couldn't figure out how to do it on Vite.js with HTML files. Any direction or help would be awesome. -
How to same place on page when redirecting to previous page
I was wondering if there is a way in django for when you click back to go to the previous page via a link or in my case an anchored link with in an img, for it to also end up in the same place as you click originally, in my case the image that is clicked in the first place. Page I click image to redirect: </head> <body> <header>{% include 'navbardesktop.html' %}</header> <div class="image-container"> <div class="image-post"> <a href="{% url 'gallery' %}" ><img class="photo-img" src="{{photo.image.url}}" /></a> <h2 class="photo-title">{{photo.image_title}}</h2> <p class="contact"> Interested in purchasing this as a print? Contact me for more information regarding price and sizes. </p> <a href="{% url 'contact' %}" class="btn btn-secondary" type="button" >Contact</a > <a href="{% url 'gallery' %}" class="btn btn-secondary" type="button" >Gallery</a > </div> </div> </body> </html> Page I want to redirect to: <body> <header>{% include 'navbardesktop.html' %}</header> <div class="container-gallery"> <div class="col-md-12" id="gallerygrid1"> <div class="row"> {% for photo in images %} <div class="col-md-4" id="gallerygrid2"> <a href="{% url 'viewimage' photo.slug %}" ><img class="gallery-thumbnail" src="{{photo.image.url}}" style="" /></a> </div> {% empty %} <h3>No Projects...</h3> {% endfor %} </div> </div> </div> </body> </html> -
Django project wait for database ready tests
I am taking a online course about Django. In this courseI am connecting my project with a Postgresql database. For a case that my Django app start before the Postgresql database start, we write a command that delays the app start until Postgresql starts. Here is the command code: from psycopg2 import OperationalError as Psycopg2OpError from django.db.utils import OperationalError from django.core.management.base import BaseCommand class Command(BaseCommand): def handle(self, *args, **options): """ Entrypoint for command """ self.stdout.write('Waiting for database...') db_up = False while db_up is False: try: self.check(databases=['default']) db_up = True except(Psycopg2OpError, OperationalError): self.stdout.write('Database unavailable, waiting for 1 second...') time.sleep(1) self.stdout.write(self.style.SUCCESS('Database available!')) But I didn't understand the test codes that testing if this commands work. Can you explain these codes logic? from unittest.mock import patch from psycopg2 import OperationalError as Psycopg2Error from django.core.management import call_command from django.db.utils import OperationalError from django.test import SimpleTestCase @patch('core.management.commands.wait_for_db.Command.check') class CommandTests(SimpleTestCase): """ Test commands """ def test_wait_for_db_ready(self, patched_check): """ Test waiting for database if database is ready""" patched_check.return_value = True call_command('wait_for_db') patched_check.assert_called_once_with(databases=['default']) @patch('time.sleep') def test_wait_for_db_delay(self, patched_sleep, patched_check): """ Test waiting for database when getting OperationalError""" patched_check.side_effect = [Psycopg2Error] * 2 + \ [OperationalError] * 3 + [True] call_command('wait_for_db') self.assertEqual(patched_check.call_count, 6) patched_check.assert_called_with(databases=['default']) -
Issues installing "pipenv install django" on Mac
So im new to coding and currently tried to learn django i follow this guide from Programming with mosh: https://www.youtube.com/watch?v=rHux0gMZ3Eg&t=783s But when i try the pipenv install django it says: zsh: command not found: pipenv I have the lastest python 3.11.1 but i can't google any anwsers that worked for me. Guys please let me know if you could help me out! I have tried to reinstall pip3 install pipenv. Googled for solutions this is the best one i found but it still didn't solve the problem: https://www.freecodecamp.org/news/pip-command-not-found-mac-and-linux-error-solved/ -
drf isnt accepting data when making a post request with fetch
Im working with static files and making a soundcloud clone using drf for backend with aws as hosting for the files. when i make a post request with the files the backend returns this error django.db.utils.IntegrityError: null value in column "name" of relation "cloudsound_song" violates not-null constraint so i console.logged the data to see if it was returning empty or not, it wasn't. it looks like the backend doesnt want to accept the form data, before this i would get a 500 error. here are my backend files app/views.py class SongViewSet(viewsets.ModelViewSet): queryset = Song.objects.all() content_type ='multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' serializer_class = SongSerializer parser_classes = [parsers.MultiPartParser, parsers.FormParser, parsers.JSONParser, parsers.FileUploadParser] http_method_names = ['get', 'post', 'patch', 'delete'] def perform_create(self, serializer): serializer.save(owner=self.request.user) app/serializers.py class SongSerializer(serializers.HyperlinkedModelSerializer): content_type ='multipart/form-data; boundary=----WebKitFormBoundary7MA4YWxkTrZu0gW' name = serializers.CharField(required=False ) image = serializers.FileField(required=False) audio_file = serializers.FileField(required=False) class Meta : model = Song fields = ('id', 'image', 'name', 'audio_file', 'created_on') def create(self, validated_data): song = Song.objects.create( name=validated_data.get('name'), image=validated_data.get('image'), audio_file=validated_data.get('audio_file'), ) song.save() return song app/models.py class Song(models.Model): name = models.CharField(max_length=100, ) image = models.FileField(upload_to='./media/', default='./media/default-cover-art_tVe9r28.png' ) audio_file = models.FileField(upload_to='./media/') created_on = models.DateTimeField(auto_now_add=True) def __str__(self): return self.name please let me know if this isnt enough. i put null=true to see if it was just my form that … -
Django validation errors not being displayed on webpage but are being read and shown within console
I am creating a user signup page for my website and I am trying to make custom validation fields for my form. I am trying to get the validation errors to be shown on the webpage but I cannot seem to get them to display. I am pretty sure it has something to do with the HTML part but I am new to this and am not sure. Below are the setup of my files forms.py from django import forms class createUser(forms.Form): username = forms.CharField( label='username', max_length=30, widget=forms.TextInput(attrs={'class': "input"}), required=True ) password = forms.CharField( label='password', max_length=30, widget=forms.TextInput(attrs={'class': "input"}), required=True ) password2 = forms.CharField( label='password2', max_length=30, widget=forms.TextInput(attrs={'class': "input"}), required=True ) email = forms.CharField( label='email', max_length=50, widget=forms.TextInput(attrs={'class': "input"}), required=True ) canvas_token = forms.CharField( label='token', widget=forms.TextInput(attrs={'class': "input"}), required=True ) def clean_password(self): password = self.cleaned_data.get('password') if not any(char.isupper() for char in password): raise forms.ValidationError("This password does not contain an uppercase character") return password models.py from django.db import models # Create your models here. class Auth(models.Model): username = models.CharField(max_length=20, blank=False, null=False) password = models.CharField(max_length=150, blank=False, null=False) email_address = models.TextField(max_length=50, blank=False, null=False) canvas_token = models.TextField(blank=False, null=False) def __str__(self): # this will name the object entry within the database to the username that was entered return self.username … -
How to covert django created_at/date_joined time to current user time?
I am getting the user object using user = User.objects.all() context = {'user':user} Passing it to context then using in templates {% for i in user %} <h1>{{i.first_name}}<h1> <h1>{{i.date_joined}}</h1> {% endfor %} Right now i am getting server time but i want to get the time as per the current user country time? How it can be possible? -
Django doesn't find Pillow "Cannot use ImageField because Pillow is not installed." Windows 10 Version 22H2 Build19045
I installing Pillow successfully inside of the venv. but I still get the same Error when starting the server. D:\Commerce>python manage.py runserver django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: auctions.listings.photo: (fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow". System check identified 1 issue (0 silenced). I have Python version 3.11.1 installed. Pillow Version Support in an activated venv I checked for: pip --version pip 22.3.1 from D:\Commerce\venv\Lib\site-packages\pip (python 3.11) The Installation Directory of Django and Pillow are the same as you can see below. And both are updated to the newest version. pip show django Name: Django Version: 4.1.5 Summary: A high-level Python web framework that encourages rapid development and clean, pragmatic design. Home-page: https://www.djangoproject.com/ Author: Django Software Foundation Author-email: foundation@djangoproject.com License: BSD-3-Clause Location: D:\Commerce\venv\Lib\site-packages Requires: asgiref, sqlparse, tzdata Required-by: pip show Pillow Name: Pillow Version: 9.4.0 Summary: Python Imaging Library (Fork) Home-page: https://python-pillow.org Author: Alex Clark (PIL Fork Author) Author-email: aclark@python-pillow.org License: HPND Location: D:\Commerce\venv\Lib\site-packages Requires: Required-by: I tried pip uninstall Pillow pip install Pillow and pip uninstall Pillow python -m pip install Pillow I updated Python, Django, PIP and Pillow. Python via the … -
Django didn't save data to postgre during test case executing
I have webapp, which has a lot of big calculation logic. To stable it and spend less time to regress tests I decided to create some unit test cases on Django. My purpose - don't create new test DB (I use Postgre SQL, is important) for every testcases running and save DB with all test data after test cases finished. I need to have test data for analysis and search bugs. I created custom TestRunner, which inherited on DiscoverRunner with change some parameters: keepdb = True debug_mode = True verbosity = 2 This thing is work, I reuse one DB for all test-cases. My problem is I don't see test data which created during test cases in my test DB. I had some failed testcases or all OK - nothing change. Interesting facts for me: During test cases I have some queries to DB about new test data and these queries returns right result. During test cases I created new objects and sequences in DB are changed as if test data exists in DB. What I do wrong? -
Failed to read dockerfile
I'm trying to dockerize my djangp app with postgres db and I'm having trouble, when run docker-compose, error is: failed to solve: rpc error: code = Unknown desc = failed to solve with frontend dockerfile.v0: failed to read dockerfile: open /var/lib/docker/tmp/buildkit-mount4260694681/Dockerfile: no such file or directory Project structure in screenshot: Dockerfile: FROM python:3 ENV PYTHONUNBUFFERED=1 WORKDIR /app COPY requirements.txt ./ RUN pip install -r requirements.txt COPY . . docker-compose: version: "3.9" services: gunter: restart: always build: . container_name: gunter ports: - "8000:8000" command: python manage.py runserver 0.0.0.0:8080 depends_on: - db db: image: postgres Then: docker-compose run gunter What am I doing wrong? I tried to change directories, but everything seems to be correct, I tried to change the location of the Dockerfile -
Next.JS frontend does not have csrf token which is from Django-Backend
I am super newbie in programming. I am using Django as Backend, Next.JS as Frontend. I have a session login function which works perfect on "runserver"+"localhost:3000" But It is not work on production. I found that there is no cookie on my production mode. which is existing on development mode. below picture is from inspect mode on chrome. like above. there is some data in my development mode. but there is nothing on my production mode. I guess that this makes some errors now. I cannot get data from drf rest api with below code. const instance = axios.create({baseURL: process.env.NODE_ENV === "development" ? "http://127.0.0.1:8000/api/v1/" : "https://mysite/api/v1/",withCredentials: true,xsrfHeaderName: "X-CSRFTOKEN",xsrfCookieName: "csrftoken", }); export const getMe = () => instance .get( `users/me`, { headers: { "X-CSRFToken": Cookie.get("csrftoken") || "", }, } ) .then((response) => response.data); above code gives me "error 500", which should give me User Data. I think that is because of my csrftoken is missing at all in my frontend. My Backend Django settings.py like this. if DEBUG: CSRF_TRUSTED_ORIGINS = [ "http://127.0.0.1:3000", "http://localhost:3000", ] else: CSRF_TRUSTED_ORIGINS = [ “myfront.com” ] CORS_ORIGIN_ALLOW_ALL = True CORS_ALLOW_CREDENTIALS = True CSRF_COOKIE_SECURE = False SESSION_COOKIE_SECURE = False Q. How can I fix my getMe function work …