Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django <div>{% block content %}
This is probably a silly question, but can you put a <div> stage around Django's {% block content %}? <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Title</title> {% load static %} <link rel="stylesheet" type="text/css" href="{% static 'property/style.css' %}"> {% block head %} {% endblock %} </head> <body> <div class = "row"> <div class = "column left"> {% block left %} {% endblock %} </div> <div class = "column center"> {% block center %} {% endblock %} <div class = "column right"> {% block right %} {% endblock %} </div> </div> </body> <HTML> and my CSS * { box-sizing: border-box; } body { color: var(--text_color); background-color: var(--background_color); font-family: var(--font); font-size: var(--font_size); } .column { float: left; padding: var(--padding); height: 300px; } .left, .right { width: 25%; } .center { width: 50%; } .row:after { content: ""; display: table; clear: both; } I am trying to make each {% block %} be a column without having to write the <div> for each template. However, my HTML output is stacking them on top of each other instead of side by side. -
Many to many relationship does not work with django-safedelete as i want
I am using a library called django-safedelete to avoid permanently deleting records from the database, the technique is called "safedelete". Here is the documentation of the library https://django-safedelete.readthedocs.io/en/latest/managers.html I have a problem and it is that when I softdelete a record in the intermediate table between Actor and Film (Participation) the QuerySet ignores it completely, I mean when I execute a query to know in which film an actor has been, the Queryset ignores that the intermediate register that links the actor and the film is softdelete and shows in any case the films in which the actor has participated. here is an example of what happens: >>> Actor.objects.get (pk = 1) <Actor: Actor object (1)> >>> Film.objects.get (pk = 1) <Film: Film object (1)> >>> Participation.objects.all_with_deleted (). Values ('id', 'actor', 'film', 'deleted') <SafeDeleteQueryset [{'id': 1, 'actor': 1, 'film': 1, 'deleted': datetime.datetime (2021, 9, 4, 0, 43, 50, 125046, tzinfo = <UTC>) }]> >>> Actor.objects.get (pk = 1) .films.all () <SafeDeleteQueryset [<Film: Film object (1)>]> As you can see, it ignores that the participation record is softdelete and also shows the film in which the actor participated, what I need is not to show that the actor participated in that … -
How should I go about building a hard-coded image search website?
I have collected some images over time and I have categorised them into different category, let's say some are of cats, dogs, houses etc. you get the point!Now I want to create a simple hardcoded search engine, which return the images, let's say if I type dogs then it should return all the dog images which I have, I have no idea how to go about doing it, would anyone tell me how should I go about doing it? I have just created a beautiful search bar and that's it! Any help would be much appreciated :) I want to create this website and host it for other people to use My current skills are HTML5, CSS3, lil bit of JS & Django! -
Djoser Get Confirmation Email When Creating User, Not When Updating Its Data
Im currently using Djoser. I am using SEND_ACTIVATION_EMAIL and SEND_CONFIRMATION_EMAIL. I just want to receive confirmation email in user creation, not in user update. Is there any view I should override in order to reach this result? -
Django : Starts with directly accessing foreign key value
I have two models that look like the following below class DjImagingImage(models.Model): img_documentnbr = models.ForeignKey('index', models.DO_NOTHING, db_column='IMG_DocumentNbr', max_length=200, to_field='drawingid', related_name='drawing_meta') class Tblinvrev(models.Model): """ Table for keeping track of Index Images and the most recent metadata """ rectype = models.CharField(db_column='RecType', max_length=1) # Field name made lowercase. drawingid = models.CharField(db_column='DrawingID', primary_key=True, max_length=20) Sometimes images are not entered into TblInvrev Now I want to search without using the relationship as I might be missing records if I do so DjImagingImage.objects.filter(img_documentnbr_id__startswith='cow') # Does not work. I use _id to access the foreign key value directly DjImagingImage.objects.filter(img_documentnbr__drawingid__startswith='cow') # Works but items not indexed in tblinvrev will not show How can I use the foreign key value in DjImagingImage to do so without traversing the relationship? -
Django pass model.class in to view
I am very new with django. I would like to upload an image display it at my HTML page. Than get some values and process it according to these values. I have created a simple model class: ''' class Segment_ch1(models.Model): title_seg = models.CharField(max_length=200,default='Ch1_seg') updated_seg = models.DateTimeField(auto_now=True) created_seg = models.DateTimeField(auto_now_add=True) segment = models.ForeignKey('Upload_ch1',related_name="%(class)s_Upload_ch1", on_delete=models.CASCADE) #segment = models.ForeignKey('Upload_ch1',related_name="+", on_delete=models.CASCADE) # explain https://stackoverflow.com/questions/34003865/django-reverse-query-name-clash gaus_sigma = models.FloatField(default=20) gaus_mode = models.CharField(max_length=200,default='constant') truncate = models.FloatField(default=4) thresh = models.FloatField(default=0.012) min_forground = models.FloatField(default=0.0005) max_forground = models.FloatField(default=0.03) def __str__(self): return str(self.id) def save(self,*args,**kwargs): #breakpoint() image = Image.open(self.segment.image) # #pixels = pixels[0,:,:] # #use the normalisation method img = get_image_intensity(image,self.segment.min_inten,self.segment.max_inten) img_gaus, im_thresh, im_sobel, basins, seg=segment_parkin(img,gaus_sigma=self.gaus_sigma,gaus_mode=self.gaus_mode,truncate=self.truncate,disp_smooth_3d=False,thersh_plot=False,thresh=self.truncate,disp_sobol=False,min_forground=self.min_forground,max_forground=self.max_forground) im_pil=Image.fromarray(np.uint8(seg)) #save buffer = BytesIO() im_pil.save(buffer,format='png') image_png_1 = buffer.getvalue() self.segment.image.save(str(self.title_seg), ContentFile(image_png_1),save=False) ''' than in views, i am getting the values using forms.py. however I am not sure if I can use the model class for save the process file and then call it for display in HTML Here is my attempt: ''' def Image_segmentation(resquset): #im1=Upload_ch1.objects.all()[0] #im2=Upload_ch2.objects.all()[0] if resquset.method == 'POST': ImageForm1_from = ImageForm_c1(resquset.POST) ImageForm2_from = ImageForm_c2(resquset.POST) if ImageForm1_from.is_valid(): breakpoint() title_form=ImageForm1_from.cleaned_data['title'] min_form=ImageForm1_from.cleaned_data['min_inten'] max_form=ImageForm1_from.cleaned_data['max_inten'] im1=Upload_ch1.objects.get(title="Ch1.tif") Upload_ch1().save(image=im1.image,title=title_form,min_inten=min_form,max_inten=max_form) #new_img2= im1=Upload_ch1.objects.get(title="Ch1.tif") im2=Upload_ch2.objects.get(title="Ch2.tif") #breakpoint() ImageForm1_from = ImageForm_c1(resquset.GET) ImageForm2_from = ImageForm_c1(resquset.GET) return render(resquset,'Image_segmentation.html',{'ImageForm1_from':ImageForm1_from,'ImageForm2_from':ImageForm2_from,'im1':im1,'im2':im2,}) ''' Upload_ch1().save(image=im1.image,title=title_form,min_inten=min_form,max_inten=max_form) ''' The error i get is: ''' … -
How can I execute ModelAdmin.save_model asynchronously?
A Django-based website I'm building may occasionally need to run shell commands when initiated by an administrative user. Anticipating this, I decided it would be a good idea to write these processes to be asynchronous considering asyncio supports shells right out-of-the-box. I am executing these processes from the save_model() function of ModelAdmin, not an async view. My issue is when long-running processes are executed, the supposedly 'async' server gets completely hung-up on them and doesn't answer any other requests from clients until they are finished. I'm 100% certain this is because I'm running these processes in a sync function, albeit asynchronously (see below). I need to be able to tell the administrative user if the process they are running has succeeded or failed. I'm currently doing this through the messages API provided by Django. Here is the function executing the shell commands (Linux): import asyncio import sys async def run_subprocess(cmd: str) -> Tuple[int, bytes, bytes]: """Run a subprocess command asynchronously. Notes: This will execute the subprocess in a shell under the current user. Args: cmd (`str`): The command to run. Returns: exec_info (`tuple`): `(retcode, stdout, stderr)` from the subprocess for processing. """ # Create an execute the future try: proc … -
my form cannot receive request.files. I have a problem that user profile photo cannot be uploaded. img is sent trough request method properly
** views.py ** def create_user(request): if request.method == 'POST': form = UserProfile(request.POST) user_photo = PhotoUser(request.FILES,request.POST) #instance=request.user.userphoto print(request.FILES) * here i can see my image went trough * if form.is_valid(): form.save() else: form = UserProfile() user_photo = PhotoUser() return render(request,'user/user.html',{'form':form,'user_photo':user_photo}) ** urls.py** urlpatterns = [ path('admin/', admin.site.urls), path('', views.exe,name='exe'), path('books/', include('books.urls')), path('user/', include('user.urls')), ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ** signals.py** @receiver(post_save,sender=User) def create_profile(sender, instance, created, **kwargs): if created: UserPhoto.objects.create(user=instance) @receiver(post_save, sender=User) def save_profile(sender, instance, **kwargs): instance.userphoto.save() ** models.py ** class UserPhoto(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) img = models.ImageField(upload_to=image_directory_path,default='avatar.png',blank=True,null=True) def __str__(self): return self.user.username ** html** <form method="post" enctype="multipart/form-data" action="."> {% csrf_token %} {{form}} {{user_photo}} <input type="file" name="img" accept="image/*" id="id_img"> <input type="submit" value="Submit"> </form> forms.py class PhotoUser(forms.ModelForm): class Meta: model = UserPhoto fields = ['img'] MEDIA_ROOT = (BASE_DIR / 'media') MEDIA_URL = '/media/' so everything works ok but users profile images are not getting uploaded. signals are executed properly and 2 models are conected and my avatar.png is uploaded to every user and user is saved. if i upload user photo via admin it works properly -
Django-Storages with SFTP: GET-requests fail
I a trying to use django-storages to access my "Hetzner" Storage Box (https://www.hetzner.com/storage/storage-box) using SFTP which should hold media data, i.e. image files which users of my website can upload dynamically. The corresponding part of my settings.py file looks like: DEFAULT_FILE_STORAGE = 'storages.backends.sftpstorage.SFTPStorage' SFTP_STORAGE_HOST = 'username.your-storagebox.de' SFTP_STORAGE_ROOT = '/media' SFTP_STORAGE_PARAMS = { 'username': 'username', 'password': 'password', 'allow_agent': False, 'look_for_keys': False, } The strange thing is that, when the user uploads an Image, it is placed on the storage space as I can confirm using SFTP. But getting the images from the storage box fails, no Image is displayed. An excerpt from the console: [03/Sep/2021 22:34:01] "GET /media/filename.jpg HTTP/1.1" 404 1962 I could figure out that Django is still looking inside my MEDIA_DIR for the files. Againg, the corresponding part of my settings: MEDIA_DIR = 'media' MEDIA_ROOT = os.path.join(BASE_DIR, MEDIA_DIR) MEDIA_URL = '/media/' So in a nutshell: Using SFTP seems to be working for putting files into storage, but getting them again somehow fails. I am hoping for some help. Thanks in advance! -
Django Celery broken after moving secret key to environment variable
I'm working on a Django project that uses Celery for periodic tasks. For improved security, I moved Django's SECRET_KEY into an environment variable. The app ran fine, so Django was certainly able to find the environment variable and set the SECRET_KEY. But an unexpected side effect was that all the regularly occurring Periodic Tasks stopped triggering. I was able to run the tasks manually from Django Admin, so the Celery workers were still alive and well, but the tasks wouldn't trigger themselves like they usually do. The app settings and Celery config are both located in a directory called server. Here's the file structure: -server -__init__.py -celery.py -settings.py Before moving the secret key, it was in settings.py like this: SECRET_KEY = "secret" After moving to an environment variable, the line in settings.py was like this: SECRET_KEY = os.environ.get("SECRET_KEY") And here's the contents of celery.py, in case that's relevant: os.environ.setdefault("DJANGO_SETTINGS_MODULE", "server.settings") app = Celery("server") app.config_from_object("django.conf:settings", namespace="CELERY") app.autodiscover_tasks() As soon as I moved the secret key out of the environment variable and back into settings.py, the tasks started firing again. I'm hoping to figure out why moving the secret key broke the periodic tasks so I can move the secret key back … -
Django Migrations stuck after executing in incorrect order
I made two changes to different models in my database. The first operations = [ migrations.DeleteModel( name='Settlement', ), ] And the second: operations = [ migrations.RemoveField( model_name='invoice', name='settlement_deducted', ), migrations.RemoveField( model_name='invoice', name='settlement_supporting', ), ] The issue is that they ran in this order, and the second one failed. The field being removed in the second migration uses the "Settlement" model, but since that model was deleted in the first migration it throws this error: ValueError: The field invoices.Invoice.settlement_deducted was declared with a lazy reference to 'accounting.settlement', but app 'accounting' doesn't provide model 'settlement'. The field invoices.Invoice.settlement_supporting was declared with a lazy reference to 'accounting.settlement', but app 'accounting' doesn't provide model 'settlement' Now when I try to do anything to fix it, it seems to just be stuck in that error state and continuously throws that same error. I have tried reverting the first migration to the previous migration on that model, adding that model back in and running makemigrations and then migrate so that the Settlement model exists again, and deleting the second migration (though it was never run anyway). All of these options are still throwing the same error. I am surprised that Django didn't catch this dependency issue … -
Reportlab in Django Application error - Forbidden (CSRF token missing or incorrect.)
I come from more of a data science background, but for fun I have been building a web application. I am new to django, javascript, and HTML, and it's a lot to wrap my head around - so if my coding appears unconventional I apologize. Feel free to offer any feedback. Within my application, I am trying to create a button on a webpage that does the following: Reads data input from an HTML table entered by the user in JavaScript (as an array). Using ajax, sends the data to a Python view. There, a function will be performed on the array, and the output will be returned to the user as a PDF generated by the reportlab library. Unfortunately, I continue to get the following error: Forbidden (CSRF token missing or incorrect.): /get_custom_bingo Here is the full error: Forbidden (CSRF token missing or incorrect.): /get_custom_bingo [03/Sep/2021 16:07:17] "POST /get_custom_bingo HTTP/1.1" 403 2513 [03/Sep/2021 16:07:17] "POST /pages/custom_bingo.html HTTP/1.1" 200 4320 [03/Sep/2021 16:07:17] "GET /static/JS/scripts.js HTTP/1.1" 304 0 I have tried to get it to go away, but nothing I can find online seems to be helping my current scenario. Does anybody know how to resolve this? (See the relevant sections … -
How to use 3 seperate filters on 1 page?
I have a page on which are 3 separate forms. With form 1 I can filter on name (typed in by user) with form method Post With form 2 I can filter on level (from list) with form method Get With form 3 I want to filter on school (from list) also with form method Get <!-- ### Filters ### --> <form method="POST" action="{% url 'spells' %}"> {% csrf_token %} <h1>Filter Options</h1> <div class="container ftable"> <div class="row"> <div class="input-group ml-5 col-md-4"> <label for="filter-search-name" class="form-labelz"><strong>Spell Name:&nbsp;&nbsp;&nbsp;&nbsp;</strong></label> <input class="form-control py-2 border-right-0 border" type="search" name="filter-search-name" id="filter-search-name" value autocomplete="off" placeholder="Give Spell Name or leave blank for all spells" spellcheck="false"> </div> <div class="col-12"> <button type="submit" class="btn btn-secondary">Filter</button> </div> </div> </div> </form> <form method="GET" action="{% url 'spells' %}"> <div class="container ftable"> <div class="input-group ml-5 mt-5 col-md-4"> <label for="filter-search-level" class="form-label"><strong>Spell Level: &nbsp;&nbsp;&nbsp;&nbsp;</strong></label> <select id="filter-search-level" name="filter-search-level" class="form-select"> <option selected value='Cantrip'>Cantrip</option> <option value='1st'>1st</option> <option value='2nd'>2nd</option> <option value='3rd'>3rd</option> <option value='4th'>4th</option> <option value='5th'>5th</option> <option value='6th'>6th</option> <option value='7th'>7th</option> <option value='8th'>8th</option> <option value='9th'>9th</option> </select> <div class="col-12"> <button type="submit" class="btn btn-secondary">Filter</button> </div> </div> </div> </form> <form method="GET" action="{% url 'spells' %}"> <div class="container ftable"> <div class=" input-group ml-5 mt-5 col-md-4"> <label for="filter-search-school" class="form-label"><strong>Spell School: &nbsp;&nbsp;</strong></label> <select id="filter-search-school" name="filter-search-school" class="form-select"> <option selected value='Abjuration'>Abjuration</option> <option value= … -
I have the problem: get() takes 1 positional argument but 2 were given, on django [closed]
class GetyPost(View): def get(request): informacion = NameUrl.objects.all() if len(informacion) > 0: datos = {'mensaje':'Conseguido', 'informacion':informacion} else: datos = {'mensaje':'No sonseguido'} return JsonResponse(datos) I don't know why the error TypeError at /api/todo/ get() takes 1 positional argument but 2 were given [1]: https://i.stack.imgur.com/dkDoa.png My url: from django.urls import path from .views import GetyPost urlpatterns = [ path('todo/', GetyPost.as_view(), name = 'GetyPost') ] -
Invalid block tag on line 29: 'endfor', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag?
Something wrong with my .html template. Can't figure the error on line 29. Says Invalid block tag on line 29: 'endfor', expected 'elif', 'else' or 'endif'. Did you forget to register or load this tag? {%extends 'mtunes/basic.html'%} {% block title%}Search{% endblock %} {% block body %} {% load static %} {% if query %} <h1 style="color: rgb(158, 60, 60); text-align: center;">Search Results for {{ query_str }}</h1> {% for i in query %} <div class="container"> <div class="card mb-3" style="max-width: 940px; padding-top: 0%;"> <div class="row no-gutters"> <div class="col-md-4"> <img src="/media/{{i.image}}" class="card-img" alt="..."> </div> <div class="col-md-8"> <div class="card-body"> <h5 class="card-title" style="color: green; font-weight: 550;">{{i.name}}</h5> <p class="card-text">Singer Name: {{i.singer}}</p> <p class="card-text">Tags: {{i.tags}}</p> <p class="card-text">Movie: {{i.movie}}</p> {% if user.is_authenticated %} <a href="/mtunes/songs/{{i.song_id}}"><button class="btn btn-outline-danger">Listen Song</button></a> </div> </div> </div> </div> {% endfor %} {% elif notfound %} <div class="row pt-3"> <!-- you can do a lot more here --> <h1> This song is not Available</h1> <span style='font-size:100px;'>&#128514;</span> </div> </div> </div> {% endif %} {% endblock %} -
Custom Django form validator doesnt render validation error on the frontend
I have a custom validator which should raise an error on the frontend for the user if the validation fails. However, I am not sure where and how to return this to the frontend. Right now it only shows in the terminal/Django error site on dev server: The view: def raise_poller(request): # if this is a POST request we need to process the form data if request.method == 'POST': # create a form instance and populate it with data from the request: form = PollersForm(request.POST) # check whether it's valid: if form.is_valid(): # Make Validation of Choices Fields poller_choice_one = form.cleaned_data['poller_choice_one'] poller_choice_two = form.cleaned_data['poller_choice_two'] if ' ' in poller_choice_one or ' ' in poller_choice_two: raise ValidationError('Limit your choice to one word', code='invalid') return poller_choice_two # !! IDE says this is unreachable else: # process the remaining data in form.cleaned_data as required poller_nature = form.cleaned_data['poller_nature'] poller_text = form.cleaned_data['poller_text'] poller_categories = form.cleaned_data['poller_categories'] # Get the user created_by = request.user # Save the poller to the database p = Pollers(poller_nature=poller_nature, poller_text=poller_text, poller_choice_one=poller_choice_one, poller_choice_two=poller_choice_two, created_by=created_by) p.save() p.poller_categories.set(poller_categories) # redirect to a new URL: return HttpResponseRedirect('/') # if a GET (or any other method) we'll create a blank form else: form = PollersForm() return render(request, … -
Checkmarx Reflected XSS
I have a Django based API. After scanning my application with CheckMarx if showed that I have Reflected XSS volnurability here: user_input_data = json.loads(request.GET.get('user_input_data')) What I already tried: Used django.utils.html.escpae Used django.utils.html.strip_tags Used html.escape Used escapejson package Every time I run scanning, it finds stored XSS at exactly this location -
Validating string for possible space returns error in Django form even though there's no space
I have two fields in my Django form where I want the user to insert exactly one word. So to have some validation in the view i created the following validator (idea is to search for spaces): Views.py [..] if ' ' in poller_choice_one or poller_choice_two: raise ValidationError(('Limit your choice to one word'), code='invalid') else: [..] To make it more robust I added the strip option to the FormFields to be validated: # Poller Choices poller_choice_one = forms.CharField(label='Choice one', max_length=20, strip=True) poller_choice_two = forms.CharField(label='Choice two', max_length=20, strip=True) I tried like a bunch of inputs from single digits to single chars etc., it always raises the validation error -
Custom Functions in Django Model
I am building a FedEx API in django and currently have a Shipment class which has methods such as create_shipment(), delete_shipment()... I have stored this shipment class in a separate file. I created a Shipment model inside my models.py and I noticed that it seems inefficient to have two different Shipment classes (one for the django model and the other defined in a separate file). I want to know if it would be considered bad practice to define the functions of the API inside the same model class. I want process_shipment() to be called by the model and then insert the instance into the database. Note that to do this I'd need to overwrite the init method of the parent model class which I hope will be ok. -
Django Rest Framework + Serializers + Vue.js, Reset Password Functionality
I am trying to create a reset password functionality, but I can't find a good tutorial that explains how to do that with DRF and Vue.js. I am using serializers to pass the data, so there are no html views involved. What is the most efficient way of creating that Reset Password Functionality? I am creating new users via /api/v1/users/. Any ideas are very appretiated. Thank you! -
I have problem with Pylance when my VSCode update
"authenticate" is not accessed Pylance ?? Photo pylance extencion is installed -
"detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)"
I created a simple Django REST framework and I am able to GET. However, when trying to POST I receive the following: "detail": "JSON parse error - Expecting value: line 1 column 1 (char 0)" I have attached my models, urls, views and serializers below. My Models.py from django.db import models from pygments.lexers import get_all_lexers from pygments.styles import get_all_styles LEXERS = [item for item in get_all_lexers() if item[1]] LANGUAGE_CHOICES = sorted([(item[1][0], item[0]) for item in LEXERS]) STYLE_CHOICES = sorted([(item, item) for item in get_all_styles()]) class Snippet(models.Model): created = models.DateTimeField(auto_now_add=True) title = models.CharField(max_length=100, blank=True, default='') code = models.TextField() linenos = models.BooleanField(default=False) language = models.CharField(choices=LANGUAGE_CHOICES, default='python', max_length=100) style = models.CharField(choices=STYLE_CHOICES, default='friendly', max_length=100) class Meta: ordering = ['created'] serializers.py class SnippetSerializer(serializers.ModelSerializer): class Meta: model = Snippet fields = '__all__' #fields = ['id', 'title', 'code', 'linenos', 'language', 'style'] urls.py urlpatterns = [ path('snippets/', views.snippet_list), path('snippets/<int:pk>/', views.snippet_detail), ] urlpatterns = format_suffix_patterns(urlpatterns) Views.py from django.shortcuts import render from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from snippets.models import Snippet from snippets.serializers import SnippetSerializer from rest_framework.decorators import api_view from rest_framework import status from rest_framework.response import Response @api_view(['GET','POST']) @csrf_exempt def snippet_list(request,format=None): """ List all code snippets, or create a new snippet. """ if … -
i dont knw why it cant reflect admin.py if there is not any mistake in setting.py?
https://github.com/Angelheartha/tera this is my github i dont have idea why after writting at admin.py it cant reflect as if i didnt write any code when i do http://127.0.0.1:8000/admin ? i thought because i missed something at setting.py but it seems not the case... i dont know what is the problem here i did python manage.py migrate but not change -
Django mysql (mariadb Server version: 5.5.68) database not working with wsgi.py
I have a working django application that works fine in the development server. As soon as I try to use it as a production server application using Apache and wsgi.py it gives me errors. With MYSQL I get the following errors: [Fri Sep 03 13:27:22.424881 2021] [wsgi:error] [pid 15424] [remote 172.30.0.54:49967] import MySQLdb as Database [Fri Sep 03 13:27:22.424920 2021] [wsgi:error] [pid 15424] [remote 172.30.0.54:49967] File "/home/bakert/.local/share/virtualenvs/trackx_proj_master-nygxcPTP/lib/python3.9/site-packages/MySQLdb/__init__.py", line 24, in <module> [Fri Sep 03 13:27:22.424952 2021] [wsgi:error] [pid 15424] [remote 172.30.0.54:49967] version_info, _mysql.version_info, _mysql.__file__ [Fri Sep 03 13:27:22.424982 2021] [wsgi:error] [pid 15424] [remote 172.30.0.54:49967] NameError: name '_mysql' is not defined When I do a pip freeze - My requirements file looks like this: asgiref==3.3.4 dj-database-url==0.5.0 dj-email-url==1.0.2 Django==3.1.12 django-cache-url==3.2.3 django-crispy-forms==1.9.2 django-ranged-response==0.2.0 django-simple-captcha==0.5.14 environs==8.0.0 marshmallow==3.12.1 mod-wsgi-httpd==2.4.48.1 mysqlclient==2.0.1 pathlib==1.0.1 Pillow==8.1.0 python-dotenv==0.17.1 pytz==2021.1 six==1.15.0 sqlparse==0.4.1 So - it seems like the virtual environment should know about mysql - but it doesn't seem to find it. I tried reverting back to sqlite - just to try it - and it complained about sqlite version... so it seems something's not right in the virtual environment that wsgi.py is trying to use. My wsgi.py looks like this: import os,sys sys.path.append('/var/www/trackx_proj/trackx_root') sys.path.append('/usr/lib64/mysql') sys.path.append('/home/bakert/.local/share/virtualenvs/trackx_proj_master- nygxcPTP/lib/python3.9/site-packages/MySQLdb') sys.path.append('/home/bakert/.local/share/virtualenvs/trackx_proj_master- nygxcPTP/lib/python3.9/site-packages') from django.core.wsgi … -
Modal content not updating
I have a pretty basic JS modal right now, but the content is not loading from the modal.html call. Here is my function: var modal = $('#userModal') var button = $('submit') button.on('click', function(event) { var str = "Testing content" $("#modal_body").html(str) modal.modal("show") The modal_body is a paragraph with the ID "modal_body". The modal is opening but the variable "str" content is not populating. Am a beginner to Ajax working in a Django Jinja2 template. Thank you!