Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
What should i do to be able to see what i posted in a category?
When i post some json that contains category like this: [ { "id": 152, "image": "https://a", "description": "J t", "price": "USD 8.70", "buy": "https:// 6d7", "category": 1 }, { "id": 153, "image": "https://", "description": "elf", "price": "65", "buy": "https://s.c D", "category": 1 } ] in templates i do not see them. image html: {% load static %} <!DOCTYPE html> <html> <head> <link rel="stylesheet" href="{% static 'main.css' %}"> <div class="header"> <img src="static/logo.png"> </div> </head> <body style="background-color: #56454F;"> <div class="grid"> {% for i in p%} <div class='card'> <img src="{{i.image}}"></img> <p id="id">{{i.description}}</p> <a href="{{i.buy}}" target='_blank' rel='noopener noreferrer'> <button><span class="price"> ${{i.price}}</span> buy</button> </a> </div> {%endfor%} </div> <div class="footer"> <h1 >&copy All rights reserved</h1> </div> </body> </html> models: from django.db import models class category(models.Model): name=models.CharField(max_length=255, db_index=True) def __str__(self): return self.name class product(models.Model): category = models.ForeignKey(category, related_name='products',on_delete=models.CASCADE) image=models.CharField(max_length=500) description=models.CharField(max_length=500) price=models.CharField(max_length=50) buy=models.CharField(max_length=100) views: class productviewset(viewsets.ModelViewSet): queryset=product.objects.all() serializer_class = productSerializer def create(self, request): serialized = productSerializer(data=request.data, many=True) if serialized.is_valid(): serialized.save() return Response(serialized.data, status=status.HTTP_201_CREATED) return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) @action (detail=False , methods=['post']) def delete(self,request): product.objects.all().delete() return Response('success') def home(request): return render(request,'home.html',{'p':category.objects.all()}) def foods(request): return render(request,'foods.html',{'p':category.objects.all()}) I do not know what should i write in {'p':category.objects.all()} to be able to put some data from a specific category to that html code. … -
TypeError: __init__() got an unexpected keyword argument 'file'
I'm using Django to develop a platform where users can upload files. This function was working fine for months with no issues, but for some reason now I get this error when trying to upload a file: Traceback: Traceback (most recent call last): File "/home/me/.local/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/home/me/.local/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/me/project/app/views.py", line 314, in invoke_local instance = SingleEndForm(file=request.FILES['file']) Exception Type: TypeError at /invoke_local/ Exception Value: __init__() got an unexpected keyword argument 'file' My model: class SingleEnd(models.Model): file = models.FileField(upload_to="documents/") email = models.CharField(max_length=100) def __str__(self): return self.email My form: class SingleEndForm(forms.ModelForm): class Meta: # shows which model to use from models.py model = SingleEnd # fields = '__all__' fields = ["file", "email"] labels = { "file": "input your fasta/fastq file (min 3 sequences)", "email": "input your email to get a notification for your results in a timely manner", } widgets = { "email": forms.EmailInput(attrs={"class": "form-control"}), "file": forms.FileInput(attrs={"class": "form-control"}), } My view: def invoke_local(request): # path to save inputs media_path = "/home/me/project/media/documents/" # path to save outputs result_path = "/home/me/project/media/results" if request.method == "POST": # use the form to upload form info (post) and files form = SingleEndForm(request.POST, … -
Django ElasticSearch dsl drf returning duplicate search result
I have search based api views, when I search something, it return value, but return the duplicate value with that term. in my database, there is no duplicate data, even in elasticsearch build. This is my API views: from django_elasticsearch_dsl_drf.viewsets import DocumentViewSet class ExampleAPIView(DocumentViewSet): document = ExampleDocument serializer_class = ExampleSerializer filter_backends = [ MultiMatchSearchFilterBackend ] multi_match_options = { 'type': 'phrase_prefix', } multi_match_search_fields = { 'title': 'title', } I am not getting why the search result returns duplicate data? Can anyone help me to fix this? -
How to create a map of the floors that the user could reserve?
I came up with a space management application for each floor and building. I would like it to be a web application. After logging in, the user could select the building, floor and the floor map should be displayed. By pressing on a room, he could reserve it. How could I implement this "map with desks to reserve" in Django or in Angular or maybe in something else it would be easier? I found only solutions with using google maps, that is not what I am looking for. -
Concerns regarding DDoS-like abuse of Django user registration POST requests
I am working on an online shopping mall-esque app with some of my friends. I am in charge of the server-side but I am not really a well-versed backend engineer. Hence, I pivoted toward using DRF for simplicity's sake. However, what caught my eye was that someone could possibly run a script that just repeats POST requests with a valid format. So far, I haven't managed to think of a way to impose custom permissions on this action because people who do not yet have an account have no way of authenticating themselves. Any help on this matter (or built-in functionality that renders this concern moot) would be much appreciated. Thank you! -
SMTPAuthenticationError when sending gmail
I am having this error: smtplib.SMTPAuthenticationError: (535, b'5.7.8 Username and Password not accepted. Learn more at\n5.7.8 https://support.google.com/mail/?p=BadCredentials ij28-20020a170902ab5c00b00163efcd50bdsm1197936plb.94 - gsmtp') when I try to send a gmail in my registration app EMAIL_USE_TLS = True EMAIL_HOST = 'smtp.gmail.com' EMAIL_HOST_USER = 'repository0612@gmail.com' EMAIL_HOST_PASSWORD = '****************' EMAIL_PORT = 587 I read in some other related forums that you just have to turn on the less secure apps in your google account settings but google already disabled that particular setting. I also tried turning off the 2-way authentication and my EMAIL_HOST_USER and EMAIL_HOST_PASSWORD are as the same as my email and password. What else should I do to solve this problem? -
Calculate Balance amount for each currency from a model - Django
I want to calculate Balance for each currency based on deposit and withdrawal. in transaction_type 'd'=deposited amount and 'w'=withdrawn amount I want to calculate Balance for each currency based on deposit and withdrawal. in transaction_type 'd'=deposited amount and 'w'=withdrawn amount. Model Code: class Transactions(models.Model): transaction_currency=models.IntegerField(max_length=50) transaction_amount=models.FloatField() transaction_date= models.DateField(auto_now_add=False) transaction_description=models.TextField() transaction_type=models.CharField(max_length=5) View Function: def Available_Amount(request): available_amont = (how to calculate available amount for each currency?) -
Embed PDF file from download(ed) document
I used to ember pdf files with this simple code: <iframe src="file.pdf" style="width: 100%;height: 100%;border: none;"></iframe> which works perfectly for me. The file should be of course on the server, but is there any similar when I don't have direct "static" access to the file, only a link which serves the file as attachment like this: #django download = file(document.path, 'r') response = HttpResponse(download.read()) response['Content-Disposition'] = 'attachment; filename=' + \ document.get_clean_name() . Is it somehow doable if the file is served as attachment, and has a similar access link: http://sth.com/download_document/2022/ ? -
What should i write in "category": to create a post that belongs to a specific category like foods?
Since i created 2 categories in the admin panel like this: image but when i want to post this json it gives my this error: [ { "category": [ "Incorrect type. Expected pk value, received str." ] }, { "category": [ "Incorrect type. Expected pk value, received str." ] } ] json: [ { "image": "https://a ", "description": "J t", "price": "USD 8.70", "buy": "https:// 6d7", "category": "foods" }, { "image": "https:// ", "description": " elf", "price": " 65", "buy": "https://s.c D", "category": "foods" } ] image What should i write in "category": to create a post that belongs to a specific category like foods? models: class category(models.Model): name=models.CharField(max_length=255, db_index=True) def __str__(self): return self.name class product(models.Model): category = models.ForeignKey(category, related_name='products',on_delete=models.CASCADE) image=models.CharField(max_length=500) description=models.CharField(max_length=500) price=models.CharField(max_length=50) buy=models.CharField(max_length=100) views: class productviewset(viewsets.ModelViewSet): queryset=product.objects.all() serializer_class = productSerializer def create(self, request): serialized = productSerializer(data=request.data, many=True) if serialized.is_valid(): serialized.save() return Response(serialized.data, status=status.HTTP_201_CREATED) return Response(serialized._errors, status=status.HTTP_400_BAD_REQUEST) @action (detail=False , methods=['post']) def delete(self,request): product.objects.all().delete() return Response('success') def home(request): return render(request,'home.html',{'p':category.objects.all()}) def foods(request): return render(request,'foods.html',{'p':category.objects.all()}) -
Existing data can not be edited in django models
After saving the filed , i want to make the field non editable, how i can do that. end_run = models.PositiveIntegerField( null=True, blank=True, help_text=_("Can be enter value Onece") -
AttributeError: module 'dashboard.views' has no attribute 'NotesDetialView'. Did you mean: 'NotesDetailView'?
I got error that says "AttributeError: module 'dashboard.views' has no attribute 'NotesDetialView'. Did you mean: 'NotesDetailView'?" urls.py from unicodedata import name from django.urls import path from . import views urlpatterns = [ path('',views.home,name="home"), path('notes',views.notes,name="notes"), path('delete_note/<int:pk>',views.delete_note,name="delete-note"), path('notes_detail/<int:pk>',views.NotesDetialView.as_view(),name="notes-detail"), ] here i got error from this line path('notes_detail/int:pk',views.NotesDetialView.as_view(),name="notes-detail"), views.py from email import message from multiprocessing import context from pyexpat.errors import messages from django.shortcuts import redirect, render from . forms import * from django.contrib import messages from django.contrib.messages import constants from django.contrib import admin # Add this import from django.contrib.auth import views from django.views import generic # Create your views here. def home(request): return render(request,'dashboard/home.html') def notes(request): if request.method == "POST": form = NotesForm(request.POST) if form.is_valid(): notes = Notes(user=request.user,title=request.POST['title'],description=request.POST['description']) notes.save() messages.success(request,f"Notes Added from {request.user.username} Sucessfully!") else: form = NotesForm() notes = Notes.objects.filter(user=request.user) context = {'notes':notes,'form':form} return render(request,'dashboard/notes.html',context) def delete_note(request,pk=None): Notes.objects.get(id=pk).delete() return redirect("notes") class NotesDetailView(generic.DetailView): model = Notes -
Django media folder vs Flask Database
what consume bigger space in the C: directory. Images from django in the media folder or flask's files in the database that has been add like this: file = Files(file=file.read())? -
I don't understand what the error is. django ajax pagination
I'm trying to do django pagination using ajax, but there is a problem. The problem is that when I click on a page, elements on that page are cleared, but others are not added. Initially everything is fine, I start clicking on pages and all the content disappears. I don't understand why (I'm not good with js), can anyone help. Code views.py class ReviewsView(ListView): model = Review template_name = 'reviews.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['reviews'] = Review.objects.all() paginator = Paginator(context['reviews'], 1) page = self.request.GET.get('page') try: context['reviews'] = paginator.page(page) except PageNotAnInteger: context['reviews'] = paginator.page(1) except EmptyPage: context['reviews'] = paginator.page(paginator.num_pages) return context Code reviews.html <div id="reviews" class="row md-3"> {% for review in reviews %} <div class="col-md-6"> <div class="reviews-card reviews__link"> <div class="reviews-card__box"> <div class="reviews-card__author"> <div class="reviews-card__preview"> <picture> <img class="reviews-card__img" src="{{ review.photo.url }}" alt="{{ review.name }} {{ review.surname }}"></picture> </div> <div class="reviews-card__name">{{ review.name }}<br>{{ review.surname }}</div> </div> <p class="reviews-card__text">{{ review.content }}</p></div> </div> </div> {% endfor %} </div> {% if not reviews.paginator.page_range|length == 1 %} <div class="pagination__wrapper"> <div id="pagination" class="pagination"> {% for page in reviews.paginator.page_range %} {% if reviews.number == page %} <span class="active">{{ page }}</span> {% elif page > reviews.number|add:-2 and page < reviews.number|add:2 %} <a class="page" href="{{ request.path }}?page={{ page }}">{{ … -
JS & Django- How to access a value from H1 tag using DOM? I am getting no response from the JS
I am passing an integer value to HTML template, and I want to access it before it is shown to the user. Here's the code: status.html <div id="frame_body"> <div id="percentage"><h1 id="receivedVal">{{projects.phase}}<sup>%</sup></h1></div> <div id="proj-name"><p>XXXXXXXXXXX</p></div> <div id="name-of-staff-head"><p>Supervised by Mr. X</p></div> <div id="temporary"> <!-- <p>Status -{{projects.status}}</p> <br> <p>Phase -{{projects.phase}}</p> <br> <p>Collaborators -{{projects.collab}}</p> --> </div> </div> JS: function showPercentage(){ var phase_no = document.getElementById("receivedVal").value; var percentage = (phase_no / 10) * 100; document.getElementById("receivedVal").innerHTML = percentage; } As you can see from the code, I want to perform that calculation and return new value there again. How can I do that? -
csrf token missing when using django Views
When I am submitting a login form for a normal user or for admin. I get the following error CSRF token missing or incorrect. The interesting things when I use a custom view for registering everything is fine. I tried to swap the urls from my custom projects to the one created by django initially and neither options work login.html <form method="POST"> {% csrf_token %} <fieldset"> <legend>Log In</legend> {{ form|crispy }} </fieldset> <div class="logBu"> <button type="submit">Login</button> </div> </form> urls.py path('register/', views.register, name='register'), path('login/', Builtviews.LoginView.as_view(template_name='main/login.html'), name='login'), path('logout/', Builtviews.LogoutView.as_view(template_name='main/logout.html'), name='logout'), Ive cleared out all my cookies. Ive even added a csrf_trusted origins as well as CORS to settings but nothing works. I even downgraded django since i read this is a 4.0.0 thing and that didnt work either. settings.py CSRF_TRUSTED_ORIGINS = [ 'http://127.0.0.1:8080/admin', 'http://127.0.0.1:8000/admin/login', 'http://127.0.0.1:8000/admin/login?next=/admin/', 'http://127.0.0.1:8000/login', 'http://127.0.0.1:8000/login/', 'http://127.0.0.1:8000/login?next=/profile/', #Encrypted version 'https://127.0.0.1:8080/admin', 'https://127.0.0.1:8000/admin/login', 'https://127.0.0.1:8000/admin/login?next=/admin/', 'https://127.0.0.1:8000/login', 'https://127.0.0.1:8000/login/', 'https://127.0.0.1:8000/login?next=/profile/' ] CORS_ORIGIN_WHITELIST = [ 'http://127.0.0.1:8080' ] I have added corsheaders to installed apps as well as the appropriate things to middlewear -
http://127.0.0.1:8000' has been blocked by CORS policy Django AJAX
I'm working on AJAX call but I'm struggling on the CORS error 'http://127.0.0.1:8000' has been blocked by CORS policy: I've search all over the internet but no luck I also tried django-cors-headers $(document).ready(function() { var delay = 2000; $('.view-data').click(function() { var slug = $(this).attr("slug"); alert(slug); $.ajax({ method: "post", url: "core:bell_schedule/", data: { slug: slug }, beforeSend: function() { $('#applicant-display').html('<div class="spinner-border text-secondary" role="status"><span class="visually-hidden">Loading...</span></div>'); }, success: function(data) { setTimeout(function() { $('#applicant-display').html(data).fadeIn('slow'); }, delay); }, error: function(data) { alert('Error 100'); } }); }); }); -
Place management application - What technologies? [closed]
I came up with a building space management application for each floor. I would like it to be a web application. After logging in, the user could select the building, floor and the floor map should be displayed. By pressing on a room, he could reserve it. In what technologies could I implement it? I was thinking about python and django, maybe some react, java and angular. I have no experience in building such an application. I only did a few projects in python, c ++ and java. I would like to find an example of such an application, maybe a video. I can't find anything like that myself. Any ideas? -
dynamic log filename with incoming post request data in Django logging
I am very new to Django. I have a use case wherein, I have to group a log filename from incoming post request json data Example of post request json data { "name": "kurt", "year_of_birth": 1996, "course": "Arts" } I want to have a filename 1996.log to be generated, so that I can have datas of all the students with year_of_birth 1996 logged in 1996.log Example 2 { "name": "Mike", "year_of_birth": 1994, "course": "Science" } in this case log filename should be 1994.log This way I want to generate log filname by year_of_birth and have logs logged in respective log file with respect to incoming post request data views.py from rest_framework import viewsets import logging student_logger = logging.getLogger("student_log") class BlogViewSet(viewsets.ViewSet): def create(self, request, *args, **kwargs): data = request.data print(f"\n############ data: {data} \n\n") student_logger.debug(data) return Response({"data": "logged successfully", "msg": "success"}) LOGGING in settings.py LOGGING = { "version": 1, "formatters": { 'student_formatter': { 'format': '{levelname} {asctime} {pathname} {filename} {funcName} {lineno} {message}', 'style': '{', }, }, "handlers": { "student_handlers": { "level": "DEBUG", "class": "logging.FileHandler", "filename": os.path.join(BASE_DIR, "logs/year_of_birth.log"), # want to change year_of_birth.log with incoming post request data's year_of_birth i.e 1996.log, 1994.log 'formatter': 'student_formatter' } }, "loggers": { "student_log": { "handlers": ["student_handlers"], "propagate": True, … -
`django-import-export` import/export nested related objects
I want to export department name, but failed. # models.py from django.contrib.auth import get_user_model from django.db import models class Department(models.Model): name = models.CharField(max_length=180, blank=True, null=True, unique=True) class HseUser(models.Model): user = models.OneToOneField(get_user_model(), on_delete=models.CASCADE) dept = models.ForeignKey(Department, on_delete=models.SET_NULL, null=True, blank=True) class UserModelProxy(get_user_model()): class Meta: proxy = True admin.py from import_export.admin import ImportExportActionModelAdmin from import_export import fields from import_export import resources class UserResource(resources.ModelResource): hseuser = fields.Field(attribute='hseuser', column_name='name', widget=ForeignKeyWidget(HseUser, 'name')) # ??? department export class Meta: model = get_user_model() class MyUserAdmin(UserAdmin, ImportExportActionModelAdmin): resource_class = UserResource admin.site.register(UserModelProxy, MyUserAdmin) Using admin actinon to export xlsx, succeed to export hseuser.name, but failed to export department name. How to fix it? -
Can any one suggest how to render a pdf document using base64 string in html
Can any one suggest how to render a pdf document. I am using the same method suggested by Will Keeling, so instead of image, I am using pdf <object id="documentFileViewModalContext" frameborder="0" width="100%" height="100%" data="data:application/pdf;base64,{{ base64_string}}" type="application/pdf" class="internal"> <embed src="data:application/pdf;base64,{{ base64_string}}" type="application/pdf" /> </object> And in python code as below pdf_file = branchDocumentFileObject.document.path file_handle = open(pdf_file, "rb") base64_string = base64.b64encode(file_handle.read()).decode('ascii') context['base64_string'] = base64_string html_content = render_to_string("adminToolsApp/manage/branch/document/documentView.html", context=context, request=request) returnStatus['status'] = 'success' returnStatus['response'] = html_content return JsonResponse(returnStatus, safe=False) I would appreciate your suggestion Thanks Benny -
After Saving value in Positive Intefer filed Django Models, can not be edit later on
I am working on postive integer field on django models.py , I want to make that filed unchangeble after saving. Can not be eidt after saving value. models.py end_run = models.PositiveIntegerField( null=True, blank=True, help_text=_("Can be enter value Onece") -
Running a streaming api python script on cPanel
I have looked over lots of info on running scripts in cPanel and I have successfully learned to do it with cron jobs etc. But with regard to a script that streams data via API I can’t find much info. Cron jobs sends me an email after execution so I know its working or not. However with a continuous data streaming script I do not know how to tell if it is running and working. I have figured I would need to setup a django web app interface to monitor it but I am not a web app programmer. Is there something out there that makes this easier? Or do I need to integrate the script into a django webapp (which means paying someone to do it for me…) ? -
How to overwrite all objects in Django database after uploading an excel file?
So I have a Leaderboard page and a Django model such as: models.py class Leaderboard(models.Model): rank = models.IntegerField() team_name = models.CharField(max_length=100) score = models.IntegerField() The thing I'm confused is how can I write the views.py function so that whenever I make a request and upload a new excel file to the views.py it would overwrite the old objects inside of the database and fill the database with the new data. I'm not sure if this is the correct way of creating a manual leaderboard but it's the only way I could think of currently. What I could think of so far: views.py def update_leaderboard(request): new_excel = request.body data = pd.read_excel(new_excel) # Overwrite the database here ... ADDITIONAL INFORMATION I'm using Django Rest Framework as well in this case, because I'm using React for my frontend. So the views might come out a little different (?) -
(DRF) How to update a foreignkey field
I have two models, Account model & Thread model: class Account(AbstractBaseUser, PermissionsMixin): class Meta: verbose_name_plural = "Account List" email = models.EmailField(max_length=255, unique=True) username = models.CharField(max_length=255, unique=True) name = models.CharField(max_length=255, default="") profile_image = models.ImageField(max_length=255, upload_to=profile_image_path, blank=True, null=True, unique=True) about = models.TextField(max_length=255, default='Write something about yourself...', blank=True) start_date = models.DateTimeField(default=timezone.now) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) last_login = models.DateTimeField(auto_now=True) objects = AccountManager() USERNAME_FIELD = "email" REQUIRED_FIELDS = ["username", "name"] def __str__(self): return self.username class Thread(models.Model): options = (('active', 'Active'), ('deactivated', 'Deactivated')) username = models.ForeignKey(Account, on_delete=models.CASCADE, to_field='username') alt = models.TextField(max_length=255, blank=True) image = models.ImageField(max_length=255, upload_to=thread_image_path, blank=True) content = models.TextField(blank=True) created = models.DateTimeField(blank=True, null=True, default=timezone.now) status = models.CharField(max_length=11, choices=options, default='active') If I have already created a thread that is ForeignKey to the Account model, I am not able to change the username of the Account model, returning the error FOREIGN KEY constraint failed. I guess the existing Thread model require a username to point to. Is there way to create a custom update method in view.py to update the ForeignKey automatically? Here is my view.py: class UserViewSet(viewsets.ModelViewSet): serializer_class = UserSerializer queryset = Account.objects.all() permission_classes = (AllowAny,) -
Send user to the page they requested before Signing in with google, after they sign in with google
I have a movie quiz app https://www.quizsocial.xyz/, where users can search for a trending movie and take a quiz about the movie’s story, so when they land on the homepage, they search for their movie, they click start quiz, they agree to the rules, they select how many questions they want to attempt and then they have to sign in with google or create an account, now if they create an account through us, their requested quiz will start automatically once they sign in, but when they do the same thing with google log in, they are redirected to the homepage. Where they have to search for the quiz again, agree to the rules, select how many questions they want to attempt. This may annoy some users and lead them to leave the website and never come back. My question is how do I retrieve their data before they signed up with google and then send them to the exact page they requested after they sign in with google.