Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to resolove an Intergration between ReactJS and Django
Hey so I am trying to fetch data from my Django API using React so to render into my front-end so I do not know where my implementation could be wrong(The fetching of the data from React to Django) So everything on the backend is all set ready for the front-end to do its work. This is the error message that I am getting: TypeError: videos.map is not a function Summary of build: So I am trying to build a web app where I can post videos in etcetra Code Below: Video.js class Videos extends Component{ constructor(props){ super(props); this.state = { ListVideos:[], newVideo:{ lecturer: '', module : '', video : null, date : Date.now() } } this.fetcVideos = this.fetcVideos.bind(this) } componentWillMount(){ this.fetcVideos() } fetcVideos(){ fetch('http://127.0.0.1:8000/api/lecture-video-list/').then(response => response.json).then(data => this.setState({ ListVideos:data })) } render(){ return( <VideoList listVideos={this.state.ListVideos}/> ) } } export default Videos; Code Below: VideoList.js const VideoList = (props) =>{ let videos = props.listVideos return( <div> {videos.map(video =>{ return( <div key={video.id}> <h3>{video.lecturer}</h3> <h4>{video.module}</h4> </div> ) })} </div> ) } export default VideoList -
Celery looking for database called "db" running on docker
Getting the following error: celeryworker_1 | django.db.utils.OperationalError: could not translate host name "db" to address: No address associated with hostname And also: celerybeat_1 | django.db.utils.OperationalError: could not translate host name "db" to address: No address associated with hostname Weird because my DB is not called "db", I don't get why they are looking for "db". celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'pyrty.settings') app = Celery('pyrty') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) docker-compose.yml: version: '3' volumes: local_postgres_data: {} services: postgres: image: postgres environment: - POSTGRES_DB=postgres - POSTGRES_USER=postgres - POSTGRES_PASSWORD=postgres volumes: - local_postgres_data:/var/lib/postgresql/data env_file: - ./.envs/.postgres django: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/app/ ports: - "8000:8000" depends_on: - postgres rabbitmq: image: rabbitmq:3.8.6 celeryworker: image: celeryworker restart: always depends_on: - rabbitmq - postgres command: celery -A pyrty worker -l INFO celerybeat: image: celerybeat restart: always depends_on: - rabbitmq - postgres command: celery -A pyrty beat -l INFO Dockerfile: FROM python:3.8.5-alpine ENV PYTHONUNBUFFERED 1 RUN apk update \ #psycopg2 dependencies && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ # Pillow dependencies && apk add jpeg-dev zlib-dev freetype-dev lcms2-dev openjpeg-dev tiff-dev tk-dev tcl-dev \ # CFFI … -
How to run migrate(django) when DB is on different host
We recently moved our MYSQL DB to different host, while python manage runserver works fine as I have below setting: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_qa', 'USER': 'qa', 'PASSWORD': os.environ.get('PASSWORD'), 'HOST': os.environ.get('HOST') } } But when I have to run migrate it is still looking for localhost. We have our release system which uses manifest files. Not sure how to include in manifest file? Any one ran through this? are there any other options? Is setting Jenkins job to run migrate right way of doing this? Before we were having DB on same host, migrate ran as part of debian post install package: manage.py collectstatic -v0 --noinput -l --settings=web_settings.settings_prod manage.py migrate -
Assign to a python variable a file uploaded with a html button Using django
<form action="/external/" method="post"> {% csrf_token %} <ul class="actions special"> <li> <a> <input class="button primary" type="submit" value="Execute External Python Script"> </a> </li> <li> <a class="button"> <label for="choose-file" value="Choose a File" lang="en"><strong></strong> <input type="file" name="param" id="choose-file" class="inputfile" text="Choose a File" accept=".xlsx, .xls"required> </label> </a> </li> </ul> {{data_external}} </form> Hello Brothers ! I want, after retrieving an excel file from an html button, to assign it to a python variable for executing a python program from another button. I use django. By the way I have two buttons; one to get the excel file and a second one to execute the external .py program. Views.py from django.shortcuts import render from django.http import HttpResponse from django.shortcuts import render import requests import sys from subprocess import run,PIPE from django.core.files.storage import FileSystemStorage def home(request): return HttpResponse(""" <h1>Bienvenue sur mon blog !</h1> <p></p> """) def index(request): return render(request, 'index.html') def external(request): inp= request.POST.get('param') out= run([sys.executable,'C://Users//acer//Desktop//Django//appweb//optimisation_itinineraire.py',inp],shell=False,stdout=PIPE) print(out) return render(request,'index.html',{'data1':out.stdout}) urls.py from django.urls import path from . import views urlpatterns = [ path('accueil/', views.home), path('index/', views.index, name='sites/index') ] -
Django forms: Update a user's attributes without changing username
I'm trying to create a form that allows a user to update their username or avatar. The problem that I am running into is that if I update the profile picture without changing the username, the django form validation if form.is_valid() will recognize the form as invalid, since the username already exists in the database. I'm using an update view, though I'm not sure I've implemented it correctly. When I try to update the avatar without changing the username, I get a page that says "Form is invalid" from the line: HttpResponse("Form is invalid"). Is there a workaround to remove the form validation? I have tried removing if form.is_valid(): but received the error 'User_form' object has no attribute 'cleaned_data'. I feel like there has to be an easy way around this that I have not been able to find, as so many sites allow you to update only one attribute at a time. Views.py model = User form = User_form fields = ['username', 'avatar'] template_name_suffix = '_update_form' def update_profile(request, user_id): if request.method == "POST": form = User_form(request.POST, request.FILES) if form.is_valid(): user = User.objects.get(pk=user_id) username = form.cleaned_data['username'] avatar = form.cleaned_data['avatar'] if username != user.username: user.username = username if avatar != user.avatar: … -
Jquery validation skipping invalid input
I'm moving my HTML/JS over to Django and using it's validation forms. However, I still want to use Jquery's for certain things like making sure an answer is inputted before the div is hidden. Jquery validate used to work but I broke it transitioning to Django, possibly from using the input tags to create my inputs? I use an onclick to validate instead of submit by the way. Anyway, here is the JS: $(document).ready(function() { var validater = $("#cc_form").validate({ rules: { pt_cc : { required: true, minlength: 3, }, }, messages: { pt_cc: "Please enter an answer", }, errorPlacement: function(error, element) { if (element.attr("name") == "pt_cc") { error.appendTo("#cc_error")} else { error.insertAfter(element);}}, onfocusout: false, invalidHandler: function(form, validater) { var errors = validater.numberOfInvalids(); if (errors) { validater.errorList[0].element.focus();} }});}); function sendto() { if ($("#cc_form").valid()) { console.log('valid');} else {return false};} And the rendered HTML, after Django does its thing: <form id='cc_form' name="contentForm" role="form" data-toggle="validator"> <div style='display:none; background-color:white' class="jumbotron shadow-lg text-center mb-4 mx-5" id=somethingelse_page> <h3>In 5 words or so, try to describe your problem.</h3><hr> <div class="d-flex align-items-center mx-auto input-group mb-2"> <div class="input-group mb-2 col-md-6 mx-auto"> <input type="text" name="pt_cc" placeholder="For example: &quot;I can't sleeep at all&quot;" class="form-control" id="something_else_cc_answer" maxlength="75" required=""> </div> </div> <div id='sub_1' class='row'> <input … -
Django Rest Framework - Render image from URL
Can anyone point me in the right direction. I am trying to learn how to build an Django image API. I want to be able to serve images onto my website from a API URL. So for example I would write img src="http://linktoapi" and it would show the image. Any code tips or links to where I might read more about how i could do this would be most appreciated. -
Save timezone aware datetime with its timezone
I'm looking for a way to save datetimes with a specific timezone other than the established timezone, however I have the following settings: TIME_ZONE = "UTC" USE_TZ = True This is convenient, since for the most part I want dates to be saved in UTC, however sometimes I need to keep track of the local datetimes the user setup. Anyone has any idea how to save a datetime without being converted to the default timezone (UTC)? I am using PostgreSQL, so I don't know if this is possible... Any tips are welcome. -
Can't upload file to Django with file field
I am trying to create a form field for uploading a file to my django site. After I submit the form I am not seeing the file show up. forms.py: class UploadFileForm(forms.Form): file = forms.FileField() views.py: def csv(request): if request.method == 'POST': form = UploadFileForm(request.FILES) if form.is_valid(): with open(os.path.join(settings.BASE_DIR, 'dashboard/configfiles/input.csv'), 'wb+') as destination: for chunk in request.FILES['file'].chunks(): destination.write(chunk) context = {'form1': SpeciesForm, 'csv_field': UploadFileForm } return render(request, 'config/species.html', context) species.html: <h3>Upload File (.txt, .csv):</h3> <form method="POST" action="species-csv" enctype="multipart/form-data"> {% csrf_token %} {{ csv_field }} <button type="submit">Upload</button> </form> -
React/Redux app not working unless chrome developer tools open?
Pretty much in the title. For some reason things like my redux actions and click handlers only fire reliably when my developer tools are open. I have no idea why this could be happening. It is extremely frustrating. Tested on Firefox and it works perfectly fine. Anybody have any idea why is happening? -
Links from Django Template not redirecting properly
I am having this issue when I click on a link from my template, it appends to the url instead of going to the intended link. Please any idea, how I can solve it. Attached are images to get a better understanding of my problem. This is the url I clicked on (cnn.com) Returns this The template -
Why can't I login using Django allauth?
I have a Django project, in which I used django-allauth to administer users, logins and such. The code shows no errors, but when I try to log in, it says the username or password is wrong. I create different users to test (directly inserting into the database), and the same happens. There are no PASSWORD_HASHERS and I haven't changed anything related to them, my login view is this: {% extends "account/base.html" %} {% load i18n %} {% load bootstrap3 %} {% load account socialaccount %} {% block head_title %}{% trans "Sign In" %}{% endblock %} {% block inner-content %} {% if messages %} <div class="row"> <div class="col-md-12"> <div class="messages"> {% for message in messages %} <div {% if message.tags %} class="alert alert-{{ message.tags }}"{% endif %}> <button type="button" class="close" data-dismiss="alert"><span aria-hidden="true">&times;</span><span class="sr-only">Cerrar</span> </button> {{ message|safe }} </div> {% endfor %} </div> </div> </div> {% endif %} <form class="login mb-lg" method="POST" action="{% url 'account_login' %}"> {% csrf_token %} {% bootstrap_form form %} {% if redirect_field_value %} <input type="hidden" name="{{ redirect_field_name }}" value="{{ redirect_field_value }}" /> {% endif %} <div class="clearfix"> </div> <button type="submit" class="btn btn-block btn-primary mt-lg">{% trans "Sign In" %}</button> </form> {% endblock inner-content %} And account/base.html is this: {% … -
Heroku Django application only working locally
I'm trynig to launch my application into production and I decided to use Heroku to host my app. I had a lot of problems and had to make some changes, but I finally got my app running. Once I finally got it to run and show the login screen, when I try to log in I get the following error: ('01000', "[01000] [unixODBC][Driver Manager]Can't open lib 'ODBC Driver 17 for SQL Server' : file not found (0) (SQLDriverConnect)") I just ran the app locally and it is working correctly. I really don't know what to do at this point. I am using azure active directory with password for database. This is what one of my connections look like: conn = pyodbc.connect('''Driver={ODBC Driver 17 for SQL Server}; Server=tcp:servername.database.windows.net,1433; Database=Reconciliation; Uid=mymail@mymail.net; Pwd=secresPass; Encrypt=yes; TrustServerCertificate=no; Connection Timeout=30; Authentication=ActiveDirectoryPassword; ''') -
Email Verification not working [Errno 111] Connection refused
I'm messing around with this e-commerce site from github https://github.com/justdjango/django-ecommerce When I try to register a new user and enter an email I get ConnectionRefusedError. I've been trying to figure out how to configure email verification with Django but all the tutorials I found you have to add the code in the settings.py file which this github does not have so I'm not sure how to fix this. Sorry if this is a stupid question i'm quite new to programming. File "/mnt/c/Users/1/Desktop/Index/Coding/14/django-ecommerce/env/lib/python3.8/site-packages/django/core/mail/message.py", line 291, in send return self.get_connection(fail_silently).send_messages([self]) File "/mnt/c/Users/1/Desktop/Index/Coding/14/django-ecommerce/env/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 103, in send_messages new_conn_created = self.open() File "/mnt/c/Users/1/Desktop/Index/Coding/14/django-ecommerce/env/lib/python3.8/site-packages/django/core/mail/backends/smtp.py", line 63, in open self.connection = self.connection_class(self.host, self.port, **connection_params) File "/usr/lib/python3.8/smtplib.py", line 253, in __init__ (code, msg) = self.connect(host, port) File "/usr/lib/python3.8/smtplib.py", line 339, in connect self.sock = self._get_socket(host, port, self.timeout) File "/usr/lib/python3.8/smtplib.py", line 308, in _get_socket return socket.create_connection((host, port), timeout, File "/usr/lib/python3.8/socket.py", line 808, in create_connection raise err File "/usr/lib/python3.8/socket.py", line 796, in create_connection sock.connect(sa) ConnectionRefusedError: [Errno 111] Connection refused [13/Aug/2020 21:46:00] "POST /accounts/signup/ HTTP/1.1" 500 186279 -
Django queryset return values that don't match
I am building a viewset that takes in zip codes and attempts to match them to my database (Postgresql). Finding the matches is no problem, but I'm curious about the best way to return the values that have no matches in the DB. class Location(models.Model): name = models.CharField(max_length=255) code = models.CharField(max_length=255) I want it to give me back what it can't find in this query. locations = ['77449', '11368', '60629', '99999'] valid_locations = Location.objects.filter(code__in=locations).distinct() Is there a method I missed that gives me back any locations that don't match my filter - in this case 99999? -
Manual webapp in pythonanywhere.com using python3.8 and django3.1
Background I have a free account at pythonanywhere.com. My thanks to them for providing this very nice free service and learning experience. To the PythonAnywhere folks who encourage me to use StackOverflow for questions about their site, I'll first say that I really like what you all have done with that site, and I'm excited to start building something there myself. I've already done the first tutorial within pythonanywhere.com with Flask and a second simple webapp (that I adapted from your first tutorial) exactly the same but using your built-in django 2.2 in place of Flask. Now I'm trying a tutorial from another site using python 3.8 and django 3.1. I'm following along in Chapter 2 of the djangoforbeginners.com site (helloworld app) and trying to implement instructions there in my pythonanywhere.com account. I know I need to adapt some of the djangoforbeginners.com instructions to fit the pythonanywhere.com environment (e.g. pipenv didn't work, but pip install django~=3.1.0 did work). (This is not my main question, but an example of the problems I expect to encounter adapting a tutorial from another site to the pythonanywhere.com environment) I encountered a problem with the python manage.py runserver step: When I run the code above, … -
How do I start the Django project
I'm attempting to use Django in my Web Programming class, and I'm having issues with the setup. My goal is to have a running default Django app, but, upon running python manage.py runserver, I get this syntax error for the default code: File "manage.py", line 17 ) from exc ^ SyntaxError: invalid syntax I also tried running it on python3, which produced a different error. See below: Traceback (most recent call last): File "manage.py", line 11, in main from django.core.management import execute_from_command_line ModuleNotFoundError: No module named 'django' The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 17, in main ) from exc ImportError: Couldn't import Django. Are you sure it's installed and available on your PYTHONPATH environment variable? Did you forget to activate a virtual environment? I have Django installed via pip, and can use the django-admin command. My exact code can be created by running django-admin startproject [name of project]. All the best, Ben -
Python/Django - How to dump variable for user and exit script (equivalent to PHP "var_dump die")
I'm pretty new to the Python/Django world and I need to dump some variables (right after model calling) and display all the informations about that specific variable to the user (the developer, in my case, me). In PHP we are used to do "var_dump($some_var); die;" But in my case, I can't find a way to achieve just that, and I'm pretty sure that's simple because obviously every django/python developer are able to do that ! -
Committing Django private keys in portfolios is a problem?
I new at Django and created an e-commerce website just for portfolio purpose(I will not use it for sell anything real, at most i going to host it in some domain to show as a portfolio) and committed it in a public Github repository, then Github sent me an email telling me i committed the secret keys of Django, is there any problem with this? Do i need to delete the repository and generate another Secret Key? -
Watchlist system on django
I want to know how to create a whatchlist on django, it could be like a function to select favourite objects as well. This is the code I've so far models.py class Watchlist(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE, default=1) object = models.ForeignKey(Object, on_delete=models.CASCADE) views.py def watchlist(request): return render(request, "auctions/watchlist.html", { "watchlists": Watchlist.objects.all() }) I didn't start html yet My idea it's to put an add button where if the user doesn't have the auction listing on his watchlist, and a remove button if it has the object on the watchlist. could anyone help me to finish it, thanks. -
Getting a value from 'checkbox-input' in django
I have a function in js that renders me a list of institutions into HTML like: for (var [key, value] of Object.entries(institutionsByName)){ '<label name="organization_label">' + '<input type="radio" name="organization" value="' + value + '" id="institution-key"/>' + '<span class="checkbox radio"></span>' + '<span class="description">' + '<div class="title">'+ key + '</div>' + '<div class="subtitle">' + '</div>' + '</span>' + '</label>' } The question is, how can i get the value of checked checkbox from this piece of HTML? I've tried sth like request.POST.get("institution-key) but it returned me nothing. -
How to generate skype video Link from django python backend and send the meeting link to user via email?
Is there any API for creating a new video meeting in Skype ? I want to do something similar using API using python -
Is it possible to create an executable from my django project with connection to a mysql database?
i'm new in python, i would like create an executable-installer of my django project, i would like that my client with double-click runs this program and open his browser with my project running on his local server, and that he can access to mysql database, Thanks. I've searched on internet about python to exe scripts, PyInstaller, but I can't find how to run the server and connect to the database in an executable. -
Django Admin - Rename "view on site" link
I'm using Django 3 to make a simple catalog. I'm using Admin site right now and I have (I think) a very basic question. I want to rename the "view on site" link to e.g. "More info". I searched for this without success. Thanks! Example: To: -
django how to get image filaname hosted on S3?
in models i am making thumbnail from uploaded image and want to save into different folder with the same name: class Ad(models.Model): title = models.CharField(max_length=100) slug = models.SlugField(max_length=100) price = models.DecimalField(max_digits=10, decimal_places=2) description = models.TextField() phone_number = models.CharField date_posted = models.DateTimeField(default=timezone.now) author = models.ForeignKey(User, on_delete=models.CASCADE) image = models.ImageField( default='ad_images/default.png', upload_to='ad_images') thumbnail = models.ImageField( default='ad_thumbnails/default.png', upload_to='ad_thumbnails') # options of the model class Meta: ordering = ['-date_posted'] # this is how the object to be displayed def __str__(self): return self.title def get_absolute_url(self): return reverse('ad-details', kwargs={'pk': self.pk, 'slug': self.slug}) def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(self.title) super().save(*args, **kwargs) img = Image.open(self.image.path) output_size = (500, 500) img.thumbnail(output_size, Image.ANTIALIAS) thumb_io = BytesIO() img.save(thumb_io, 'JPEG', quality=100, subsampling=0) # chose same name as original image name = os.path.basename(self.image.name) # save=False in order not to call super().save() again and again.. self.thumbnail.save(name, File(thumb_io), save=False) super().save(*args, **kwargs) But S3 doesnt have os.path of course. Current self.image.name is ad_images/kokokok.jpg. So, if you know the regex to get string after the last / or any other method? Is there any way to get filename of an image?