Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django: I want to track from which url a request was made?
in the TestQuestionList class, the get function must receive an id to return id, I thought that I could do this with the help of request.get_full_path()example on the bottom class TestQuestionList(APIView): def get(self, request): obj = Test.objects.get(id = request.get_full_path()) romms = TestQuestionBlok.objects.filter(id__in=obj.questions) serializer = TestQuestionSerializers(romms, many=True) return Response(serializer.data) but request.get_full_path() instead of /tests/api/ (where the request was made from) returned /api/question/ why? This is part of the code from where the request was made useEffect(() => { axios({ method: 'GET', url: 'http://127.0.0.1:8000/api/questions/', }).then(response => { setAllQuestions(response.data) }) }, []) Thanks in advance for your replies -
Django modifying login view has no effect
Long story short: No matter what I do with the login view, it won't change the behavior of the login form, I can delete my views altogether (and urls) and it still works, so it must be picking it up from somewhere else. From where and how do I change that? Long version: I was following a tutorial to implement login, logout and registration with django built in features, it is actually working fine but when I was trying to modify the login view I just realized that no matter what I tried to do in the view, it wouldn't change the behaviour (I was trying to redirect to a different page if the user was already logged, for instance). I started playing around to see what I could change and how it would reflect, even adding prints, but nothing happened, until I decided to try replacing all the code inside the login view function with pass, AND IT STILL WORKED! It happens the same with the logout view, but it doesn't with the register view. I don't understand what's going on. I tried to find something online, but I couldn't find anything related to this exact issue. This is … -
Accept URL as parameter in path (special characters)
I have a view and a path where I'd like to accept a str parameter and pass it to my make_request view. The problem I'm having is the strings I'd like to accept are URLs. When I pass a string like 'https://example.com/' I get an error saying Page not found (404) as there are special characters. urls.py from django.urls import path from . import views urlpatterns = [ path('<str:url>', views.make_request, name='make_request'), ] views.py def make_request(url): print(url) -
Django ORM filtering using expression against multiple fields
I am trying to use Django ORM filter to retrieve Announcement records with announcement_dates that are later than the current date - "expire_in_days" field - i.e., retrieve announcements that have not yet expired. Here is the SQL representation of what I am trying to do with ORM: select * from announcement where message_date > current_date - expire_in_days; I should be able to retrieve all records and filter them externally, but I am trying to learn how to do this with Django. Here is my model class Announcement(models.Model): message = models.TextField("announcement message") message_date = models.DateField("Announcement date") expire_in_days = models.PositiveIntegerField("Number of days before announcement expires") def __str__(self) -> str: return '(message: %s, message_date: %s, expire_in_days: %s)' % (self.message, self.message_date, self.expire_in_days) Here is what I tried but it did not work: In [1]: from events.models import Announcement In [2]: from datetime import date, timedelta In [3]: from django.db.models import F In [4]: date.today() Out[4]: datetime.date(2022, 5, 29) In [5]: date.today() - timedelta(days=2) Out[5]: datetime.date(2022, 5, 27) In [6]: Announcement.objects.all() Out[6]: <QuerySet [<Announcement: (message: There is a surprise coming up!, message_date: 2022-05-27, expire_in_days: 1)>]>" In [7]: Announcement.objects.filter(message_date__gt = (date.today() - timedelta(days = F('expire_in_days')))) --------------------------------------------------------------------------- TypeError Traceback (most recent call last) Input In [7], in … -
Django: converting csv file to ofx doesn't work when i put the source = request.FILES
I need some help please from 2 days am trying to convert a csv file of an ofx file , i have suceeded to do that but the thing just work when i specify a file and not something general what i mean : this code work perfect : def UploadFile(request): if request.method == 'POST': form = BlogForm(request.POST,request.FILES) if form.is_valid(): form.save() ofx = OFX(mapping) records = read_csv("/home/mariana/django_project/media/test.csv", has_header=True) groups = ofx.gen_groups(records) trxns = ofx.gen_trxns(groups) cleaned_trxns = ofx.clean_trxns(trxns) data = utils.gen_data(cleaned_trxns) content = it.chain([ofx.header(), ofx.gen_body(data), ofx.footer()]) with open ("/home/mariana/django_project/media/testt.ofx", 'w') as f: res = write(f, IterStringIO(content)) print("sucess") else: form = BlogForm() context = { 'form':form, } return render(request, 'pages/Upload.html', context) this is my models.py : class Blog(models.Model): csv_file = models.FileField(null = True, upload_to='files_csv') filename = models.CharField(max_length=20, null = True) urlpatterns = [ ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) def save(self, *args, **kwargs): super(Blog, self).save(*args, **kwargs) the thing doesn't work if i go that in general what i mean is if i modify : records = read_csv("/home/mariana/django_project/media/test.csv", has_header=True) ------> records = read_csv(request.FILES, has_header=True) ---> it doesn't work and give me an error(expected str, bytes or os.PathLike object, not MultiValueDict) , why this !!! why when i put request.FILES doesn't work -
POST request is not working after django website deployment through Microsoft IIS
I have successfully deployed my django web application through Microsoft IIS FastCGI. So look wise my website seems to be fine. But after submitting the form on the website, i's showing nothing. It's like the submit button is not posting the form at all. But the same thing is running fine on the local server (not with the IIS deployed one). In short, after deployment I am assuming that the index.html seems to be working fine but veiws.py or my JavaScript is not. I am not able to find find any solution for this. Any kind of help would be much appreciated. For the reference, the main web.config is below. web.config <configuration> <system.webServer> <handlers> <add name="Python FastCGI" path="*" verb="*" modules="FastCgiModule" scriptProcessor="C:\Python\python.exe|C:\Python\Lib\site-packages\wfastcgi.py" resourceType="Unspecified" requireAccess="Script" /> </handlers> </system.webServer> <appSettings> <!-- Required settings --> <add key="WSGI_HANDLER" value="my_app.wsgi_app()" /> <add key="PYTHONPATH" value="C:\MyApp" /> <add key="DJANGO_SETTINGS_MODULE" value="my_app.settings" /> <!-- Optional settings --> <add key="WSGI_LOG" value="C:\Logs\my_app.log" /> <add key="WSGI_RESTART_FILE_REGEX" value=".*((\.py)|(\.config))$" /> <add key="APPINSIGHTS_INSTRUMENTATIONKEY" value="__instrumentation_key__" /> <add key="WSGI_PTVSD_SECRET" value="__secret_code__" /> <add key="WSGI_PTVSD_ADDRESS" value="ipaddress:port" /> </appSettings> </configuration> -
How i can to change date of Django project
I implement project using Django and i have a some module calculate with current date and time. I want to test this module with change local time method. I tried to change computer date and time but not change in Django. i want to know how to change current date and time in Django. -
How can I hide current uploaded image location path in django?
I have made a feature in Django where every user can change his platform's logo. The image selected by the user will be saved in static/{user.customer.public_id}/platformLogo/image.jpg. When i save the changes, i can see the uploaded image's path which also contain unique public ID which i don't want user to see for security purpose. Can anyone help me to hide this image path in Django for user? Attaching my code part here below. Here we can see the image path which has unique ID in path, which we need to hide Here is the uploaded image path directory Here is my models.py from sre_constants import CATEGORY from unicodedata import category from attr import fields from django.db import models from datetime import date from django.contrib.auth.models import User import uuid def upload_path(instance, filename): filename = str(date.today()) name = instance.user.customer.public_id.hex return f'{name}/platformLogo/{filename}.jpg' class Customer(models.Model): user = models.OneToOneField(User, null=True, blank =True, on_delete=models.CASCADE) public_id = models.UUIDField(primary_key=True, default = uuid.uuid4, editable=False) date_created = models.DateTimeField(auto_now_add=True, null=True) name = models.CharField(max_length=200, null=True) otp_code = models.CharField(max_length=6, null=True) first_name = models.CharField(max_length=200, null=True) last_name = models.CharField(max_length=200, null=True) email = models.CharField(max_length=200, unique=True) phone = models.CharField(max_length=200, null=True) profile_pic= models.ImageField(upload_to=upload_path, default='logo.png', null=True, blank=False,) def __str__(self): return self.name Here is my views.py @login_required(login_url='login') def accountSetting(request): customer … -
django_filters filter_overrides not applying to CharFields with choices
I have declared a django_filters.FilterSet with a Meta class where I would like to use filter_overrides in order to customise some of the filters. I am using code very similar to the example in the official documentation: class AccommodationFilter(django_filters.FilterSet): class Meta: model = AccommodationOffer fields = ['numberOfPeople', 'petsAllowed', 'typeOfResidence', 'startDateAccommodation' ] filter_overrides = { models.BooleanField: { 'filter_class': django_filters.BooleanFilter, 'extra': lambda f: { 'widget': forms.CheckboxInput(attrs={'class':'form-control', 'value' : 'true'}), }, }, models.CharField: { 'filter_class': django_filters.ChoiceFilter, 'extra': lambda f: { 'widget': forms.Select(attrs={'class':'form-control'}), }, }, } The BooleanFields are showing up as expected, however no matter what I try, the CharFields (which have choices set) do not render with the class="form-control" attribute. -
it doesn't decrease when i delete a row in heroku postgresql,why? (Django)
I have a django application running on heroku. and it is using free postgresql in this application.but even if I delete 30 40 maybe more lines from the admin panel, the number of rows (lines) in the heroku dashboard does not decrease.Even if I delete 20 30 rows (lines) at once, it never decreases, it increases constantly.It never goes below 877. but it keeps increasing when i add something new. -
Django CBV inheritance not working as expected
I use these two classes to get the context data and check permissions respectively: class RestaurantView(View): def get_context_data(self): ctx = {'restaurant': get_object_or_404(Restaurant, slug=self.kwargs['slug'])} return ctx class ManageRestaurantMixin(LoginRequiredMixin, UserPassesTestMixin, RestaurantView): def test_func(self): ctx = super().get_context_data() return ctx['restaurant'].owner == self.request.user Now the first one is working, so when i don't need permission i get the expected behavior, for example with this DetailView: class Info(RestaurantView, DetailView): model = Restaurant context_object_name = 'restaurant' template_name = 'restaurant/info.html' But then if inherit from ManageRestaurantMixin the permissions are checked as expected, but the context object is not working and the template displays an empty form: class EditInfo(ManageRestaurantMixin, UpdateView): model = Restaurant context_object_name = 'restaurant' template_name = 'restaurant/edit_info.html' fields = ['name', 'address', 'logo'] success_url = '/account/myrestaurants' I get that the context gets overwritten, but i don't get how. How can i solve this? Is there a better way to handle this kind of situations? -
ID Card Generation in Django
I am using Django my own Admin panel but I want to create employee card can you help me with view.py and template code? this is My Urls.py path('showcustomer',views.ShowCustomer) this is the view.py def ShowCustomer(request): qrcode_img=qrcode.make('Wellcom') canvas=Image.new("RGB", (290,290),'White') Draw=ImageDraw.Draw(canvas) canvas.paste(qrcode_img) fname=f'qr_code-(self.name)'+'.png' buffer=BytesIO() canvas.save(buffer,'PNG') img=qrcode_img.save(fname, File(buffer), save=False) canvas.close() return render(request, 'ShowCustomer.html',{'img':img}) and this is template <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <body> <h1>Show Customer page</h1> {{ img }} <img src={{img}} style="width: 20%; height: 20%;"> </body> `enter code here`</html> -
Use two managers in one model
I have a Place model with subclasses Restaurant and Bar. I attached InheritanceManager from django-model-utils to Place to use the select_subclasses() method to get instances of the subclass. from model_utils.managers import InheritanceManager class Place(models.Model): # ... objects = InheritanceManager() class Restaurant(Place): # ... class Bar(Place): # ... Everything worked fine. But now I want to set the order of the model Place with django-ordered-model. This package also uses a manager: ... objects = OrderedModelManager() ... How to combine them? -
Django Framework Rest match calendar users with current user
I am doing an exercise where the goal it's to match my current calendar with other users. To do this, I created a UserProfile App and Schedule App. Each user has a profile that can have multiple intervals. Considering my current calendar: { "count": 1, "next": null, "previous": null, "results": [ { "id": 3, "user": { "id": 3, "username": "john.doe", "first_name": "John", "last_name": "Doe" }, "calendar": [ { "id": 1, "mon": true, "tue": true, "wed": true, "thu": true, "fri": true, "sat": true, "sun": true, "start_date": "09:30", "end_date": "12:20" }, { "id": 2, "mon": true, "tue": true, "wed": true, "thu": true, "fri": true, "sat": true, "sun": true, "start_date": "14:00", "end_date": "23:00" } ] } ]} When I am doing a call to the endpoint /api/search/users it returns all User Profiles with info from each user. example: { "count": 99, "next": "http://localhost:8000/api/search/users?page=2", "previous": null, "results": [ { "id": 1, "user": { "id": 1, "username": "john.bender.99", "first_name": "John", "last_name": "Bender" }, "calendar": [ { "id": 2, "mon": true, "tue": true, "wed": true, "thu": false, "fri": true, "sat": false, "sun": false, "start_date": "09:30", "end_date": "12:20" }, { "id": 55, "mon": false, "tue": true, "wed": true, "thu": false, "fri": true, "sat": false, "sun": false, "start_date": … -
why django can not create a table after deleting the table and the migration files of the app?
I am working with Django v4.* which I connected it to Postgres DB on the localhost, I have created my model (Article) then makemigration then migrate then I have changed the model by adding extra field, as a result it didn't take effect so I have deleted the table and all the migrations files in articles/migrations folder apart of the __init__.py file, then I did makemigrations then migrate it create a new file 0001_initial.py but its not creating a new table into the DB? I am wandering why Django unable to create the table back again? -
Overlapping Checking Rule DJango validation
I am trying to overlapping validation check but i could not do it can anyone help me. record=[] if count > 1: for i in range(count): start_run = self.data.get(f'runningdefinition_set-{i}-start_run',[]) end_run = self.data.get(f'runningdefinition_set-{i}-end_run',[]) application_run =self.data.getlist(f'runningdefinition_set-{i}-application_run') for overlap_check in (i, start_run, end_run, application_run): if overlap_check not in record: record.append(overlap_check) else: raise ValidationError( "overlapping not allowed" ) -
Waypoints infinite for loading chat messages when scrolled to top of scrollable element
I'm trying to load chat messages when the user scrolls to the top of the div (the div is scrollable, so the context isn't the window, it's the div). Also when the page loads the div is automatically scrolled to the bottom. I'm doing this in django and when running this code the waypoint is triggered when the user is scrolled to the bottom, but the div that should be triggering it (id=trigger-load) is above the viewport. I've tried adding a set timeout for the initialization of infinite_chat but that also didn't work. This is the code: class ChatDetail(LoginRequiredMixin, generic.ListView): login_url = reverse_lazy('login') model = Message paginate_by = 20 context_object_name = 'messages' template_name = 'index.html' Html: ``` <div class="overflow-y-scroll px-5 pt-5 flex-1 infinite-container-chat" id="chat-content"> {% if page_obj.has_next %} {% include 'partials/common/loader.html' %} {% endif %} <div class="" id="trigger-load"></div> {% include 'partials/friend_hidden_message.html' %} {% include 'partials/user_hidden_message.html' %} {% for message in messages reversed %} {% if forloop.first %} <div class="infinite-item"> {% if user.id == message.user.id %} {% include 'partials/user_message.html' %} {% else %} {% include 'partials/friend_message.html' %} {% endif %} </div> {% else %} <div class="infinite-item"> {% if user.id == message.user.id %} {% include 'partials/user_message.html' %} {% else %} {% include … -
DJango QuerySet filter query using a model attribute
Let's say I have a model Example class Example start_time = models.DateTimeField(db_index=True) duration = models.IntegerField(default=0) And a QuerySet class class ExampleQuerySet def live_objects(): self.active().filter(start_time__gte=get_minutes_before(get_utc_now(),5), start_time__lte=get_minutes_after(get_utc_now(), self.duration)) The objective of the live_objects() method is to return those objects which have their current time > start time and current time < start time + duration of the object But this above query is failing with the error that self object doesn't have duration attribute How do I go about writing a query where I can filter out objects that are currently live ? -
How to put up new content some part of a div is pressed
The title is probably confusing but there isnt a better way to ask the question. Im making a job searching website using django. Im not really experienced in the front end. I want a list of job offers to be showing and when one of them is clicked I want a enlarged version with additional info(Apply button, detailed description) to appear of the specific job offer clicked. Sort of like how it linkedin does it. This is the code I am using for listing out all of the jobs. I know I will probably need a dynamic url but from there I dont know how to implement it on the front end. Comps is just a list of all of the objects in a Model for Companies. {% for comp in comps %} <div class="CompList"> <span>{{comp.jtitle}}</span> <h2>{{comp.name}}</h2> <h3>{{comp.country}}, {{comp.city}}</h3> </div> {% endfor %} -
Ldap authentification with django
I'm trying to set up ldap connexion with django but it won't work. So, I tried this to test if it's working and it's returns <(97, [], 1, [])>. import ldap server = 'ldap://Server' user_dn = 'Test' password = 'Formation123' con = ldap.initialize(server) con.simple_bind_s(user_dn, password) But when I try to connect on the admin page of django it doesn't work. Here's my config and my directory.enter image description here Thank you for your help. enter image description here -
Django: Why am I getting a 400 bad request error?
I am developing a web application on django + react And I needed to make a request in which I pass a list with ids, but I have a '"POST /api/questions/ HTTP/1.1" 400 39' views.py questions = [] class TestQuestionList(APIView): def get(self, request): global questions romms = TestQuestionBlok.objects.filter(id__in=questions) serializer = TestQuestionSerializers(romms, many=True) return Response(serializer.data) def post(self, request, format=None): global questions serializer1 = TestQuestionSerializers(data=request.data) if serializer1.is_valid(): print(serializer1.data['answers']) return Response(serializer1.data, status=status.HTTP_200_OK) return Response(serializer1.errors, status=status.HTTP_400_BAD_REQUEST) serializers.py class TestQuestionSerializers(serializers.ModelSerializer): class Meta: model = TestQuestionBlok fields = ('answers', ) Testpage.jsx import React, {useState, useEffect} from 'react'; import axios from "axios"; import { useParams } from "react-router-dom"; import "../styles/Testpage.css" function Testpage() { axios.defaults.xsrfCookieName = 'csrftoken' axios.defaults.xsrfHeaderName = "X-CSRFTOKEN" useEffect(() => { axios({ method: 'POST', url: 'http://127.0.0.1:8000/api/questions/', data: { question: [1, 3] } }) }, []) return ( <div> a </div> ); } export default Testpage; How can I fix this ? -
How do i get my like button to show up on my blog posts?
I got some problems getting my like button to show am not sure what to enter into the post_detail.html to get the like button to show up on the blog posts. i tried {% include and putting the entire code from main.html in to the post_detail.html etc But all i get is errors what is the correct way to get the code from main.html to show up on the blog post post_detail.html ? would really appreciate some help cause i been stuck on this for very long and cant figure it out how to get the like button to show up on blog posts. newsapp folder views.py from django.shortcuts import render, get_object_or_404, redirect from django.views import generic from .models import Post, Like from .forms import CommentForm class PostList(generic.ListView): queryset = Post.objects.filter(status=1).order_by('-created_on') template_name = 'index.html' paginate_by = 6 def post_view(request): qs = Post.objects.all() user = request.user context = { 'qs': qs, 'user': user, } return render(request, 'newsapp/main.html', context) def like_post(request): user = request.user if request.method == 'POST': post_id = request.POST.get('post_id') post_obj = Post.objects.get(id=post_id) if user in post_obj.liked.all(): post_obj.liked.remove(user) else: post_obj.liked.add(user) like, created = Like.objects.get_or_create(user=user, post_id=post_id) if not created: if like.value == 'Like': like.value = 'Unlike' else: like.value = 'Like' like.save() return … -
Django filebrowser functions
I am writing a code for a customer who needs a filemanager with version control for every file and hidden files based on logged in user. I was wondering if the filebrowser can be used and extended or would it be much faster if I make my own code with my own views and templates? Thanks -
Django Parsing filtered queryset into json without loop
I have lastSpecifiedHours variable that filters last 48 hours actions. I need to return that as JSON as plate, time, longitude, latitude. Built as below but I used loop for that. I wonder is there anyway making same return without loop? def lastpoint(request): if request.method == "POST": #post vehicle plate as vplate plate = request.POST.get("vplate") #hours can be got with post if necessary hours = 48 vehicle = Vehicle.objects.get(plate = plate) lastSpecifiedHours = datetime.now(tz=timezone.utc) - timedelta(hours=hours) resultJson = [] #Cached result for optimization results= NavigationRecord.objects.filter(vehicle=vehicle, datetime__gte=lastSpecifiedHours) for result in results: resultJson.append({"Plate": vehicle.plate, "Date Time": result.datetime, "Longitude": result.longitude, "Latitude": result.latitude}) return JsonResponse(resultJson, safe=False) -
How to get value from foreign key and next foreign key?
We need to get cost from Reward, but we must use TwitchUser it`s my models.py class TwitchUser(models.Model): username = models.CharField(max_length=250, verbose_name='username', null=True) refresh_token = models.CharField(max_length=300, verbose_name='refresh_token', null=True) id = models.CharField(max_length=150 ,primary_key=True) login = models.CharField(max_length=250, null=True) avatar = models.CharField(max_length=400, verbose_name='avatar') params = models.ForeignKey('Parametrs', on_delete=models.CASCADE) class Parametrs(models.Model): skip = models.ForeignKey('Reward', on_delete=CASCADE) chat_bot = models.BooleanField(default=False) class Reward(models.Model): id = models.CharField(primary_key=True, max_length=50) title = models.CharField(null=True, max_length=50) cost = models.IntegerField(default=0) background_color = models.CharField(max_length=30, verbose_name='color', default='FFD600') cooldown = models.IntegerField(default=30) type = models.CharField(max_length=100, )