Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django send email: django.core.exceptions.ImproperlyConfigured error
I am trying to send a test email in Django with "send_email" function but getting an exception of "django.core.exceptions.ImproperlyConfigured: Requested setting EMAIL_BACKEND, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings." Via py shell however everything works. I have tried to set "set DJANGO_SETTINGS_MODULE=mysite.settings" (Windows), and include it in PyCharm Env Variables and also run "django-admin dbshell --settings mysite.settings". The last produced an exception ModuleNotFoundError. I cannot get what it the problem, sending email via python smtp lib works and via django does not. -
Heroku error H10 when deploying Django app
my problem is that when i'm trying to deploy Django app on heroku, i get that H10 error, and obviously cant access the site. heroku logs --tail dont show anything specific beside that H10 error code at=error code=H10 desc="App crashed" method=GET My Procfile is loading web processes, so it's in the right place i guess, but i belive that maybe configuration of that web process is wrong. I had a problem with H14 error which was caused, because i had Procfile in wrong directory. It was directory of the project where manage.py file is sitting. I had to move it one directory above, because it was root file of my repository(.git file was sitting there). This is my Procfile: web: gunicorn api_project.wsgi My directory tree is like: ROOT/ ├─ .git/ ├─ Procfile ├─ api_project/ │ ├─ api_project/ │ ├─ manage.py │ ├─ robots.txt ├─ .gitignore And wsgi file is inside that send api_project dir. Maybe the path inside the Procfile should be diffrent? -
Django Having Error in Production on an ajax request
I am creating a django project and I tried with a guide. I have my code working in Development, but once I pushed code to production, I get errors on ajax requests. I see the error is happening on the views level where I get the keys and the key is a field named "text". In development, using this for submission of quizzes works perfectly well, but in development, it doesn't. I tried using pk for the submission and it returns errors and is unable to create an accurate result instance. Below are my model's instances and views. Error File "/home/django/.local/lib/python3.9/site-packages/django/db/models/query.py", line 435, in get raise self.model.DoesNotExist( quiz.models.Question.DoesNotExist: Question matching query does not exist. models.py from django.db import models import random from account.models import Profile from django.urls import reverse import datetime from django.utils import timezone from ckeditor_uploader.fields import RichTextUploadingField class PublishedBookManager(models.Manager): def get_queryset(self): return super(PublishedBookManager, self).get_queryset().filter(publish_book=True) class Book(models.Model): name = models.CharField(max_length=120) description = models.TextField() created_by = models.ForeignKey(Profile, default=1, null=True, on_delete=models.SET_NULL) number_of_questions = models.IntegerField() number_of_sections = models.IntegerField() time = models.IntegerField(help_text="duration of the quiz in minutes") required_score_to_pass = models.IntegerField(help_text="required score in %") start_date = models.DateTimeField(default=timezone.now) publish_book = models.BooleanField(default=False) date_created = models.DateTimeField(auto_now_add=True) last_updated = models.DateTimeField(auto_now=True) objects = models.Manager() published = PublishedBookManager() def __str__(self): … -
Leaflet Vector grid call url only when map zoom/pan stops
I am using Leaflet.VectorGrid in my react frontend which is fetching dynamic vector tiles from django backend (ST_MVT). Everything is working fine but when user scroll or pan multiple times, all the requests are sent to the backend and after processing all the requests, vector tiles are shown in the front end. Is there any way to wait for the user to finish zoom/pan and only then send the requests to backend. Attached is a demo video -
django can't delete user getting this error "FOREIGN KEY constraint failed"
I am trying to delete an specific user from admin panel but I am getting this error FOREIGN KEY constraint failed. Why I can't delete the user? why I am getting this error? here is full error log of my console: return self.connection.commit() django.db.utils.IntegrityError: FOREIGN KEY constraint failed [19/Oct/2021 11:32:00] "POST /admin/members/usermanagement/ HTTP/1.1" 500 172740 -
How can I use this objectmixins in my functional based views?
I am trying to implement a user activity tracking app in my project. I want to track user each and every click. Can anyone help me in implementing this. although I have tried , I am stucked here while getting objects. Help me in implementing this object mixins into my functional based views. Here is my models.py: # Create your models here. from django.db import models from django.contrib.contenttypes.models import ContentType from django.contrib.contenttypes.fields import GenericForeignKey from django.conf import settings from .signals import object_viewed_signal User = settings.AUTH_USER_MODEL class History(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL, null=True) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() viewed_on = models.DateTimeField(auto_now_add=True) def __str__(self): return "%s viewed: %s" %(self.content_object, self.viewed_on) class Meta: verbose_name_plural = "Histories" def object_viewed_receiver(sender, instance, request, *args, **kwargs): new_history = History.objects.create( user = request.user, content_type = ContentType.objects.get_for_model(sender), object_id = instance.id ) object_viewed_signal.connect(object_viewed_receiver) and this is my views.py from django.shortcuts import render # Create your views here. from django.shortcuts import render, redirect from django.views.generic import ListView, View from django.views.generic.detail import SingleObjectMixin from .models import History from django.shortcuts import render # Create your views here. from django.shortcuts import render, redirect from django.views.generic import ListView, View from django.views.generic.detail import SingleObjectMixin from .models import History class HistoryList(ListView): def … -
I was trying this code with the help of folium and pandas but it is showing this error
import folium import pandas data= pandas.read_csv("Volcanoes.txt") lat= list(data["LAT"]) lon= list(data["LON"]) elev = list(data["ELEV"]) def color_producer(elevation): if elevation<1000: return 'green' elif 1000<=elevation<3000: return 'orange' else: return 'red' Fg= folium.FeatureGroup(name= "My Map") for lt,ln,el in zip(lat,lon,elev): fg.add_child(folium.Marker(location=[lt,ln], popup=str(el)+" m", icon=folium.Icon(color=color_producer(el)))) map.add_child(fg) map.save("Map1.html") this code returns the following error :"Object of type function is not JSON serializable" -
Reverse for 'profile_view' with arguments '('',)' not found. 1 pattern(s) tried: ['in/(?P<username>[^/]+)/$']
views.py User = get_user_model() class ProfileView(View): def get(self, request, *args ,**kwargs): username = kwargs.get('username') try: user = User.objects.get(username=username) except Exception as e: return HttpResponse('This page does not exist. ') if username == request.user.username: context = { 'user': user } return render (request, 'authprofile.html' , context=context) else: context = { 'user': user } return render (request, 'authprofile.html' , context=context)## urls.py from user.views import ProfileView urlpatterns = [ path('in/str:username/',login_required(ProfileView.as_view()),name='profile_view'), -
PM2 vs Gunicorn: Equivalent Gunicorn setup of PM2's fork_mode
We have a staging server for running our web app's current state under our develop git branch. It is running a Next.js component for frontend purposes, and Django for web API (using DRF). As a staging server, we have not fully set it up as that of a production server, where we would normally use Gunicorn. Instead, we are running both Next and Django app using PM2 in cluster_mode and fork_mode, respectively. In our production server, we are running Django on Gunicorn using parallelism with the most basic setup of just setting the workers without necessarily using worker_connection and threads like that of gevent or gthread, respectively. I am wondering, with PM2, what is the equivalent behavior of its fork_mode in Gunicorn? (Like does fork_mode work like that of gevent or gthread? Is it running on concurrency instead of being parallel?) I want to know if PM2's fork_mode is implementing threading or concurrency. If it is, then it might be the reason why Django API request thru our staging server running PM2 fork_mode is causing significant delays, or sometimes causes delays on initial request after some inactivity. With the current state of our Django app's codebase, parallelism works best, which … -
Django REST Framework - "Must be Device instance" error when calling PUT from javascript
I'm getting an error when trying to update an object instance using PUT using the rest framework: ValueError: Cannot assign "{'id': UUID('954...8b4')}": "DeviceConfig.device" must be a "Device" instance. view defn: class DeviceConfigViewSet(viewsets.ModelViewSet): #todo: secure authentication_classes = [] queryset = DeviceConfig.objects.all().order_by('device') def get_queryset(self): device = self.get_renderer_context()["request"].query_params.get('device') if device: return DeviceConfig.objects.filter(device=Device(device=device))[0:] else: return self.queryset serializer_class = DeviceConfigSerializer DeviceConfig model: class DeviceConfig(models.Model): device = models.OneToOneField(Device,primary_key=True,on_delete=models.CASCADE) bpm = models.DecimalField(max_digits=22, decimal_places=3, blank=True, null=True, default=0.5) duty = models.DecimalField(max_digits=22, decimal_places=4, blank=True, null=True, default=0.022) ledState = models.IntegerField( default=255, validators=[MaxValueValidator(255), MinValueValidator(0)] ) pressureMax = models.IntegerField( blank=True, null=True, default=70, validators=[MaxValueValidator(255), MinValueValidator(10)]) JS func FE side: function formSubmit(){ var myForm = document.getElementById("config-form"); var formObj = new FormData(myForm); var object = {}; formObj.forEach(function(value, key){ object[key] = value; }); object["device"] = DEVICE_UUID; const putMethod = { method: 'PUT', headers: { 'Content-type': 'application/json; charset=UTF-8' // Indicates the content }, body: JSON.stringify(object) } fetch("http://localhost:81/configs/"+DEVICE_UUID, putMethod); } I've tried not sending the device ID from the front end but it gives me a 400 then the ol' goog search didn't turn up much for me this time, but I'm not quite sure how to send a Device instance from the client side besides by it's pk which is what I've tried -
Django URL Path from DB file value
I am trying to create 'project' pages that have their paths generated with the {{ project.title }} values, rather than the current method I have which uses ints. I don't quite understand how I can do this, but feel I am close? Models.py from django.db import models # Create your models here. class Project(models.Model): title = models.CharField(max_length=100) description = models.TextField() technology = models.CharField(max_length=20) image = models.FilePathField(path='projects/static/img/') live = models.URLField() source = models.URLField() def __str__(self): return self.title Urls.py from django.urls import path from . import views urlpatterns = [ path("", views.project_index, name="projects"), path("<int:pk>/", views.project_details, name="project_details"), # PK for Primary Key ] Views.py from django.shortcuts import render from .models import Project # Create your views here. def project_index(request): projects = Project.objects.all() context = {'projects': projects} return render(request, 'projects/project_index.html', context) def project_details(request, pk): project = Project.objects.get(pk=pk) context = {'project': project} return render(request, 'projects/project_details.html', context) I figure path("<int:pk>/", will need to be a slug, but I just cannot figure out how to tie in the DB data. Potentially context = {'project': project}? Currently the url is http://127.0.0.1:8000/projects/1/ - I am looking for http://127.0.0.1:8000/projects/EXAMPLE/ Thanks -
Different serializer for Create view depending on request.data type?
I'm trying to set-up a Create view that allows for creating a single object or nested objects depending on if the payload is a dictionary or a list respectively. # views.py class CreateAPIView(generics.CreateAPIView): queryset = Item.objects.all() def get_serializer_class(self): print("get_serializer_class runs") if type(self.request.data.__class__.__name__) == "dict": return SingleItemSerializer else: return NestedItemSerializer # dictionary single_payload = {"name": "A"} # list multiple_payload = [ {"name": "B", children: [ {"name": "C", children: []} ]}, {"name": "D", children: []}, {"name": "E", children: []}, ] # Works fine. "get_serializer_class runs" is printed. Returns HTTP_201 response = APIClient().post(CreateAPIView_URL, single_payload) # Doesn't work. "get_serializer_class runs" is not even printed. Returns HTTP_401 response = APIClient().post(CreateAPIView_URL, multiple_payload) I've tried converting multiple_payload to JSON, including format="json" in the APIClient().post(), adding JSON renderer and parser to the view... but multiple_payload doesn't work. The part that's really throwing me off is the fact that get_serializer_class runs isn't even printed for the multiple_payload -
Heroku DB above limit's
Heroku send an email that my database is (Above limits, access disruption imminent). But the problem is I upgraded my DB a year ago from Hobby dev -> Hobby basic, I think hobby dev is still saving data from my app. It's okay to delete Hobby Dev DB? without affecting current data inside my app? heroku pg:info -
too many values to unpack (expected 2), while importing to django database
I am getting error on importing to data base in Django as shown below, I have more than this field on database, but it can be blank or having a default value. def user_upload(request): template = "super_admin/user_upload.html" data = User.objects.all() prompt = { 'order': 'Order of the CSV should be username, ' 'first_name, last_name, email, add_1, add_2,' ' suburb, state, postcode, country', 'Users': data } if request.method == "GET": return render(request, template, prompt) try: csv_file = request.FILES['file'] except MultiValueDictKeyError: csv_file = None if csv_file: if not csv_file.name.endswith('.csv'): messages.error(request, 'THIS IS NOT A CSV FILE') if csv_file: data_set = csv_file.read().decode('UTF-8') io_string = io.StringIO(data_set) next(io_string) for row_count, column in csv.reader(io_string, delimiter=',', quotechar="|"): if len(column) > 10: try: user = User( username=column[0], first_name=column[1], last_name=column[2], email=column[3], add_1=column[4], add_2=column[5], suburb=column[6], city=column[7], state=column[8], postcode=column[9], country=column[10], ) user.set_password('password') user.is_approved = 't-1' user.added_by_admin = True user.save() except (IntegrityError, ValueError) as e: pass return render_to_response('snippets/message_2.html') context = {} return render(request, template, context) else: messages.error(request, 'Please select a valid file!') return redirect('home') the csv file I am trying to upload is below, what would be the cause, seeking an advice. -
Prevent Double Click in JS for in browser game using Django 2.2
I have an issue where it requires the button to be clicked twice in order to initiate the functions. Except that the first click initiates gameOver() and a second click initiates a gameOver() again. But it takes two clicks to initiate showGame() and hideStartBtn() Therefore at the end of the timer ends it pops up two alerts since it loops twice. Question is: How can I prevent double click and activate all the functions in a single click? Here's a repo. $ git clone https://github.com/carlitos-206/js-browser-game-django.git JS - Snippet function showGame() { var game = document.getElementById("the-game"); if (game.style.display === "none") { game.style.display = "block"; } else { game.style.display = "none"; } }; function hideStartBtn() { var StartBtn = document.getElementById("game-btn"); if (StartBtn.style.display === "block") { StartBtn.style.display = "none"; } else { StartBtn.style.display = "block"; } }; var killCount = 0; function kill_1() { var killBtn = document.getElementById("kill-1") if (killBtn.style.display === "block") { killBtn.style.display = "none"; killCount ++; } else { killBtn.style.display = "block"; } }; //This function repeats kill_1 - kill_7 function kill_7() { var killBtn = document.getElementById("kill-7") if (killBtn.style.display === "block") { killBtn.style.display = "none"; killCount ++; } else { killBtn.style.display = "block"; }; }; function gameOver() { var timeLeft = … -
redirect to previous page after successful admin login
I have authorized.html page which needs a admin login to view so when I go to http://127.0.0.1:8000/authorized/ it takes me to http://127.0.0.1:8000/admin/login/?next=/admin/%3Fnext%3D/authorized/, which is expected. I used the below code in view.py file to built this functionality: class authorizedView(LoginRequiredMixin,TemplateView): template_name = 'home/authorized.html' login_url = '/admin/' But after the successful admin login it didn't take me back to authorized.html instead it directs to http://127.0.0.1:8000/admin/?next=/authorized/ which is just admin page and not the page that I want authorized.html. How to do this? Please provide the detailed steps, i'am new to django! -
Procfile problem when deploying django app on heroku
my problem is that i'm trying to deploy django app on heroku, but everytime when i deploy it and try to open it, i get that error at=error code=H14 desc="No web processes running" method=GET path="/"... I created plain file called "Procfile" with this inside: web: gunicorn api_project.wsgi Also checked few hundreed times if api_project is my root directory, and if Procfile is actually in that directory, and it is indeed. Also checked if i commited all changes, and i did many times. Also tried with heroku ps:scale web=1 command and got this error: Couldn't find that process type (web). Also tried with rebuilding packages and it didn't worked. Also checked if gunicorn is in my requirements file and it indeed is. I dont know what else i could try. Here is proof that my Procfile is in correct directory -
How to parse file names (images) and assign them to a model?
I am relatively new in Django and building an e-commerce application. I have a folder with images (they are in the static directory), and lots of products (~15000, I pull the product data from an API.). Unfortunately I do not pull the image data from the API, instead I have a folder with all the images, and their name contains a fragment of the product.name string. e.g product.name = AH 285/55 R16 Turanza AH325 image_name = Turanza__1 What I am trying to achieve is the following pseudo code: if product.name (the string) is contained in the image_name(path of the image), save the image and associate it with the model, otherwise pass. class Product(models.Model): code = models.CharField(primary_key=True, unique=True, max_length=15, null=False, blank=False) name = models.CharField(max_length=50, null=True, blank=True) brand = models.ForeignKey(Brand, on_delete=models.SET_NULL, null=True, blank=True) price = models.FloatField(null=True, blank=True) image1 = ... image2 = ... or class Image(models.Model): product = models.ForeignKey(Product, ...) name = models.CharField(...) How would I approach this? Maybe a model property? What is the best practice for a problem like this? Can someone point me in the right direction? -
Django + Postgres: could not open extension control file citext.control
Environment(s) Ubuntu 20.04 & Debian 10 with Python 3.8 or 3.7, respectively. Postgresql versions 11, 12, and 14 have been tried. Psycopg2-binary 2.8.0 Overview I'm attempting to install a Django project, and I'm getting this error: psycopg2.errors.UndefinedFile: could not open extension control file "/usr/share/pgsql/extension/citext.control": No such file or directory The psycopg devs informed me this is likely an issue with the postgresql-contrib libraries. Similarly, others have been able to fix this error by installing postgresql-contrib, however, this does not work for me. I've also tried installing postgresql-12. I can see that citext.control is available in /usr/share/postgresql/12/extension/citext.control, so I tried ln -s /usr/share/postgresql/12 /usr/share/pgsql with no effect. I also ran CREATE EXTENSION citext; in Postgres, also without effect. Any support with this would be greatly appreciated, as I was hoping to have this project live already! Thanks so much. Trace Running migrations: Applying core.0043_install_ci_extension_pg...Traceback (most recent call last): File "/home/user/venvs/janeway/lib/python3.8/site-packages/django/db/backends/utils.py", line 64, in execute return self.cursor.execute(sql, params) psycopg2.errors.UndefinedFile: could not open extension control file "/usr/share/pgsql/extension/citext.control": No such file or directory The above exception was the direct cause of the following exception: Traceback (most recent call last): File "manage.py", line 16, in <module> execute_from_command_line(sys.argv) File "/home/user/venvs/janeway/lib/python3.8/site-packages/django/core/management/__init__.py", line 364, in execute_from_command_line utility.execute() File … -
Data from js to python(django) and vice versa
I have a script which make a calendar and assigns values like date to a cell. I would like to send three arguments to my function in django, such as date, current month, and current year, and get the result back. I would like everything to be done in a loop so that each cell would get a different value. Javascript script: function showCalendar(month, year) { let firstDay = (((new Date(year, month)).getDay() - 1) + 7) % 7; let daysInMonth = 32 - new Date(year, month, 32).getDate(); let tbl = document.getElementById("calendar-body"); // body of the calendar // clearing all previous cells tbl.innerHTML = ""; // filing data about month and in the page via DOM. monthAndYear.innerHTML = months[month] + " " + year; selectYear.value = year; selectMonth.value = month; // creating all cells let date = 1; for (let i = 0; i < 6; i++) { // creates a table row let row = document.createElement("tr"); //creating individual cells, filing them up with data. for (let j = 0; j < 7; j++) { if (i === 0 && j < firstDay) { let cell = document.createElement("td"); let cellText = document.createTextNode(""); cell.appendChild(cellText); row.appendChild(cell); } else if (date > daysInMonth) { … -
PostgreSQL VS MySQL while dealing with GeoDjango in Django
There are multiple Tutorials/Questions over the Internet/Youtube/StackOverflow for finding nearyby businesses, given a location, for example (Question on StackOverflow) : Returning nearby locations in Django But one thing common in these all is that they all prefers PostgreSQL (instead of MySQL) for Django's Geodjango library I am building a project as: Here a user can register as a customer as well as a business (customer's and business's name/address etc (all) fields will be separate, even if its the same user) This is not how database is, only for rough idea or project Both customer and business will have their locations stored Customers can find nearby businesses around him I was wondering what are the specific advantages of using PostgreSQL over MySQL in context to computing and fetching the location related fields. (MySQL is a well tested database for years and most of my data is relational, so I was planning to use MySQL or Microsoft SQL Server) Would there be any processing disadvantages in context to algorithms used to compute nearby businesses if I choose to go with MySQL, how would it make my system slow? -
Django permissions for GET, PUT and DELETE
I am trying to make the PUT and DELETE methods require authentication but I want the GET method to be public. I know I can take the GET method out and put it into its own function but I would need to make another url for it. What would be the best way to approach this? thanks @api_view(['GET', 'PUT', 'DELETE']) @permission_classes([IsAuthenticated]) def getOrUpdateOrDeleteCar(request, pk): if request.method == 'GET': vehicle = Car.objects.get(id=pk) serializer = CarSerializer(vehicle, many=False) return Response(serializer.data) elif request.method == 'PUT': data = request.data car = Car.objects.get(id=pk) car.image=data['image'] car.make=data['make'] car.prototype=data['prototype'] car.year=data['year'] car.serviceInterval=data['serviceInterval'] car.seats=data['seats'] car.color=data['color'] car.vin=data['vin'] car.currentMileage=data['currentMileage'] car.save() serializer = CarSerializer(car, many=False) return Response(serializer.data) elif request.method == 'DELETE': car = Car.objects.get(id=pk) car.delete() return Response('Car Deleted!') -
How to remove form-group from input in Django Crispy?
I'm having trouble rendering a template with Django Crispy. When I add a {{ form.name|as_crispy_field }} Crispy adds me a classless div and another div with the form-group class wrapping my input <div id="div_id_name" class="form-group"> <div class=""> <input type="text" name="name" value="Maria" maxlength="150" class="textinput textInput form-control" required="" id="id_name"> </div> </div> I would like to remove these two divs, and leave only the input. My forms.py looks like this: class ClientForm(forms.ModelForm): class Meta: model = ClientModel fields = ( "name", "email", "birth_date", ) widgets = { "birth_date": forms.TextInput(attrs={"type": "date"}), } def __init__(self, **kwargs): super().__init__(**kwargs) self.helper = FormHelper() self.helper.form_show_labels = False The version of Django Crispy Forms is 1.13.0 and Bootstrap 4.6.0. -
why not executed subprocess ffmpeg in online windows virtual server django?
this is my code: subprocess.run('ffmpeg -i ' + media_in + ''' -ss 00:00:01 -frames:v 1 -vf "scale=w='min(150\, iw*3/2):h=-1'" ''' + image_out, shell=True) image_out is result of a video. My code is executed correctly on localhost and output. Although I installed ffmpeg on a virtual server in the c:/ drive and made the environment settings But in Deploy mode, it does not run on Windows Virtual Server and does not output? Does not run on the my web site Blockquote -
Django: How to access object id with the reverse relationship?
Let's say I have this code: class Recipe(models.Model): item = models.OneToOneField("Item", on_delete=CASCADE) class Item(models.Model): # ... Recipe objects do have an item_id attribute, but Item objects don't have a recipe_id attribute. Is there a way to allow both models to directly access the id of the other side of the relation? Note that for some external reasons (that are not interesting to explain here), I can't access fields by relations, so recipe.id is unavailable to me. Of course, a workaround could be to define a property named recipe_id on the Item object, it works but feels unnatural to me, and a bit repetitive since I need do to it on multiple models.