Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
"Authentication credentials were not provided." Django and AWS application
I am implementing an application in Django with a TokenAuthentication extension that I found here https://medium.com/@yerkebulan199/django-rest-framework-drf-token-authentication-with-expires-in-a05c1d2b7e05 Everything works perfect in localhost but when I upload my application to AWS, postman doesn't recognize the token that I send in the headers. Is there a reason for this? I don't know if I am missing something, the response is { "detail": "Authentication credentials were not provided." } But in localhost is OK :( -
django loop static files directory
Iam trying to loop thru images in static/folder. I can loop thru images in main 'static' folder but when i put them in 'static/folder' iam not sure how to do it in html. my html lines(works when img in main 'static' folder) {% for file in files %} <img src=" {% static file %}" height="800"> <p>File name:{{ file }}</p> {% endfor %} my views.py def album1(request): images = '/home/michal/PycharmProjects/Family/gallery/static/' files = os.listdir(os.path.join(images)) context = {'files': files} return render(request, 'gallery/album1/main.html', context) If i change views to: def album1(request): images = '/home/michal/PycharmProjects/Family/gallery/static/' files = os.listdir(os.path.join(images, 'folder')) context = {'files': files} return render(request, 'gallery/album1/main.html', context) It loops filenames in 'static/folder/' as expected, but then i cant figure out how to change it in html ,as its adding file names to: /static/{{ file }} instead to /static/folder/{{ file }}. I think iam missing something or something need changing in load static on this particular page? {% load static %} # either here <img src=" {% static file %}"> # or here? -
How to run function in django on clicking item from a list?
In my template I have a list containing some items under headings of name and id and i want to add hyperlink to each of them item and when i click an item it takes it's id as argument to the function in views.py of django and run that function. Currently my templates looks like: <html> <head> <body> <table border="1" cellpadding="5" cellspacing="5"> <td>ID</td> <td>Name</td> {% for i in data%} <tr> <td>{{i.ID}}</td> <td>{{i.Name}}</td> </tr> {% endfor %} </table> </body> </head></html> -
Django project layout
I would like to change the layout of standard django project and I also run django with virtual env. How can I do it? Current project structure looks like this: app1 - __init.py__ - admin.py - apps.py - models.py - tests.py - views.py mysite - __init.py - asgi.py - settings.py - urls.py - wsgi.py db.sqlite3 manage.py .gitignore requirements.txt I would like to move these files into separate folder called src and leave some non-django files outside of the structure (things like gitignore, requirements, etc.), so the directory looks like this src app1 - __init.py__ - admin.py - apps.py - models.py - tests.py - views.py mysite - __init.py - asgi.py - settings.py - urls.py - wsgi.py db.sqlite3 manage.py .gitignore requirements.txt -
Cant filter this variable (Python)
Im using python to filter this variable a = " ".join(map(str, items)) a = {'id': 10, 'product': {'id': 10, 'name': 'Modelo Jungla', 'price': Decimal('19.50'), 'imageURL': '/images/s10_2mkhtq7.png'}, 'quantity': 1, 'digital': False, 'get_total': Decimal('19.50')} I want to get some specific part of the string, or delete some parts -
Azure-cli fails to add extensions on termux
I've installed the Azure-cli on termux. I followed this tutorial it works fine except when I attempt to setup "UP extension", with this command : $ az extension add --name db-up It gave me this error : An error occurred. Pip failed with status code 1. Use --debug for more information. -
Built-In callable as a default argument for a Django Field
I have a JSONField that I need to apply a default dictionary to. As per the documentation, I am avoiding passing the mutable dictionary to the default field. This is done by instead passing the copy method to the default argument like such: default_dict = {'some_key': 'some value'} class MyModel(models.Model): my_field = models.JSONField(default=default_dict.copy) When applying makemigrations, this is failing because of the following condition in django.db.migrations.serializer.FunctionTypeSerializer: if self.value.__module__ is None: raise ValueError("Cannot serialize function %r: No module" % self.value) I can get around this by defining a callable that returns a copy, but I think this is adding unnecessary syntax and makes it harder to read: class ADict(dict): def __call__(self): return self.copy() default_dict = ADict({'some_key': 'some value'}) class MyModel(models.Model): my_field = models.JSONField(default=default_dict) Is there a way to pass a built-in objects method as the default value for a Django field? -
How to add title without losing option selected in form select multiple ( django )
Here are my models.py: class Student(models.Model): course = models.ManyToManyField( CourseInstance) Here are my views.py: class StudentUpdate(UpdateView): model = Student fields = '__all__' student_form.html: <form action="" method="post" id = "group-form"> {% csrf_token %} <table> {% for field in form %} <div class="row"> <div class="col-md-2"> {{ field.label_tag }} {% if 'курсы:' in field.label_tag|lower %} <div> <a href="{% url 'GroupCreate'%}" id="add_group" onclick="return showAddPopup(this);">Добавить</a> </div> {% endif %} {{ field.errors }} </div> <div class="col-md-10 pull-left"> {% if 'курсы:' in field.label_tag|lower %} {% comment %} {% load widget_tweaks %} {% render_field field class="help-title-on" %} {% endcomment %} <select name="course" required id="id_course" multiple> {% with value=form.course.value %} {% for value in form.course.field.choices.queryset %} <option title="{{value}}" value="{{ value.id }}">{{ value }}</option> {% endfor %} {% endwith %} </select> {% elif 'modelfield' not in field.name %} {{ field }} {% endif %} </div> </div> {% endfor %} </table> <input type="submit" value="Submit"> When I render the form template this way, I lose the "course" selected, but the title is added. Tried to do with widget settings. I don't know how to refer to "option" in "select". How to assign: option title="{{text_value}}" with title but lose selected without title but with selected -
Javascript & Django: Event listener for form submit (Multiple forms using for loop) for AJAX
I tried posting before but I was not able to get a clear answer so I thought I would reframe it simply. My template currently uses a for loop to print the posts of a "blog" and another for loop inside that to print comments belonging to the post. Before I continue, just want to make it clear that my models and database is functioning. I even currently have a working comment section, it just keeps refreshing the page and so I would like to incorporate JS and AJAX instead. Because I have multiple posts with their own comment sections, I tried creating individual id's for each form in the loop by saying . However, I am slightly confused as to how I am supposed to create an EventListener to make sure that no matter which of these forms are pressed, it takes the correct data and sends it to the backend. Any help would be appreciated. Thank you! Code upon request is available. However, I would like to stress that it is unnecessary to ask for my model code as it works just fine. -
Reactify Django or separated frontend and backend
I would like to know why sould reactify Django or why should we use separated django backend and react frontend. which implementation is more scalelable I hope you could help me ;) -
How do I continue work on a django project I created with cmd and using sublime text?
How do I continue work on a django project after I switched off my laptop. I'm using sublime text to edit and my command prompt to runserver. I have created a virtual environment and also activate it at the beginning of my work. -
How do fix form has no attribute get for my Django form
I am displaying the filled data by filling in form fields with data filled in sessions. Previously I implemented it using class where I had self variable so form = self.get_initial_data(request) worked However trying to do it via function based view yields me this error. How do I correct it? my views.py file def get_initial_data(request): form=RegForm(initial={ 'first_name':request.session.get('first_name',''), 'last_name':request.session.get('last_name',''), 'personal_email':request.session.get('personal_email',''), 'official_email':request.session.get('official_email',''), 'permanent_address':request.session.get('current_address',''), 'current_address':request.session.get('permanent_address',''), 'pan_card_number':request.session.get('pan_card_number',''), 'aadhar_card_number':request.session.get('aadhar_card_number',''), 'loan_amount':request.session.get('loan_amount','')}) return form @login_required(login_url='login') def multi_form(request): form=RegForm() if request.method=='POST': form=RegForm(request.POST, request.FILES) if form.is_valid(): request.session['first_name']=form.cleaned_data['first_name'] request.session['last_name']=form.cleaned_data['last_name'] request.session['personal_email']=form.cleaned_data['personal_email'] request.session['official_email']=form.cleaned_data['official_email'] request.session['current_address']=form.cleaned_data['current_address'] request.session['permanent_address']=form.cleaned_data['permanent_address'] request.session['pan_card_number']=form.cleaned_data['pan_card_number'] request.session['aadhar_card_number']=form.cleaned_data['aadhar_card_number'] request.session['loan_amount']=form.cleaned_data['loan_amount'] form.save() messages.success(request, "Your Response has been recorded") return render(request, 'customer/index.html') else: if request.session.has_key('pan_card_number'): form=RegForm(get_initial_data(request)) context = {'form': form} return render(request, 'customer/index.html', context) else: context = {'form': form} return render(request, 'customer/index.html', context) My forms.py file class RegForm(ModelForm): class Meta: model=Customer fields=['first_name', 'last_name','personal_email','official_email','current_address','permanent_address','pan_card_number','aadhar_card_number','loan_amount','personal_photo','bank_statement','salary_slip','pan_card','aadhar_card'] The error I am getting AttributeError at /form/ 'RegForm' object has no attribute 'get' Request Method: GET Request URL: http://127.0.0.1:8000/form/ Django Version: 3.1 Exception Type: AttributeError Exception Value: 'RegForm' object has no attribute 'get' -
Is there a way to take data from a django form and upload it to database?
I am trying to pull data from a Django form and upload it to the database. Here are my models: class Category(models.Model): category = models.CharField(max_length = 128) def __str__(self): return f"{self.category}" class Meta: verbose_name_plural = 'Categories' class Listing(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE, default = None) title = models.CharField(max_length = 64) description = models.TextField(max_length = 128) bid = models.ForeignKey(Bid, on_delete = models.CASCADE, related_name = 'listing') url = models.URLField(max_length = 350, blank = True) category = models.ManyToManyField(Category, related_name='listings') watchers = models.ManyToManyField(User, blank = True, related_name='listings') So, when a user adds a new listing, they should choose from categories. Here is how I did it after trying for quite a bit: def new_listing(request): if request.method =="POST": form = ListingForm(request.POST) if form.is_valid(): bid = Bid(amount = int(request.POST['bid'])) bid.save() listing = Listing() listing.bid = bid listing.user = request.user listing.title = form.cleaned_data['title'] listing.description = form.cleaned_data['description'] listing.url = form.cleaned_data['url'] listing.save() listing = Listing.objects.reverse()[0] for category in form.cleaned_data['category']: listing.category.add(category) The issue here is that I have to first save the listing, then pull it again and manually add Categories. I am just wondering if there is a cleaner way of doing this? Or is this how it is done in Django? Cause' I had a really … -
How to retrieve data from SQLite in django (NO PYTHON SHELL)
I looked at many feed/tutorial and when I try to look at retrieving data from SQLite in Django in it always related to Python shell but I do not find any example about how to get data in python files, by this I mean for example getting all database's row in a list with which I can create class instance based on those data. Admitting I have a model looking like this: class Example(models.Model): str = models.CharField() boolean = models.BooleanField(default=False) int = models.IntegerField(default=0) And my own made class: from XXX import Example data = Example.objects.all() for row in data: Class(str=row.str , bool=row.bool, int=row.int) class Class: def __init__(self, str="", bool="False", int=0) In addition, "objects" appears colored in yellow in PyCharm, saying it can't find the meaning/origin. I can't make it work and it actually give me the following error (no idea if it is related): django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. Thank you in advance ! -
DATABASE DRIVEN PWA (Progressive Web App) or Mobile App
This is a general question. My goal is to NARROW DOWN what I need to focus in learning how to code and which programming language to start with. I'm checking into PYTHON and PHP but leaning towards PHP just because I'm familiar with Joomla CMS. My goal is to create a DATABASE-DRIVEN PWA & Mobile App. Summarize the problem: all programming languages has several areas (e.g. machine learning, AI, data analysis, data science, web development, etc.). It's like academics we learned in grade school and high schools that no longer serves us in the profession we choose, agree? Case in point: How many of you are using biology or chemistry that we learned in high school? Describe what you’ve tried: I looked into HTML, PYTHON, JAVA, MySQL, SQLite, Postgre, and PHP When appropriate, show some code: This irrelevant as this is more of a GENERAL QUESTION just to narrow down where I need to focus. I only want to learn what is related to what I want to do (DATABASE-DRIVEN PWA & Mobile App), Here's the question: Is it same to assume that... if and when using or customizing a CMS like Joomla or Django... all programming languages have the … -
What are the next steps after I made a functional Django web app in my personal laptop?
I'm new to programming. What are the general steps a web developer takes after he made a web app or static website using Django in a personal computer? I'm not asking for specifics cause probably is too long, but more general stuff that I can later research myself online. For example: Make a web app in Django. Buy a physical server. Install apache. Buy a domain name or hosting. Bear with me, I'm a noob so probably I listed nonsense, but just trying to ask how its supposed to ask here. For example, if I wanted to make a cake: Get a recipe. Gather the materials/ingredients. Mix ingredients. Place it in oven to bake. Take it out let it cool. Serve to people. I just need the correct path to take, not much the specifics on how to accomplish each path "station". Hope I asked well, thanks guys. -
'str' object has no attribute 'get' attribute error in django
This is the views.py class EditForm(forms.Form): content = forms.CharField(label="content",widget=forms.Textarea,required=True) def edit(request, title): if request.method == "POST": form = EditForm(request.POST) if form.is_valid(): content = form.cleaned_data["content"] util.save_entry(title, content) return render(request, "encyclopedia/page.html", { "title": title, "content": util.get_entry(title) }) else: content = util.get_entry(title) return render(request, "encyclopedia/edit.html", { "form":EditForm(content) }) This is urls.py path("wiki/<str:title>/edit", views.edit, name="edit") This is edit.html % extends "encyclopedia/layout.html" %} {% block title %} Edit {{ title }} {% endblock %} {% block body %} <form action="/wiki/{{ title }}/edit" method="post"> {% csrf_token %} {{ form }} <input type="submit"> </form> {% endblock %} i am getting 'str' object has no attribute 'get' attribute error when i go to the /title/edit route.I am new to django please be elaborate, thanks in advance. -
How to solve this payment to the right user problem
''' Problem description: We have two users objects created with a User class. Each user is a customer in our company. The users are able to send payments to us through their bank account but we don't have an ID for their bank account on record so we don't know which of them is sending us what money. If the two users send payments to us, with an optional memo field, how do we handle matching the payments to the right user? Please describe why you arrived at your solution. ''' How do I solve this problem. Can anyone help me with code ? class User: def __init__(self,first_name,last_name,email,phone): self.first_name = first_name self.last_name = last_name self.email = email self.phone = phone self.owes = 0 self.payments = [] def get_balance(self): total_paid = 0 for paid in self.payments: if "amount" in paid: total_paid += paid.get("amount") balance = self.owes - total_paid return balance user_a = User(first_name="Lionel",last_name="Messi",email="messi@gmail.com",phone="1111111111") user_a.owes = 56 user_b = User(first_name="Cristiano",last_name="Ronaldo",email="ronaldo@gmail.com",phone="2222222222") user_b.owes = 450 print(f"User A's name is {user_a.first_name} {user_a.last_name}, Balance is ${user_a.get_balance()}") print(f"User B's name is {user_b.first_name} {user_b.last_name}, Balance is ${user_b.owes}") print("\n") new_payment_1 = {"type":"Zelle","amount":300,"date":"05-07-2020","memo":"Cristiano Ronaldo 546432"} new_payment_2 = {"type":"Zelle","amount":450,"date":"05-07-2020","memo":""} -
Image upload error from React Form into Django ImageField
I want to update ImageField in my Django model and i am using axios PATCH method for it. Image comes from my Ant Design Form and i save it in my state. Why i cant update my image file as so? Should i format image file differently before sending it to backend? Error that occurs is 400 Bad request. My profile updating form: import React from "react"; import { Form, Input, Button, Select, message, Upload } from "antd"; import {connect} from 'react-redux'; import { UploadOutlined } from '@ant-design/icons'; import axios from "axios"; const FormItem = Form.Item; const { Option } = Select; const success = () => { message.success('Teie profiil on salvestatud edukalt, võite lehte uuendada'); }; class ProfileForm extends React.Component { state = { file: null, }; dummyRequest({ file, onSuccess }) { onSuccess("ok"); } constructor(props) { super(props) this.state = {sport: this.props.profile.sport}; this.handleChange = this.handleChange.bind(this); this.handleFormSubmit = this.handleFormSubmit.bind(this); } handleImageChange(file) { this.setState({ file: file }) console.log(file) }; handleChange(name, value) { this.setState({ [name]: value }); } handleFormSubmit = (event) => { const name = event.target.elements.name.value; const email = event.target.elements.email.value; const location = event.target.elements.location.value; const image = this.state.file.name; console.log(image); const sport = this.state.sport; axios.defaults.headers = { "Content-Type": "application/json", Authorization: this.props.token } const … -
How to parse serializer data in django rest framework
enter image description here I want to parse this so that i can get a list of phase id to run another query for specific reason. this is serializer.data Response. how to parse this to get a list of ids ? -
Django application: UserPassesTestMixin to verify user is the author of posts before allowing access to view?
The goal of my application is to allow users to create posts for their own private account viewing. I'm using a class based view to show the current logged in user their posts. In order to prevent users from being able to see other user's posts, I have a UserPassesTestMixin test_func that iterates through the query set and checks to make sure they are the author of those posts. The problem that I'm having is when there are no posts to display, I receive a 404 error code stating that there is nothing matching the query. I want it to still display the page even when there are no posts available. When I only use the get_queryset function, it works and displays my template without posts, but without having the UserPassesTestMixin and test_func, a user could enter another person's username into the URL and be able to view the other person's account/posts. Here is the code for this class based view in my views.py file: class UserSessionListView(LoginRequiredMixin, UserPassesTestMixin, ListView): model = session template_name = 'programmerjournal/user_sessions.html' context_object_name = 'sessions' paginate_by = 24 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return session.objects.filter(author=user).order_by('-date_added') def test_func(self): user = get_object_or_404(User, username=self.kwargs.get('username')) posts = get_list_or_404(session, author=user) for … -
How can I upload the image file with axios?
Do I need to change the model below to upload images to django restapi? function axmethod(url, method, options) { if (options !== undefined) { var {params = {}, data = {}} = options } else { params = data = {} } return new Promise((resolve, reject) => { const config = { } axios({ url, method, params, data, }).then(res => { resolve(res) }, res => { reject(res) }) }) } please help if i need to add? -
python - django - file descriptors not closing
I have standalone django program which runs a thread that runs every 5 seconds, reads data from DB using django querysey and publishes it to kafka. What is happening is that after certain period of time (3-4 days), I get below error File \"/usr/local/lib/python2.7/dist-packages/kafka/conn.py\", line 239, in recv readable, _, _ = select([self._sock], [], [], timeout) ValueError: filedescriptor out of range in select()", After debugging I found that file descriptors on the system were exhausted. But I don't see any resource leak in the program. Standalone program: from g_notifications import process_once as g thread_event = Event() def process(obj, source, *args): try: while True: obj(*args) thread_event.wait(5) except Exception: thread_event.set() thread_event.clear() def main(): django.setup() thread_g = Thread(target=process, name='g', args=(g, 'g')) thread_g.start() Thread part: import socket from django.db import connection from notification.kafka_publish import KafkaPublisher from settings.common import KAFKA_TOPIC kafka_publisher_g = None def process_once(publisher_type=KafkaPublisher): global kafka_publisher_g try: socket.gethostbyname('mysql') except socket.error: return if kafka_publisher_g is None: kafka_publisher_g = publisher_type() try: notification_objects = list(Notification.objects.all().order_by('id')[:5]) except Exception as exc: log.exception("Unexpected error could not complete database query!") return finally: close_db_connection(connection) error_flag = _publish_notification_and_verify(notification_objects) if error_flag: kafka_publisher_g.close() kafka_publisher_g = None def _publish_notification_and_verify(notification_objects): global kafka_publisher_g error_flag = False for notification_object in notification_objects: message = notification_object.notification_data try: response = kafka_publisher_g.publish(bytes(message)) if … -
How do I create add a domain's configuration file to /etc/apache2/sites-available/ in Apache2?
I'm trying to point a domain (example.com) to an IP address where I have a working website built with Linode and Django. I don't want to change GoDaddy's nameservers (I purchased the domain from GoDaddy), and I was looking for example.com.conf in my /etc/apache2/sites-available/, but I could not find it. How do I get example.com.conf? -
Unable to host in heroku do to excessive errors
I have been trying to host in Heroku for the last week and can't figure out the problem I am facing! The app is deployed and built successfully but when I open the URL it says "Application Error" Then when I run heroku logs I was given with this... 2020-08-21T16:21:04.049609+00:00 app[web.1]: raise HaltServer(reason, self.WORKER_BOOT_ERROR) 2020-08-21T16:21:04.049638+00:00 app[web.1]: gunicorn.errors.HaltServer: <HaltServer 'Worker failed to boot.' 3> 2020-08-21T16:21:04.136860+00:00 heroku[web.1]: Process exited with status 1 2020-08-21T16:21:04.175715+00:00 heroku[web.1]: State changed from up to crashed 2020-08-21T16:21:11.000000+00:00 app[api]: Build succeeded 2020-08-21T16:25:25.745203+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=kti-bylimra.herokuapp.com request_id=920d0650-de28-4b2f-928d-6a97a46fc0db fwd="112.135.197.200" dyno= connect= service= status=503 bytes= protocol=http 2020-08-21T16:25:27.248826+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=kti-bylimra.herokuapp.com request_id=3be3c388-44d4-4481-891a-4ccc8ed79c85 fwd="112.135.197.200" dyno= connect= service= status=503 bytes= protocol=http 2020-08-21T16:25:37.977206+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=kti-bylimra.herokuapp.com request_id=b8ea34c4-2625-47c2-842f-256d727e48de fwd="112.135.197.200" dyno= connect= service= status=503 bytes= protocol=http 2020-08-21T16:25:38.166373+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=kti-bylimra.herokuapp.com request_id=f095f479-6ec5-4f22-ac97-0d3e499ebc2c fwd="112.135.197.200" dyno= connect= service= status=503 bytes= protocol=http 2020-08-21T16:25:38.926833+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=kti-bylimra.herokuapp.com request_id=99979365-e018-47f7-9167-2594b7c3eaa9 fwd="112.135.197.200" dyno= connect= service= status=503 bytes= protocol=http 2020-08-21T16:26:00.656226+00:00 app[api]: Starting process with command `python manage.py migrate` by user najaaznabhan@gmail.com 2020-08-21T16:26:12.645457+00:00 heroku[run.1617]: State changed from starting to up 2020-08-21T16:26:12.745856+00:00 heroku[run.1617]: Awaiting client 2020-08-21T16:26:12.766309+00:00 heroku[run.1617]: Starting process with command `python manage.py migrate` …