Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Pillow not found after building wheels
I am running django project on docker which runs fine but I setup a production environment which installs pip packages from built wheels. but now am getting error trying to run migration am getting: "(fields.E210) Cannot use ImageField because Pillow is not installed. HINT: Get Pillow at https://pypi.org/project/Pillow/ or run command "python -m pip install Pillow" Here is my dockerfile # BUILDER # ########### # pull official base image FROM python:3.8.3-alpine as builder # set work directory WORKDIR /usr/src/app # set environment variables ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 # install system dependencies RUN apk update \ && apk add gcc musl-dev postgresql-dev zlib \ python3-dev jpeg-dev zlib-dev openssl-dev libffi libffi-dev # lint RUN pip install --upgrade pip RUN pip install flake8 COPY . . RUN flake8 --ignore=E501,F401,E731,E722,F403,F405 . # install dependencies COPY ./requirements.txt . RUN pip wheel --no-cache-dir --no-deps --wheel-dir /usr/src/app/wheels -r requirements.txt ######### # FINAL # ######### # pull official base image FROM python:3.8.3-alpine # create directory for the app user RUN mkdir -p /home/app # create the app user RUN addgroup -S app && adduser -S app -G app # create the appropriate directories ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $APP_HOME WORKDIR $APP_HOME # install dependencies RUN … -
CSV file import-Django(Only 1 row of data is getting imported)
I am trying to upload CSV file content to database but observed that only first row of data is getting updated and also if data with same value present then it's simply ignoring. And also can we use open with logic so that once task is completed it should get close automatically. My Views.py import csv, io from django.shortcuts import render from django.contrib import messages # Create your views here. # one parameter named request def contact_upload(request): # declaring template template = "testapp/upload.html" data = Movie.objects.all() # prompt is a context variable that can have different values depending on their context prompt = { 'order': 'Order of the CSV should be releasedate, moviename, hero, heroine, rating', 'profiles': data } # GET request returns the value of the data with the specified key. if request.method == "GET": return render(request, template, prompt) csv_file = request.FILES['file'] # let's check if it is a csv file if not csv_file.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') data_set = csv_file.read().decode('UTF-8') print(data_set) io_string = io.StringIO(data_set) next(io_string) # setup a stream which is when we loop through each line we are able to handle a data in a stream for column in csv.reader(io_string, delimiter=',', quotechar="|"): _, created … -
Django Project is not getting displayed/created
I am using virtual environment to create a django project. On running "django-admin startproject tutorials", command is getting executed successfully, but project is not yet created. On running the same command("django-admin startproject tutorials") again. it is throwing error as CommandError: 'C:\Users\abhinavkumar\Documents\mysql.python\tutorials' already exists. While doing dir I can see that tutorials is not present. Directory of C:\Users\abhinavkumar\Documents\mysql.python 30-09-2020 17:50 <DIR> . 30-09-2020 17:50 <DIR> .. 28-09-2020 10:36 <DIR> database 16-09-2020 12:08 <DIR> venv 04-09-2020 17:01 <DIR> __pycache__ 0 File(s) 0 bytes 5 Dir(s) 865,337,741,312 bytes free -
Django CMS - Content only shown if on /?edit and logged in?
Hello there Django folks! I think there is some info I missed somewhere in the documentation, I have a project where I only can se the content if I am logged in. Perhaps it's a setting somewhere, anyone have a clue where I should look for answers? -
Radio button doesnt appear on my default DjangoModelform. I cant find the issue?
This is my model where I want my Gender field to appear as radio button. class Passenger(models.Model): # book_id = models.OneToOneField(Booking, # on_delete = models.CASCADE, primary_key = True) First_name = models.CharField(max_length=200, unique=True) Last_name = models.CharField(max_length=200, unique=True) Nationality = models.CharField(max_length=200, unique=True) Passport_No = models.CharField(max_length=200, unique=True) Passport_Exp_Date = models.DateField(blank=False) Contact_Number = models.CharField(max_length=200, unique=True) Email = models.EmailField(max_length=200, unique=True) Customer_id = models.CharField(max_length=50) Gender = models.CharField(max_length=50) This is my Passenger form. class PassengerForm(forms.ModelForm): Passport_Exp_Date = forms.DateField(widget=forms.widgets.DateInput(attrs={'type': 'date'})) CHOICES = [('M', 'Male'), ('F', 'Female'), ('O', 'Others')] Gender = forms.ChoiceField(choices=CHOICES, widget=forms.RadioSelect) class Meta: model= Passenger fields = '__all__' -
Image upload above 1 mb gives 500 server error django on app engine
I have been trying to upload images on my website but it shows 500 server error on uploading large files how can I solve this issue. Can anyone link a tutorial or solution to this issue? Thanks in advance -
The current path, <code>hooktest/</code>, didn't match any of these
I have an django project whith single app and I am trying to configure URL path but can't. My project structure is: -- 05 #parent directory -- env #virtualenv -- tools #django project located directory which was created by django-admin manage.py -- tools __init__ urls.py settings.py etc -- webhooks #here is my app __init__.py urls.py views. py etc In my tools/urls.py the following instructions from django.contrib import admin from django.urls import path, include from webhooks.views import hook_receiver_view urlpatterns = [ path('admin/', admin.site.urls), path('hooktest/',hook_receiver_view,name='hook'), ] My webhooks/views.py contain from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.http import require_http_methods @require_http_methods(["GET","POST"]) def hook_receiver_view(request): return HttpResponse('success') While I am trying to access url specified in tools/urls .py by curl http://example.com/hooktest/ It's return me the following error <p> Using the URLconf defined in <code>tools.urls</code>, Django tried these URL patterns, in this order: </p> <li> admin/ </li> <p> The current path, <code>hooktest/</code>, didn't match any of these. What I am doing wrong. Anyone guide me. Thanks in advance -
Django Template - Value Iteration
I am using following code to calculate total price for each item in shopping cart. How should I calculate grand total for whole cart - sum of each "total" from code below? I did read docs (Built-in template tags and filters) but didn't managed to figure it out. {% for key,value in request.session.cart.items %} Total {{ value.price|multiply:value.quantity }} {% endfor %} -
How to manage multiple device login with django rest framework?
So I have an app in which I previously managed login logout with access tokens. When login, an access token will be generated and it will be sent to FE. Access token will be stored in FE (Front end) and it will define if the user is logged in or not. When the user logs out, access token will be deleted from both FE and BE (Back-end database). In this scenario, logging in with the same account in multiple devices is not possible and also had other issues. Now I want to add multiple device login and some other features. So far I have thought of providing a maintaining a refresh token and access token in the database. The expiration of access token and refresh token will be around 5 minutes and 1 month respectively. When access token will expire during user is logged in, it will check if the refresh token is valid and if valid, new access token will be generated. Access token and refresh token both will remain after logging out to allow multiple device login. But I am not satisfied with this idea and I think there are some best practices and tools that I can … -
Use django models in an external .py file
I am trying to make a telegram bot that needs access to a database of a django app. I want to avoid making webservices in views.py to manage content because I don't want to make an API an just want to keep things separated by the moment, so I need to access to the django ORM in the telegram bot. I have imported the models in my bot main file but I get this message: File "C:\Python37-32\lib\site-packages\django\apps\registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. Once I get this message, I add the app to settings adding this line to the INSTALLED_APPS variable: 'localadmin.apps.BotConfig' and the next lines in the apps.py file: class BotConfig(AppConfig): name = 'localadmin.bot' Having in mind that there's a folder called "bot" which have the main.py file that launches the bot. So, I think, everything was in order, but, with this changes, I get the next error message. File "C:\Python37-32\lib\site-packages\django\apps\registry.py", line 135, in check_apps_ready raise AppRegistryNotReady("Apps aren't loaded yet.") django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. So I guess my problem, is that I need to use a proper django app to use the models, but I can't do this, due that … -
Twilio with Django - Capturing Call SID
I am trying to implement Twilio with Django. I have followed and implemented this tutorial and it works fine. I've then rolled this into my project and calls work fine. I need to capture to call SID from the Twilio SDK when the call is made so I can link it to records within the database. So I have this initial Javascript and when the call is disconnected for whatever reason I need to capture the call SID. /** * Twilio Client configuration for the browser-calls-django * example application. */ // Store some selectors for elements we'll reuse var callStatus = $("#call-status"); var answerButton = $(".answer-button"); //var callSupportButton = $(".call-support-button"); var hangUpButton = $(".hangup-button"); var callCustomerButtons = $(".call-customer-button"); var device; /* Helper function to update the call status bar */ function updateCallStatus(status) { callStatus.attr('placeholder', status); } console.log("Requesting Access Token..."); $(document).ready(function() { $.get("/support/token", {forPage: window.location.pathname}) .then(function(data) { // Setup Twilio.Device device = new Twilio.Device(data.token, { // Set Opus as our preferred codec. Opus generally performs better, requiring less bandwidth and // providing better audio quality in restrained network conditions. Opus will be default in 2.0. codecPreferences: ["opus", "pcmu"], // Use fake DTMF tones client-side. Real tones are still sent to the … -
Django/Docker-compose: Retry Database Connection when: django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)")
This question have been asked here: django.db.utils.OperationalError: (2002, "Can't connect to MySQL server on 'db' (115)") and the answer has been to wait for the database to be ready. However, the official documentation here: https://docs.docker.com/compose/startup-order/ suggests that instead an in app retry method is implemented in order to retry the database connection when this fails. To handle this, design your application to attempt to re-establish a connection to the database after a failure. If the application retries the connection, it can eventually connect to the database. The best solution is to perform this check in your application code, both at startup and whenever a connection is lost for any reason. Unfortunately, the documentation just ends there and does not provide any examples or guides on how to implement this retry method. Does anyone knows how to do that in a clean way? -
Django orm query to count all the results returned and add to the queryset with other annotations, but not use group by
This should be the sql of django orm query select 0 'bucket_id', 'Incomplete' as 'name', count(*) 'user_count' from UserSr where job = 1 and pred_perf is null here is what i tried but it does group_by and returns multiple results UserSr.objects.filter(job=job_id, pred_perf__isnull=True).annotate(bucket_id=Value(0, IntegerField()),name=Value('Incomplete', output_field=CharField()),entry_count=Count('*')) -
ERROR django-softdelete: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output
I am trying to download django-softdelete~=0.9.1 on a different (windows) device than I usually use through pip. However when run I get the error ERROR: Command errored out with exit status 1: command: 'c:\users\pelizzy\appdata\local\programs\python\python38-32\python.exe' -c 'im port sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\PelizzY\\AppData\\Local\\Temp\ \pip-install-32uur6be\\django-softdelete\\setup.py'"'"'; __file__='"'"'C:\\Users\\PelizzY\\A ppData\\Local\\Temp\\pip-install-32uur6be\\django-softdelete\\setup.py'"'"';f=getattr(tokeni ze, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.cl ose();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base 'C:\Users\PelizzY\A ppData\Local\Temp\pip-pip-egg-info-_tq6m_l3' cwd: C:\Users\PelizzY\AppData\Local\Temp\pip-install-32uur6be\django-softdelete\ Complete output (44 lines): WARNING: The wheel package is not available. ERROR: Command errored out with exit status 1: command: 'c:\users\pelizzy\appdata\local\programs\python\python38-32\python.exe' -u - c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\PelizzY\\AppData\\Local\\ Temp\\pip-wheel-300gjngn\\setuptools-hg\\setup.py'"'"'; __file__='"'"'C:\\Users\\PelizzY\\Ap pData\\Local\\Temp\\pip-wheel-300gjngn\\setuptools-hg\\setup.py'"'"';f=getattr(tokenize, '"' "'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();e xec(compile(code, __file__, '"'"'exec'"'"'))' bdist_wheel -d 'C:\Users\PelizzY\AppData\Local \Temp\pip-wheel-3w4e_e8i' cwd: C:\Users\PelizzY\AppData\Local\Temp\pip-wheel-300gjngn\setuptools-hg\ Complete output (6 lines): usage: setup.py [global_opts] cmd1 [cmd1_opts] [cmd2 [cmd2_opts] ...] or: setup.py --help [cmd1 cmd2 ...] or: setup.py --help-commands or: setup.py cmd --help error: invalid command 'bdist_wheel' ---------------------------------------- ERROR: Failed building wheel for setuptools-hg ERROR: Failed to build one or more wheels Traceback (most recent call last): File "c:\users\pelizzy\appdata\local\programs\python\python38-32\lib\site-packages\set uptools\installer.py", line 126, in fetch_build_egg subprocess.check_call(cmd) File "c:\users\pelizzy\appdata\local\programs\python\python38-32\lib\subprocess.py", l ine 364, in check_call raise CalledProcessError(retcode, cmd) subprocess.CalledProcessError: Command '['c:\\users\\pelizzy\\appdata\\local\\programs\\ python\\python38-32\\python.exe', '-m', 'pip', '--disable-pip-version-check', 'wheel', '--no -deps', '-w', 'C:\\Users\\PelizzY\\AppData\\Local\\Temp\\tmp2i04c4ia', '--quiet', 'setuptool s_hg']' returned non-zero exit status 1. The above exception was the direct cause … -
No module named django-admin
I have using virtual environment to create a django project. I have freshly installed django and python to create a project. but facing an error to create a project. I guess the screenshot may help you the understand my question.enter image description here . (venv) C:\Users\abhinavkumar\Documents\mysql.python>django-admin startproject tutorials (venv) C:\Users\abhinavkumar\Documents\mysql.python>python -m django-admin C:\Users\abhinavkumar\Documents\mysql.python\venv\Scripts\python.exe: No module named django-admin. Project didn't get created whereas after "python -m django-admin". it is showing an error as module django-admin not found. -
Django, upload two files on one page
model.py: class InJPG(models.Model): file_path = models.FileField(upload_to="media",unique=True) views.py from model import InJPG def get_name(request): file1=InJPG(request.POST or None) file2=InJPG(request.POST or None) if file1.is_valid(): file1.save() if file2.is_valid(): file2.save() return render(request,'files.html',{'file1':file1,'file2':file2}) files.html ... {% block page %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{file1}} <button type="submit">upload file1</button> </form> <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{file2}} <button type="submit">upload file2</button> </form> {% endblock %} I have web page, where I can upload two files file1 and file2 problem: I can load one file at once only, page is refreshing when I am uploading first file. I want to Load both files using one button. or two load buttons without refreshing second form. I am using two forms because i want to separate webpage and use there card classes -
Passing different URL parameters to AJAX function in Django
How to pass the different URL names to the javascript function. Here are my HTML and Javascript code. {% for profile, g_name in group_list %} <li class="contact"> <div class="wrap"> <img src="{{profile}}" alt="No image" /> <div class="meta"> <input type="hidden" id="myGroup" name="myGroup" value="{{g_name}}"> <button onclick="GetMessages()"> <p class="name">{{g_name}}</p> </button> </div> </div> </li> {% endfor %} <script> function GetMessages() { var myGroup = document.getElementById('myGroup').value; $('.ajaxProgress').show(); $.ajax({ type: "GET", url: "/getmsgs/"+myGroup, success: function(response){ $("#display").empty(); ... }, error: function(response){ alert("No Data Found"); } }); } </script> and this is my URL path('getmsgs/<str:word>/', views.groupmsgs_ajax, name='groupmsgs_ajax'), when I try the above method I am getting the first 'myGroup' id value. it is passing the first group name by default. I am not able to call other group names. Thank you for any help -
Django: Can't redirect to home page after login
I'm developing simple user authentication with a gorgeous frontend. It has only one app 'account'. under the app I created a 'registerPage' view and the register process working fine. But for login I'm using default view from django.contrib.auth. Problem is, after giving the email & password to login it should be redirect to home page, but remains in the same login page account/views: from django.shortcuts import render, redirect from django.contrib.auth.forms import UserCreationForm, AuthenticationForm from django.contrib.auth import authenticate, login, logout from django.contrib import messages from django.contrib.auth.decorators import login_required # views here... from .models import * from .forms import CreateUserForm def registerPage(request): if request.method == 'POST': form = CreateUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account was created for ' + user) return redirect('login') else: form = CreateUserForm() context = {'form':form} return render(request, 'account/register.html', context) def logoutPage(request): logout(request) return redirect('login') @login_required def homePage(request): context = {} return render(request, 'account/home.html', context) account/urls: from django.urls import path from . import views urlpatterns = [ path('', views.homePage, name="home"), path('register/', views.registerPage, name="register"), # path('login/', views.loginPage, name="login"), ] login.html: main body <main class="login-body" data-vide-bg="{% static 'img/login-bg.mp4' %}"> <!-- Login Admin --> <form class="form-signin" action="" method="POST"> {% csrf_token %} <div class="login-form"> <!-- logo-login --> <div class="logo-login"> <a … -
Django check if username starts with a special character and change it to authenticate with changed username
Here's my custom auth backend. I want to check if username starts with a certain character and change this character to the new string or character. class PhoneAuthBackend(object): def authenticate(self, request, username=None, password=None): try: user = User.objects.get(username=username) if username.startswith('8'): username[0].replace('+7') if user.check_password(password): return user except User.DoesNotExist: return None -
Has anyone verified paystack payment using python or django
I check their documentation on how to implement verifying payment in my django rest project but i noticed they only had the options of using php, node and curl. please is there any other way i can go about it Thanks. -
django.core.exceptions.FieldError: Cannot resolve keyword 'slug' into field. Choices are:
#models.py class Category(models.Model): title = models.CharField(verbose_name='TITLE', max_length=200) slug = models.SlugField('SLUG', unique=True, allow_unicode=True, help_text='one word for title alias.') ... class Episode(models.Model): category = models.ForeignKey("Category", verbose_name=("CATEGORY"), on_delete=models.CASCADE) number = models.IntegerField() ... class Meta: ... def __str__(self): ... def get_absolute_url(self): return reverse("manga:episode_detail", kwargs={"slug": self.category.slug, "number": self.number}) #urls.py ... path("category/<korslug:slug>/", views.CategoryDetailView.as_view(), name="category_detail") path("category/<korslug:slug>/<int:number>/", views.EpisodeDetailView.as_view(), name="episode_detail"), #views.py # ... class EpisodeDetailView(DetailView): model = Episode It raised django.core.exceptions.FieldError: Cannot resolve keyword 'slug' into field. Choices are: ... How to access to Foreign key's slug? I've tried to change attribute query_pk_and_slug to True, and change get_queryset function like follow this, but it throwed same exception. query_pk_and_slug = True def get_queryset(self): return Episode.objects.filter(category__slug=self.kwargs['slug']) -
root domain running wordpress and django application on app subdomain - proxy pages from app subdomain to main domain
I have a Saas website that is developed using Django and the marketing site is also hand coded and running under django. I would like to move the marketing site on the main domain to wordpress and then host the web application under an app subdomain. However a number of pages that are important to our SEO are generated by the web application and appear on the main domain now. eg. example.com/service_page_1 example.com/service_page_2 Once I move the application to a subdomain these will be available at: app.example.com/service_page_1 app.example.com/service_page_2 Is there a way example.com can be running a wordpress marketing site and these pages from the subdomain can be made available on the main domain? I thought about hosting the content in iframes on the wordpress site but I am not sure how this would affect SEO. The web application will be running behind an nginx web server. Is there a way to proxy calls to certain routes on wordpress to my web application running behind nginx? (eg. www.example.com/service/*/ to display the page from my web application at app.example.com/service/*/) -
How can I arrange translation properly between the languages?
Arrangment of words is different in english and the language I want to switch to. <span> Biplove{% trans " has" %} <span class="font-6"> {% trans "replied" %} </span> {% trans "to your comment." %} </span> The arrangement of translation from above code will be different according to code. English Biplove has replied to your comment Another language Biplove has to your comment replied So, the arranging of translation will just be altering its position like above. What am I missing? -
Django: How do I make the media_url and root append my tenant folders using django-tenants?
I am trying to serve images from different tenants but on inspecting the image it brings a 404 error. How can I make my media_url or media_root append my tenant folder so as to appropriately server the images? This is the URL that is currently using to serve the broken thumbnails: http://d9.local.com:8000/media/thumbs/document-b4ded536-0302-11eb-be53-1062e5032d68-thumb.png?v=32361c04 expected url:http://d9.demo.com:8000/media/d9/thumbs/document-b4ded536-0302-11eb-be53-1062e5032d68-thumb.png Here is my settings.py file: STATICFILES_STORAGE = "django_tenants.staticfiles.storage.TenantStaticFilesStorage" MULTITENANT_RELATIVE_STATIC_ROOT = "" DEFAULT_FILE_STORAGE = 'django_tenants.files.storage.TenantFileSystemStorage' STATICFILES_LOCATION = 'static' MULTITENANT_RELATIVE_MEDIA_ROOT = '' MEDIAFILES_LOCATION = 'uploaded' MEDIA_ROOT = os.path.join(BASE_DIR,'media') MEDIA_URL = '/media/' STATIC_URL = '/static/' STATIC_ROOT = 'staticfiles' _DEFAULT_STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, STATICFILES_LOCATION), ] STATICFILES_DIRS = os.getenv('STATICFILES_DIRS', _DEFAULT_STATICFILES_DIRS) STATICFILES_FINDERS = ( 'django_tenants.staticfiles.finders.TenantFileSystemFinder', 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ) MULTITENANT_STATICFILES_DIRS = [ os.path.join(PROJECT_ROOT, "media/%s/thumbs" ), ] -
Is there a way to change the display value in series using highcharts
(Notice: noticed stackoverflow didn't like me embeding pictures because the account is so new so I will post a link to them instead) I am quite new to stackoverflow, django and highcharts so I apologies for any inconvenience. So I am currently working with displaying time and dates in highcharts when I noticed a small problem. When looking at the chart everything looks fine like this. https://i.stack.imgur.com/6hALh.png But when I hover my mouse about a point on the chart it shows a different value. It looks like this https://i.stack.imgur.com/WUr2p.png I would like so that when focusing on a point it will display as HH:MM:SS like it does on the side instead of the total amount of microseconds. What do I need to change to make it happen? Here is the code for the chart <script> $(function () { $('#container').highcharts({ chart: { type: 'line' }, title: { text: 'Time worked by {{user_to_show}}' }, xAxis: { categories: {{dates|safe}} }, yAxis: [{ title: { text: '' }, gridLineWidth: 1, type: 'datetime', //y-axis will be in milliseconds dateTimeLabelFormats: { //force all formats to be hour:minute:second second: '%H:%M:%S', minute: '%H:%M:%S', hour: '%H:%M:%S', day: '%H:%M:%S', week: '%H:%M:%S', month: '%H:%M:%S', year: '%H:%M:%S' }, opposite: true }], plotOptions: …