Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Generate a pdf file of the data from database
I want to display this context inside an invoice html page but I seem to be stuck at getting data. I want this data to be displayed at the invoice page. Currently, it is giving me Error:''QuerySet' object has no attribute 'product'' models.py: class PurchaseItem(models.Model): product = models.ForeignKey(Item, on_delete=models.CASCADE) quantity = models.PositiveSmallIntegerField() purchase_price = models.DecimalField(max_digits=6, decimal_places=2) paid_amount = models.DecimalField(max_digits=6, decimal_places=2) views.py: def get_context_data(request, **kwargs): purchases = PurchaseItem.objects.all() context={ "company": { "name": "Mc-Services", "address": "1080, Vienna, Austria", "phone": "(818) XXX XXXX", "email": "contact@mcservice---.com", 'product': purchases.product, 'price' : purchases.product.price, 'quantity' : purchases.quantity, }} return render(request, 'purchase/pdf_template.html', context) and the html file pdf_template.html: <tbody> {% for purchase in purchases %} <tr> <td class="no" >{{purchase.product}}</td> <td class="qty" >{{purchase.quantity}}</td> <td class="total" >${{purchase.product.price}}</td> </tr> {% endfor %} </tbody> -
Is there a way to fix this django stripe integration error?
We are integrating stripe for as us stripe account. There is no connection to India but we get this error... Instead of the payment url, we get this : Request req_OuSWvylGF8wZDi: As per Indian regulations, only registered Indian businesses (i.e. sole proprietorships, limited liability partnerships and companies, but not individuals) can accept international payments. More info here: https://stripe.com/docs/ Please help to fix this error. We tried integrating stripe , backend django for a us based company. But we keep on getting Indian regulations error. We don't know how. There is not a relation to India. -
how to add a python ide using codemirror to a django app
I'm new to Django and web-dev and was looking for a good tutorial explaining how to add a codemirror IDE to a django app but haven't been to successful can anyone lead me in the right direction or just throw up some basic code ie: models.py views.py settings.py etc of a basic python ide set up. any help would be greatly appreciated thanks in advance. -
How to render out DateTime selection on form
I am basically trying to make a website that has a form to fill in for someone to select what equipment they need and have another for returning the equipment, I have it all set up and can see it in the admin panel, everything is working fine but when navigating to the return page as this is set out a little different to the original form to collect and by that I mean instead of "Comments" its "ReturnDate", I have this set as DateField apposed and ran the migrations, now when navigating to the page I can not see a Calander to select a date to return the equipment. Any help would be much appreciated, fairly new to Python, Django. I will attach my views, models, form, etc so you can see what I have done. VIEWS from django.shortcuts import render from django.http import JsonResponse from main.models import WFHSHEET from django.http import HttpResponse, response, HttpResponseRedirect from .forms import WFHLIST, RETURNLIST from django.core.mail import send_mail # Create your views here. def home(response): return render(response, 'home.html', {}) def wfhsheet(response): if response.method == "POST": form = WFHLIST(response.POST) if form.is_valid(): form.save() else: form = WFHLIST() return render(response, "form.html", {"form":form}) def returnsheet(response): if response.method … -
What do "-" user in django admin mean? Can't delete or open
I'm trying to learn Django and following a tutorial, I have a "-" user in my Customer Model, I'm not sure where it came from. If I attempt to delete or open it, the error below appears. I tried to verify if my Customer Model is working by deleting other named users and It's working fine. What does the "-" entry means? Thank you for the help. Customer Model page in Django admin TypeError at /admin/accounts/customer/3/change/ str returned non-string (type NoneType) Request Method: GET Request URL: http://127.0.0.1:8000/admin/accounts/customer/3/change/ Django Version: 4.1.3 Exception Type: TypeError Exception Value: str returned non-string (type NoneType) Exception Location: C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages\django\contrib\admin\options.py, line 1859, in _changeform_view Raised during: django.contrib.admin.options.change_view Python Executable: C:\Users\user\AppData\Local\Programs\Python\Python311\python.exe Python Version: 3.11.0 Python Path: ['C:\Users\user\Desktop\crm', 'C:\Users\user\AppData\Local\Programs\Python\Python311\python311.zip', 'C:\Users\user\AppData\Local\Programs\Python\Python311\Lib', 'C:\Users\user\AppData\Local\Programs\Python\Python311\DLLs', 'C:\Users\user\AppData\Local\Programs\Python\Python311', 'C:\Users\user\AppData\Local\Programs\Python\Python311\Lib\site-packages'] Server time: Sun, 01 Jan 2023 15:43:55 +0000 I tried to verify if my Customer Model is working by deleting other named users and It's working fine. -
No diffrence after implementing indexes into Django Model
I want to speed-up my app. I work with large dataset ~26 million records like this: enter image description here The long query processing time (page loading) encouraged me to create indexes. But after implementing I dont see any page loading time difference. My models.py file: enter image description here My views.py file: enter image description here My forms.py file: enter image description here I've tried doing few combinations of indexes. 1) enter image description here 2) enter image description here according to query in views.py which is: enter image description here The speed is still as low as in the version without indexes and takes about 20 second to load a page. How to create indexes that works? -
How I can show the table of all user which role is based on specific values
I have a User Table in Django. It has different role values. I would like to show all user which role is based on a specific value. I would like to show all user in Django admin panel which role is couple only. In admin.py: from django.contrib import admin from django.contrib.auth import admin as auth_admin from django.contrib.auth import get_user_model from users.forms import UserChangeForm, UserCreationForm from users.models import EmailConfirmationToken User = get_user_model() @admin.register(User) class UserAdmin(auth_admin.UserAdmin): form = UserChangeForm add_form = UserCreationForm fieldsets = (("User", {"fields": ("name", "wedding_date", "wedding_zip_code", "role", "photo", "subscription", "leads")}),) + auth_admin.UserAdmin.fieldsets list_display = ["username", "name", "is_superuser", "is_active"] search_fields = ["name", "subscription"] -
How to add images in the project Django
My logo doesn't work in Django project: Code bellow: index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Главная</title> {% load static %} <img src="{% static 'media/logo.svg' %}" alt="My logo"> </head> <body> </body> <footer> </footer> </html> settings.py: STATIC_URL = 'static/' The structure of project: When i try yo open yje console it takes: Failed to load resource: the server responded with a status of 404 (Not Found) Logo is in a static/media/logo.svg -
Use Throttling to restrict the number of times a certain request can be made globally
I am using Django Throttling, and want to add a behavior that will throttle users from calling a certain request more than X times in rate - globally. Using AnonRateThrottle or UserRateThrottle is not good enough for me, because it checks the number of times that a certain User or IP address made the request. I want to limit the global calls to a certain api_view, no matter who made the request. For example, if the rate is 1/min and user X made a request, than every other user will be throttled for the next minute. -
How can I retrieve tag attributes from an HTTP XML request in Django REST?
I'm trying to send an XML file as a payload over HTTP to a Django development server on my local machine. I have no issues sending HTTP POST requests with JSON payloads and I understand that XML functionality does not come with Django REST framework out of the box, so I installed djangorestframework-xml. I used a parser decorator in my api view function definition like so: @api_view(['GET', 'POST']) @parser_classes([XMLParser]) def my_view(request): if request.method =='GET': pass if request.method == 'POST': return Response({'received_data': request.data}) The issue is, the way the data is structured, the information I need to parse is stored as tag attributes, like so: <CEF> <Element> <p x="1" y="2"/> </Element> </CEF> And when it is received by Django, request.data does not include attribute tag data: { "received_data": { "Element": { "p": null } } } Is there a header I could add to the HTTP request to preserve the xml tag attribute data? Any pointers are greatly appreciated! I tried different configurations for the tag data, but ultimately, I have no control over the data source and the way the data is structured in the xml file. -
JSONField validation based on another model object
yelp, im stuck. Im trying to build an online bicycleshop and i cant seem to figure this one out. Class Product(models.Model): name_of_bicycle = models.Charfield() Class Bid(models.Model): bid_number = models.PositiveIntegerField() name_of_bidder = models.Charfield() bid = models.JSONField() The JSONField should contain [name_of_bicycle, bidding amount]. Is this possible? Do i have to use JSON schema? I appreciate the help. ——————————————————- -
Why the Imgaes doesn't work in my Django Project
My logo doesn't work in Django project: Code bellow: index.html: <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <title>Главная</title> {% load static %} <img src="{% static 'media/logo.svg' %}" alt="My logo"> </head> <body> </body> <footer> </footer> </html> settings.py: STATIC_URL = 'static/' The structure of project: -
How to delete entry in django?
there is a small django project that has methods for creating a topic, creating and editing posts within it. I don't understand how to write a method to delete a post in a topic views.py from django.shortcuts import render, redirect from django.contrib.auth.decorators import login_required from .models import Topic, Entry from .forms import TopicForm, EntryForm from django.http import Http404 @login_required() def new_entry(request, topic_id): topic = Topic.objects.get(id=topic_id) check_topic_owner(topic.owner, request) if request.method != "POST": form = EntryForm() else: form = EntryForm(data=request.POST) if form.is_valid(): new_entry = form.save(commit=False) new_entry.topic = topic new_entry.save() return redirect('composetopic:topic', topic_id=topic_id) context = {'topic': topic, 'form': form} return render(request, 'composetopic/new_entry.html', context) @login_required() def edit_entry(request, entry_id): entry = Entry.objects.get(id=entry_id) topic = entry.topic check_topic_owner(topic.owner, request) if request.method != "POST": form = EntryForm(instance=entry) else: form = EntryForm(instance=entry, data=request.POST) if form.is_valid(): form.save() return redirect('composetopic:topic', topic_id=topic.id) context = {'entry': entry, 'topic': topic, 'form': form} return render(request, 'composetopic/edit_entry.html', context) def check_topic_owner(owner, request): if owner != request.user: raise Http404 i was tried to add delete_entry() function, but its not working