Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to get current page of django rest pagination in List Api View?
How am I, with this code, supposed to get the current page of pagination in Django Rest in a proper way? class LatestEpisodesAPIView(ListAPIView): serializer_class = LatestEpisodeSerializer pagination_class = StandardResultsSetPagination def get(self, request, *args, **kwargs): res = super(LatestEpisodesAPIView, self).get(request, *args, **kwargs) res.render() cache.set("apiepisode_p_" + HOWTOGETCURRENTPAGINATIONPAGE, res, 60*5) return res In this code I wanted to cache the response of the current page for 5 minutes, by which extravagant joining costs could be averted as the cpu operation costs could peak a high of 500ms per request, and this endpoint is frequently used. To that end, the prerequisite is a unique key for each page, which, in common sense, would be the page number. However, inasmuch the impoverished lackluster inherent nature of DRF's official documentation, information about pagination per se is already scarcer than hen's teeth, let alone trying to get the current page. After hours of scouring the length and breadth of DRF docs, and brute-forcing google search, I myself still fail to find any way to accomplish this goal. I believe I could do this by request.query_params.get("page") but this seems really hard-coded and looks more like a hack than a proper way of doing things. Thanks for your help! -
How to associate form with a button outside that form?
Given this field {% bootstrap_field form.photo %} which is a forms.ImageField and the form after, I need to associate the field with the form in a way that when the form is submitted, I get the value in form.photo. <div class="row container h-100"> <div class="col-xl-4"> <div class="card mb-4 mb-xl-0"> <div class="card-body text-center"> <img style="max-width: 50%" alt="Avatar" class="img-account-profile rounded-circle mb-2" src={{ request.user.profile.photo.url }}> {% bootstrap_field form.photo %} </div> </div> </div> <div class="col h-100"> <div class="card shadow-lg"> <div class="card-body p-5"> <form enctype="multipart/form-data" method="post"> {% csrf_token %} <div class="row"> <span class="col"> {% bootstrap_field form.first_name %} </span> <span class="col"> {% bootstrap_field form.last_name %} </span> <button class="btn btn-success col">Update</button> </div> </form> </div> </div> </div> </div> Currently if a photo is uploaded, it won't show up in the form response because it's not included within <form></form>. I need it to be outside the form because the locations of the form fields and the photo are different. -
Order django queryset by rank of related tags
I'm a little stuck on something. I'm trying to create a cheatsheets app where the user can upvote other users posts. I'm using django-taggit to manage tags and django-vote for voting functionality. class Cheatsheet(VoteModel, models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=500, null=True, blank=True, default="") description = models.CharField( max_length=500, null=True, blank=True, default="") tags = TaggableManager(blank=True) def __str__(self): return self.title and this is the view: class CheatsheetViewSet(viewsets.ModelViewSet, VoteMixin): queryset = Cheatsheet.objects.all() serializer_class = CheatsheetSerializer http_method_names = ['get', 'post', 'retrieve', 'put', 'patch', 'delete'] I'm trying to sort cheatsheets based on the tags related to previously upvoted posts. I have managed to obtain a "tag rank" based on the posts that the user has upvoted. For example if the user upvoted a post with the tags "css" and "js" and another post with only the tag "css" user_tag_rank would result in something like this: {"css": 2, "js": 1} I would like to order the posts based on this rank, with tags with the most upvotes first. In this case all posts with the tag "css" would come first, then posts with the tag "js" and then any other posts. The question is how do I go about sorting the posts based on … -
Diango matching a string with a regex field
In django, if we have a regex and look for a rows whose a field is matching with a regex, it will be something like this: MyAudience.objects.filter(email__iregex=f'^({'|'.join(emails)})$') But what if I want to do it the other way? Let's say I have a string: email = 'abc@example.com' and in my model AudienceFilter, I have a field pattern. This column keeps the regex for the model. I want to find with patterns do match my string? How can I do that? AudienceFilter.objects.filter(pattern__?????=email) -
SQLite error when deploying Django Website on AWS
I'm neewbie here and in programming, so please have some mercy :D I'm making my first Django project with Maximilian Course. I have made Django blog. I walked through few errors when deploy, but now i have encountered this one: enter image description here So I found this solution: https://stackoverflow.com/questions/66380006/django-deterministic-true-requires-sqlite-3-8-3-or-higher-upon-running-python So i understand it like this: 1. In ubuntu terminal i type : sudo apt install python3.10-venv to install envirement 2. Then in my Django project in Visual Studio i type python3 -m venv django_my_site to create virtual env 3. Now i click "+" to open this env and type pip3 install pysqlite3 pip3 install pysqlite3-binary 4. After that i type python3 -m pip freeze > requirements.txt and i get requirements.txt file which looks like that: [enter image description here](https://i.stack.imgur.com/ZeS20.png) 5. After that i pack once more all necessary folders and files [enter image description here](https://i.stack.imgur.com/TTZWZ.png) 6. In AWS in application versions I upload zip once more and deploy. 7. Now looks like AWS have problem with installing packages I have an error log like this: https://files.fm/f/562x66duz -
Redirecting old urls to new urls in Django
After publishing site in Django, I changed my slugs and now old pages show as errors in Google search. Is there a way to automatically redirect them without having to write an individual redirect for each page? -
What is the max size of Django cache and is there any chance to extend that?
I'm working on a project where i have to deal with big data (big number of rows) To make the app fast I'm using redis with Django cache , I'm selecting all the data from Table A and saving it to cache as a json array, and later I select, update and delete from cache, I also have other tables B, c, D ... etc Each table could hold more then 3 million rows in the future, probably more and more ... I was wounding if Django cache can handle that? If not what's the maximum size or rows that Django cache can store? Is there a way to extend that, if not what are the order solutions for this problem? I don't want to select data always from database, Because speed does matters here -
I have an error in installing django-socketio in windows virtualenv
I have a problem in installing django socket io, i changed django version to 3.2 and still the error image of the error -
How to change where vitejs puts its HTML files?
I want to change where vite produces its HTML files, but I have not been able to figure it out yet. By default, the files for an html page get compiled into these file locations: /dist/src/pages/index.js /dist/src/pages/index.html The locations above are produced by this vite.config.ts: import { defineConfig } from "vite"; import react from "@vitejs/plugin-react"; import path, { resolve } from "path"; import manifest from "./src/manifest"; import makeManifest from "./build-utils/rollup-plugins/make-manifest"; const root = resolve(__dirname, "src"); const pagesDir = resolve(root, "pages"); const assetsDir = resolve(root, "assets"); const outDir = resolve(__dirname, "dist"); // const publicDir = resolve(__dirname, "src", "public"); const publicDir = resolve(__dirname, "src", "copied-to-dist-on-compile"); const isDev = process.env.__DEV__ === "true"; const isProduction = !isDev; export default defineConfig({ resolve: { alias: { "@src": root, "@assets": path.resolve(root, "assets"), "@pages": path.resolve(root, "pages"), "@utils": path.resolve(root, "utils") }, }, plugins: [ react(), makeManifest(manifest), ], publicDir, build: { outDir, assetsDir, minify: isProduction, reportCompressedSize: isProduction, rollupOptions: { input: { devtools: resolve(pagesDir, "devtools", "index.html"), panel: resolve(pagesDir, "panel", "index.html"), content: resolve(pagesDir, "content", "index.ts"), background: resolve(pagesDir, "background", "index.ts"), contentStyle: resolve(pagesDir, "content", "style.scss"), popup: resolve(pagesDir, "popup", "index.html"), newtab: resolve(pagesDir, "newtab", "index.html"), options: resolve(pagesDir, "options", "index.html"), }, watch: { include: ["src/**", "vite.config.ts"], exclude: ["node_modules/**", "src/**/*.spec.ts"], }, output: { entryFileNames: "src/pages/[name]/index.js", chunkFileNames: isDev ? … -
Deployment issues with railway
due to the new pricing of heroku I decided to switch from heroku to railway. At first I encountered a cors header error but then I added SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') to my settings.py file. The error stopped occurring but now I'm facing a new error <meta name="viewport" content="width=device-width, initial-scale=1"> <meta charset="utf-8"> <title>Server Error</title> and the title of the error is response status is 503. I've set Debug to False, I've added the url to the list of Allowed hosts and I've also added corsheaders to installed apps and the cors middleware. Any help with go a long way. -
How to keep calling api until task is completed in reactjs?
I am working on reactjs as frontend, and Django in the backend. I have a time taking task written in django, which ideally takes more time to retrieve values than the stipulated API response time. Therefore, I have made it into a celery task, whose task id I return as an API response. The plan was to make the API call on page load which starts the celery task, and returns the task ID. So, with the task ID, I can keep polling another API to get the task's status, until completed. Once the task is completed, I can ping another API to get the response of the celery task. I thought, I can make the API call, and thenafter run a loop with a sleep, but not sure how to achieve this? import { useEffect, useState } from "react" import axios from "axios" function App() { const [taskId, setTaskId] = useState("") const apiToSpawnTask = () => { axios.get("http://localhost:8000/spawn_task") .then(({data}) => setTaskId(data.task_id)) } const checkTaskStatus = () => { axios.get(`http://localhost:8000/task-id/${taskId}`) .then(({data}) => { // data.status contains the status of the task id }) } const getCompletedTaskResult = () => { axios.get(`http://localhost:8000/get-task-result/${taskId}`) .then(({data}) => { // this data is used in … -
Csv to django model with many-to-many relationship
I have to write a script to load data from a csv file and add the entries to a django database. The only problem I have is that I need to group entries from one column and link it to the id-s, like this: So notice that the same protein id-s map to different protein-domains, but protein_domains can also map to more than one protein, thus I need the many-to-many relationship. Of course, protein id I can only have one, so the data should be like: [protein_id, protein_taxonomy,[protein_domain,protein_domain],protein_length] My django models look like this: class Domains(models.Model): pfam = models.ForeignKey(ProteinFamily, on_delete=models.DO_NOTHING) # pfam = models.CharField(max_length=15, null=True, blank=False) description = models.CharField(max_length=100, null=True, blank=False) start = models.IntegerField(null=False, blank=True) stop = models.IntegerField(null=False, blank=True) def __str__(self): return self.pfam.domain class Protein(models.Model): protein = models.ForeignKey(ProteinId, on_delete=models.DO_NOTHING) protein_taxonomy = models.ForeignKey(Taxonomy, on_delete=models.DO_NOTHING) protein_length = models.IntegerField(null=True, blank=True) protein_domains = models.ManyToManyField(Domains, through='ProteinDomainsLink') def __str__(self): return self.protein.protein_id This is my attempt to load the data from csv and add it to the database: with open(assignment_data_set) as csv_file: csv_reader = csv.reader(csv_file, delimiter=',') for row in csv_reader: proteins.add((row[0],row[8],row[5],row[1])) protein_rows = {} for entry in proteins: row = Protein.objects.create(protein=proteinIds_rows[entry[0]],protein_length=entry[1],protein_taxonomy=taxonomy_rows[entry[3]]) row.protein_domains.add(domains_rows[entry[2]]) row.save() protein_rows[entry[0]] = row It kind of works, but still 2 Protein objects get created … -
Single Sign-on architecture with Django and Azure
I have 3 applications developed with Django Framework and i need to centralize authentification through Single Sign-On (SSO) with Azure AD. My questions are the following : What is the best architecture to implement the solution? Which libraries should i use ? (i'll be gratefull if usefull tutorials are attached :p) -
how to connect ClearDB -mysql database to my web app django project
i have deployed my first Dejango webapp to Heroku. At the begining it was working but it was not connecting the database and loging and also create super user was not working either. i changed database in heroku from Postgre to ClearDB database because this last one is free in Heroku. the problem is when i try to python manage.py makemigrations or migrate or createsuperuser it does not work and shows this error: **(2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") **``` i changed the Database from settings.py but it was not working either: this is the database file from Settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': '******', here i have changed from my local database to the new name coming from heroku 'USER': '******', here i have changed the user for the one coming from Heroku 'PASSWORD': '******', here i have changed the passworkd for the one coming from Heroku 'HOST': '****', here i have changed the HOST for the one coming from Heroku 'PORT': 3306 } } this is the top of Settings.py import os import django_heroku import dj_database_url from decouple import config i also changed the allowed hosts ALLOWED_HOSTS = ['.herokuapp.com'] thanks … -
Uncaught SyntaxError: Unexpected token " " is not valid JSON at JSON.parse (<anonymous>) when working with django
I am working on a Django chat application whereby I am using websockets and transferring JSON data. I have however encoutered some errors which are making it difficult for me to proceed. The error states Uncaught SyntaxError: Unexpected token 'T', "Thanks for"... is not valid JSON at JSON.parse (<anonymous>) at ws.onmessage Here is part of my consumers.py which is handling the connection: def websocket_receive(self, event): print(f'[{self.channel_name}] - Recieved message - {event["text"]}') msg = json.dumps({ 'text': event.get('text'), 'username': self.scope['user'].username }) self.store_message(event.get('text')) async_to_sync(self.channel_layer.group_send)( self.room_name, { 'type': 'websocket.message', 'text': msg } ) def websocket_message(self, event): print(f'[{self.channel_name}] - Message sent - {event["text"]}') self.send({ 'type': 'websocket.send', 'text': event.get('text') }) And here is my javascript: ws.onmessage = function(event) { console.log(event); console.log("Message is received"); const ul = document.getElementById('message-list') var li = document.createElement('li') var data = JSON.parse(event.data); // var data = event.data; li.append(document.createTextNode( '[' + data.username + ']:' + data.text )) ul.append(li); } The code above is my original code. After going through similar previous errors, I noticed one comment saying that it is because the data is already in json format. However, when I replace var data = JSON.parse(event.data); with var data = event.data; I do not get the same error above, but instead the returned data … -
Django RequestFactory; TypeError: get() missing 1 required positional argument;
In attempting to test the context of a view PostedQuestionPage with RequestFactory, the following error is being raised when running the test: File "C:\Users\..\django\test\testcases.py", line 1201, in setUpClass cls.setUpTestData() Fi..\posts\test\test_views.py", line 334, in setUpTestData cls.view = PostedQuestionPage.as_view()(request) File "C:\..\django\views\generic\base.py", line 70, in view return self.dispatch(request, *args, **kwargs) File "C:\..\django\views\generic\base.py", line 98, in dispatch return handler(request, *args, **kwargs) TypeError: get() missing 1 required positional argument: 'question_id' It's unclear to me as to why the error is being raised while question_id is being passed into reverse("posts:question", kwargs={'question_id': 1})? test_views.py class TestQuestionIPAddressHit(TestCase): '''Verify that a page hit is recorded from a user of a given IP address on a posted question.''' @classmethod def setUpTestData(cls): user_author = get_user_model().objects.create_user("ItsNotYou") user_me = get_user_model().objects.create_user("ItsMe") author_profile = Profile.objects.create(user=user_author) user_me = Profile.objects.create(user=user_me) question = Question.objects.create( title="Blah blahhhhhhhhh blahhh I'm bord blah blah zzzzzzzzzzzzz", body="This is zzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzzz...zzzzz", profile=author_profile ) authenticated_user = user_me.user request = RequestFactory().get( reverse("posts:question", kwargs={"question_id": 1}), headers={ "REMOTE_ADDR": "IP Address here" } ) request.user = authenticated_user cls.view = PostedQuestionPage.as_view()(request) views.py class PostedQuestionPage(Page): template_name = "posts/question.html" def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['answer_form'] = AnswerForm return context def get(self, request, question_id): context = self.get_context_data() question = get_object_or_404(Question, id=question_id) if question.profile.user != request.user and not question.visible: raise Http404 context |= … -
Getting id for Custom Admin Actions
I want to get the id of a query set that is selected in the admin panel and want this custom action to redirect me to the url having the id in it. However I am not able to do so. admin.py: @admin.register(models.PurchaseItem) class PurchaseItemAdmin(admin.ModelAdmin): list_display = ( 'id', 'product', 'supplier', 'quantity') @admin.action(description='View Invoice') def get_context_data(self, request, query_set): return HttpResponseRedirect('/purchases/10/generatePDF') actions = [get_context_data] I want to be able to have any id instead of hardcoding '10' in the url to that when I select a query, I can use the custom command to redirect to its pdf page. -
Save django summer note as typing
I currently have a working install of django-summernote. What I am wondering, is does django offer the ability to have an event trigger when typing into the editor to save the post? -
Json displaying blank
Im making a request from a JSon file in a webpage, but is returning a blank screen. import { useEffect, useState } from 'react'; import axios from 'axios' import './App.css'; import React from 'react'; function App() { const [posts, setPosts] = useState([]) useEffect(() => { axios.get("https://economia.awesomeapi.com.br/json/last/USD-BRL") .then((response) => { console.log("ok") console.log(response.data) setPosts(response.data) }).catch(() => { console.log("erro") }) }, []) return ( <div> {posts?.map((post, key) =>{ return( <div key={key}> <td></td> <td>Dolar</td> <td>{post.bid}</td> <td>{post.create_date}</td> </div>) })} ); } export default App; The console is able to see the json file, but the page on the browser is completely blank: enter image description here I tried many json files, and only one worked out, was this one: https://api.covid19api.com/countries I had this same problem using React and Django. -
Contactform model displays no content in the Django admin panel. Django admin panel module values are empty
so I am trying to make an simple contact form for my website and Technically I am finished with this. But whenever i try to test and submit something through this form, the input values are not showing in the admin panel. I get no errors but the i don't see any code For example: (https://i.stack.imgur.com/plMjM.png) This should add 3 values into the admin panel But instead (https://i.stack.imgur.com/DQR7U.png) does it add nothing into the admin panel. The code should work like this: The user should write a message in the HTML. <section class="contact-me"> <h2>Kontaktiere mich</h2> <form method="POST"> {% csrf_token %} <h4>Vorname:</h4> <input type="text" placeholder="Vorname" name="vorname"> <h4>Email:</h4> <input type="email" placeholder="email@email.com" name="email"> <h4>Nachicht/Frage:</h4> <textarea name="nachricht" id="" cols="30" rows="10"></textarea> <br> <input type="submit" value="submit"> </form> </section> In the views.py file there is this code witch should take the inputs and convert them into the model. views.py def aboutme(request): if request.method=="POST": contact = ContactForm() vorname = request.POST["vorname"] email = request.POST["email"] nachricht = request.POST["nachricht"] contact.name = vorname contact.email = email contact.nachricht = nachricht contact.save() return HttpResponse("<h1>Danke für deine Nachricht</h1>") return render(request, "aboutme.html") models.py class ContactForm(models.Model): vorname = models.CharField(max_length=15) email = models.EmailField(max_length=20) nachricht = models.TextField(max_length=1000) def __str__(self): return self.vorname The admin panel shows that there is an … -
how to insert list of data into django database?
I made a list of items in string that i wanted to insert them into my Country table from shell, well wasn't successful so need some help.(i tried to add it as list and tuple but didn't work just caused more errors) I use sqlite3 database models.py class Country(models.Model): #countries list country_name = models.CharField(max_length=100) a list like this 'Afghanistan', 'Albania', 'Algeria', 'Andorra' -
In Django's auth contrib module, how do I invoke the function that generates a password reset email?
I'm using Django 3.1.1 with the auth contrib module. I would like to send the user an email when they request their password be reset (via an API call) so I created this in my urls.py file path('reset_password', views.ResetPasswordView.as_view(template_name='../templates/users/password_reset.html'), name='reset_password'), and added this to my views.py file 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: print("email: %s " % email) return super(ResetPasswordView, self).post(request, *args, **kwargs) except: # this for if the email is not in the db of the system return super(ResetPasswordView, self).post(request, *args, **kwargs) but when I call my reset password endpoint with a user that exists, I simply get the contents of my template returned from the endpoint. How do I configure things such that the … -
CSS is not linked to HTML(template) file successfully and nothing happens when I change the CSS - Django
I just finished reading Django document and I'm trying to deploy a website with it. I linked all the style sheets to HTML file(template) but when I change the CSS file(like changing color), nothing change. Furthermore the pre loader don't work and Its just spinning. Directory Structure: HTML file header: <link rel="stylesheet" href="{% static 'css/basic.css' %}" /> <link rel="stylesheet" href="{% static 'css/layout.css' %}" /> <link rel="stylesheet" href="{% static 'css/blogs.css' %}" /> <link rel="stylesheet" href="{% static 'css/line-awesome.css' %}" /> <link rel="stylesheet" href="{% static 'css/magnific-popup.css' %}" /> <link rel="stylesheet" href="{% static 'css/animate.css' %}" /> <link rel="stylesheet" href="{% static 'css/simplebar.css' %}" /> views.py: def home(request): return render(request, "index.html") setting.py: STATIC_URL = 'static/' STATICFILES_DIR = [ path.join(BASE_DIR, 'static'), ] STATIC_ROOT = path.join(BASE_DIR, 'static') And for the preloader: HTML file: <div class="preloader"> <div class="centrize full-width"> <div class="vertical-center"> <div class="spinner"> <div class="double-bounce1"></div> <div class="double-bounce2"></div> </div> </div> </div> </div> js: $(window).on("load", function() { var preload = $('.preloader'); var lines = $('.lines-grid'); preload.find('.spinner').fadeOut(function(){ preload.fadeOut(); lines.addClass('loaded'); }); }); I tried to delete the pre loader but when I delete the JS or the html element the page goes black at all -
Django Template and jQuery response Syntax Help - Could not parse the remainder Error
I'm trying to pass a response variable into a form action, but it keeps saying "ERROR:Could not parse the remainder" It is the ${response['comment_id']} throwing an error I think it's the {} within the {% %} messing it up? Anyone know a solution for this? {% url "delete_comment" ${response['comment_id']} %} -
Count total sum of values for a category
I have a table that contains a set of bills. Each bill is categorized. Like CreditCard, Loan, and Personal... Im trying to get the total amount for category. class Debt(models.Model): Categories = [ ('Credit Card', 'Credit Card'), ('Mortgage', 'Mortgage'), ('Loan', 'Loan'), ('Household Bill', 'Household Bill'), ('Social', 'Social'), ('Personal', 'Personal') ] user = models.ForeignKey(User, on_delete=models.CASCADE) creditor = models.ForeignKey(Creditor, on_delete=models.CASCADE) amount = models.FloatField(blank=True,null=True) category = models.CharField(max_length=50, blank=True,null=True, I think that using annotate is the correct approach, but I'm can't work out how to group the categories together to get the total. all_outgoing = Debt.objects.annotate(total=Sum('amount')).filter(category='personal') I don't think I should need to create a annotate for each category, but maybe I do? Is there a better way? Is the better way to wrap in a loop and pass the category onto the filter? Thanks