Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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, ) -
Cannot connect to redis://localhost:6379// while using docker-compose
This may be a simple question but I've just started to learn docker and I am making my first project with it. I have a django project using celery and Redis. I've made Dockerfile and docker-compose.yml: Dockerfile FROM python:3.8 RUN apt-get update && apt-get upgrade -y && apt-get autoremove && apt-get autoclean RUN apt-get install -y \ libffi-dev \ libssl-dev \ libxml2-dev \ libxslt-dev \ libjpeg-dev \ libfreetype6-dev \ zlib1g-dev \ net-tools ARG PROJECT=djangoproject ARG PROJECT_DIR=/var/www/${PROJECT} RUN mkdir -p $PROJECT_DIR WORKDIR $PROJECT_DIR COPY requirements.txt . RUN pip install -r requirements.txt EXPOSE 8000 STOPSIGNAL SIGINT CMD ["python", "manage.py", "runserver", "127.0.0.1:8000"] Docker-compose.yml: version: "3" services: redis: image: redis:latest container_name: rd01 ports: - '6379:6379' restart: always expose: - '6379' django: container_name: django_server build: context: . dockerfile: Dockerfile image: docker_tutorial_django volumes: - ./parser_folder:/var/www/djangoproject ports: - "8000:8000" links: - redis depends_on: - celery celery: build: . command: celery -A Parsing worker -B --loglevel=DEBUG volumes: - ./parser_folder:/var/www/djangoproject links: - redis When I execute docker-compose up I get an error consumer: Cannot connect to redis://localhost:6379//: Error 99 connecting to localhost:6379. Cannot assign requested address.. I tried to change ports and write the command for Redis in docker-compose.yml but it won't working. Help me to figure it out … -
Watch star rating in page and rate in the other
I am new to Django and I'm using Star-Rating. I would like to know if there is a possibility a user can see the ratings on one page without the opting to rate and on another page, the same user can rate -
Invalid HTTP_HOST header: Django deployment
I have a very strange problem. I published my site with NGİNX, then I added a subdomain. Invalid HTTP_HOST header: 'm.bakuklinik.shop'. You may need to add 'm.bakuklinik.shop' to ALLOWED_HOSTS. I get this error. I refreshed the setinngs.py file on the server and did it as follows. ALLOWED_HOSTS = ['159.223.235.76', 'www.bakuklinik.shop', 'bakuklinik.shop', 'm.bakuklinik.shop',] But again I got the same error. Then I deleted the www.bakuklinik.shop url to see if it would work. It shouldn't work, but it does. even when i delete settings.py file it works. I guess I need to make changes elsewhere. I would be glad if you help. -
Bad Request Python Django on User Registration and Email Confirmation
So I implemented by User Registration Class, and it was working fine and then tried sending out Email Confirmation through Send Grid which also worked fine. Then I added some conditions. Basically, the workflow is: User signs up by sending relevant info. The 'is_active' field is set to False initially Then a PatientSerializer object is created of the request, which is saved in the database IF valid. Created a token through libraries to verify email address Created a TokenSerializer object by passing the ID in the request and the token created in (3) and saved it if it's valid Under the same if block, a message was made through the SendGrid API and was sent to the user Then there's just except and else statements to catch errors My models.py file: from django.db import models from django.contrib.auth.models import User class Token(models.Model): user = models.ForeignKey( User, on_delete=models.CASCADE, related_name='token') token = models.CharField(max_length=256, blank=True, null=True) My serializer.py file: from pyexpat import model from rest_framework import serializers from django.contrib.auth.models import User from rest_framework.validators import UniqueValidator from rest_framework_jwt.settings import api_settings from .models import Token class TokenSerializer(serializers.ModelSerializer): class Meta: model = Token fields = ('user', 'token',) class PatientSerializer(serializers.ModelSerializer): token = serializers.SerializerMethodField() email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] …