Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Creating Dynamic Form Fields in Django ModelForm
I am looking to search the instance, check a value in a specific field and then return a list for the field to Meta but it doesn't appear the __init__ can return anything. How can I make a dynamic form that based on a value in a field, shows only a predetermined other fields. Goal: Ultimately if subgrade_02_weight != None then make subgrade_02_title, subgrade_02_weight, subgrade_02_1_star, etc. visible. I have over 100 fields that I would need to make visible and do not want to do this in a hack way in the template. It seems like JS is the best approach but I have 0 experience in JS. class Inspection_ResultForm(forms.ModelForm): #work on this tomorrow def __init__(self, user, *args, **kwargs): super( Inspection_ResultForm,self).__init__(*args, **kwargs) #if user.groups.filter(name='Operations Manager').exists(): fields_list = ["subgrade_00_title", "subgrade_00_weight", "subgrade_00_1_star", "subgrade_00_2_star", "subgrade_00_3_star", "subgrade_00_4_star", "subgrade_00_5_star", "subgrade_01_title", "subgrade_01_weight", "subgrade_01_1_star", "subgrade_01_2_star", "subgrade_01_3_star", "subgrade_01_4_star", "subgrade_01_5_star" ] if self.instance.inspection_request.sample.order.specification.subgrade_02_weight != None: fields_extends = ["subgrade_02_title", "subgrade_02_weight", "subgrade_02_1_start", "subgrade_02_2_star", "subgrade_02_3_star", "subgrade_02_4_star", "subgrade_02_5_star"] fields_list.extend(fields_extends) print(fields_list) fields = fields_list return fields class Meta: model = Inspection_Result fields = ('subgrade_00_title', 'subgrade_01_title',) #would like this to be equal to field list calculated in __init__ -
File-field in Django admin not showing when upgraded Django to 3 from 2.1
Django admin file field is showing "loading" after upgrading Django to 3 from 2.1 The console shows the error It was working fine when it was 2.1. -
Django on button click open modal and populate the form
I have a modal which contains a HTML form with customer details. On button click I want to get the details for the customer from view, open the modal and populate the details in the modal <td><a href="/edit_customer/{{ customer.customer_name }}" class="btn btn-primary" data-toggle="modal" data-target=".bd-example-modal-lg"><i class="fa fa-fw fa-edit"></a></td> It opens the modal but does not calls the function in view. I tried this way <td><a href="/edit_customer/{{ customer.customer_name }}" class="btn btn-primary edit_btn"><i class="fa fa-fw fa-edit"></a></td> By handling everything in js $(".edit_btn").click(function(){ var _url = $(this).attr('href'); $.ajax({ url: _url, success: function(response){ //show the modal //populate the form document.getElementById("customer_name).value = ""; ... }, error: function(error){ console.log(error) } }); }); But I don't want to do this way. I want to to populate in template only. Something like this - <form> <label>Customer Name:</label> {{ customer.customer_name }} <br> </form> Is it possible? -
How to annotate sum over Django JSONField (Array of objects) data?
I have models sth like this # models.py class MyModel( models.Model ): orders = models.JsonField(null= True, blank=True, default=list) category = models.ForeignKey(Category, on_delete=models.CASCADE) I stored json data in this structure. [ { "order_name": "first order", "price": 200 }, { "order_name": "second order", "price": 800 }, { "order_name": "third order", "price": 100 } ] I want to sum price of all json objects ie 200+800+100 -
Block title in child template does not override
I have been trying to inherit from the base.html template of my application but when I override the block title it in the child template does not render it. I have read and the read the documentation but I don not see what I am doing wrong. Hereunder is my code: Base.html <!DOCTYPE html> <html lang="en"> <head> <!-- Required meta tags --> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384- EVSTQN3/azprG1Anm3QDgpJLIm9Nao0Yz1ztcQTwFspd3yD65VohhpuuCOmLASjC" crossorigin="anonymous"> <title>{%block title %} {%endblock%}</title> </head> <body> <script src="https://cdn.jsdelivr.net/npm/bootstrap@5.0.2/dist/js/bootstrap.bundle.min.js" ntegrity="sha384-MrcW6ZMFYlzcLA8Nl+NtUVF0sA7MsXsP1UyJoMp4YLEuNSfAP+JcXn/tWtIaxVXM" crossorigin="anonymous"></script> {%block content %} {%endblock content %} </body> Childtemplate, {% extends 'simple_investing/base.html' %} <head> <title>{% block title %} Welcome to Simple Investing {% endblock%}</title> </head> {%block content%} <body> <br> <p style = "font-style: normal">This website has the goal of assisting <strong><em>you</em> </strong> in the process of making <strong><em>sound investment decisions</em></strong> in the <i>stock market</i>. In order to accomplish this goal we focus on:</p> <ul> <li><p> Basic concepts that everyone should know before making an investment.</p></li> <li><p> Providing the tools necessary to analyze the fundamentals of any public company. You can create a portfolio of companies that you are interested in.</li><p> </ul> <br> <p>Let's start by learning the main <a href ="http://127.0.0.1:8000/concepts">concepts.</a> </p> <p>If you already have a … -
Django Form Not Sending File via Modal
I'm trying to upload a file via a form inside a bootstrap modal. request.POST correctly shows the file name in QueryDict, but request.FILES shows an empty MultiValueDict. For comparison, I also tried another version of the form that is exposed in the page, which seems to be working perfectly. What's the difference? Thanks. <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <link href="https://cdn.jsdelivr.net/npm/bootstrap@5.1.0/dist/css/bootstrap.min.css" rel="stylesheet" integrity="sha384-KyZXEAg3QhqLMpG8r+8fhAXLRk2vvoC2f3B09zVXn8CA5QIVfZOJ3BCsw2P0p/We" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.7/umd/popper.min.js"></script> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/js/bootstrap.min.js"></script> </head> <body> <!-- UPLOAD FILE --> <form action="." method='post' enctype="multipart/form-data"> {% csrf_token %} {{ file_form.as_p }} <input type="submit" value="Upload"> </form> <!-- MODAL VERSION --> <a href="#" type="button" class="btn" data-toggle="modal" data-target="#statusModal"> Modal </a> <div class="modal fade" id="statusModal" tabindex="-1" role="dialog" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog" role="document"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">UPLOAD FILE</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <form action =".?&status=status-update" enctype="multipart/form-data" method = "post"> <div class="modal-body"> {% csrf_token %} {{ file_form.as_p }} </div> <div class="modal-footer"> <input class="btn green-button" type = "submit" value = "Send"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> </div> </form> </div> </div> </div> </body> </html> views.py: from django.shortcuts import render, redirect from upload_file.forms import FileForm from upload_file.models import File def index(request): if request.method == "POST": print(request.POST) print(request.FILES) file_form … -
Django: How can I create a function in models to get the username that made that post and also in views
I am creating a forum and i’ve been paralized with this problem, i can’t create a model to get the username of the user that made a post in the forum, i made a search and found nothing hope someone can help me -
Requests in Vuejs returning different response than Postman from django-rest-framework backend
I have been trying to implement the Twitch user authorization code flow. I am working on getting the authorization url generated from the django backend and pass it to my Vue front end so the user can open the user authorization page. Postman recovers the generated url perfectly however when i try to do the same in Vue using Requests it is giving me an entirely different object. Object { _events: {…}, _eventsCount: 1, _maxListeners: undefined, uri: {…}, method: "POST", readable: true, writable: true, explicitMethod: true, _qs: {…}, _auth: {…}, … } auth.js:37:12 and here is what Postman returns "{'url': 'https://id.twitch.tv/oauth2/authorize', 'client_id': 'xxx', 'redirect_uri': 'http://localhost:8000/api/twitch/callback', 'grant_type': 'token', 'scope': 'user_read'}" I'm not sure what could be causing this. Below is the code used to get to this point. urls.py from django.conf.urls import url from django.urls import include, path from better_auth import views urlpatterns = [ url(r'^api/token$', views.get_twitch_token), url(r'^api/auth/login$', views.get_twitch_user_token_uri), url(r'^api/auth/twitch/callback$', views.save_twitch_user_token), ] views.py import json import os import requests from django.http.response import JsonResponse from rest_framework.decorators import api_view from rest_framework import status # get user access token @api_view(['POST']) def get_twitch_user_token_uri(request): endpoint = "https://id.twitch.tv/oauth2/authorize" token_url = { 'url': endpoint, 'client_id': settings['TWITCH_CLIENT_ID'], 'redirect_uri': settings['TWITCH_REDIRECT_URI'], 'grant_type': 'token', 'scope': 'user_read' } Json = json.dumps(token_url) Json = … -
can't passe form's attrs in ModelForm to Template
I'm trying to set a ModelForm, but when I don't get the attrs that I set in my Form in the Template. also I wan't to get the date input in the format dd/mm/yyyy, this is my model: class Delivery(models.Model): user = models.ForeignKey(Customer, on_delete=models.CASCADE, related_name=_("delivery_user")) full_name_reciever = models.CharField(_("Reciever Full Name"), max_length=50) pickup_address = models.ForeignKey(Address, on_delete=models.CASCADE, related_name=_("pickup_address")) destination_address = models.CharField(max_length=250) destination_city = models.ForeignKey(City, on_delete=models.CASCADE, related_name=_("delivery_city")) destination_post_code = models.CharField(max_length=20) operation_date = models.DateField( _("desired pickup date"), auto_now=False, auto_now_add=False, blank=False, null=False ) boxes_number = models.PositiveIntegerField(_("Number of Boxes"), default=1) boxes_wight = models.PositiveIntegerField(_("Boxes Wight"), default=1) boxes_volume = models.PositiveIntegerField(_("Boxes Volume"), default=0) document = models.FileField( help_text=_("Delivery Documets"), verbose_name=_("Delivery Certificates"), upload_to="documents/deliveries_documents/", ) invoice = models.BooleanField(_("check if you want an invoice"), default=False) created_at = models.DateTimeField(_("Created at"), auto_now_add=True, editable=False) updated_at = models.DateTimeField(_("Updated at"), auto_now=True) delivery_key = models.CharField(max_length=200) billing_status = models.BooleanField(default=False) delivery_status = models.BooleanField(default=False) class Meta: ordering = ("-created_at",) verbose_name = _("Delivery") verbose_name_plural = _("Deliveries") def __str__(self): return str(self.created_at) The ModelForm: class UserDeliveryForm(forms.ModelForm): class Meta: model = Delivery fields = [ "full_name_reciever", "pickup_address", "destination_address", "destination_city", "destination_post_code", "operation_date", "boxes_number", "boxes_wight", "boxes_volume", "document", "invoice", "delivery_key", "billing_status", "delivery_status", ] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) self.fields["full_name_reciever"].widget.attrs.update( {"class": "form-control mb-2 delivery-form", "Placeholder": "full name reciever "} ) self.fields["pickup_address"].widget.attrs.update( {"class": "form-control mb-2 delivery-form", "Placeholder": "pickup address "} … -
How to solve django.utils.datastructures.MultiValueDictKeyError: 'image'
details.html <html> <head> <title> Python button script </title> </head> <body> <h1>Hello</h1> {% if Button_number != 0 %} <form method="POST"> {% csrf_token %} <select name="buttonColor" id="buttonColor"> <option selected disabled="true">Select color</option> <option value="Red">Red</option> <option value="Blue">Blue</option> <option value="Green">Green</option> </select> <input type="submit" value="Insert" /> </form> {% endif %} </body> </html> home.html <!DOCTYPE html> <html> <head> <title> Python button script </title> </head> <body> <form action="/external/" method="post" enctype="multipart/form-data"> {% csrf_token %} Input Image: <input type="file" name="image" required> <br><br> <input type="submit" value="Enter Image"> </form> </body> </html> views.py from django.shortcuts import render from django.core.files.storage import FileSystemStorage import pytesseract from PIL import Image from .models import insertbutton from django.contrib import messages def button(request): return render(request,'home.html') def external(request): imagetry=request.FILES['image'] print("image is ",imagetry) fs=FileSystemStorage() filename=fs.save(imagetry.name,imagetry) print(filename) im = Image.open(imagetry) text = pytesseract.image_to_string(im) #-------------image processing--------------- return render(request, 'details.html', {'Button_number': Button_number, 'button_heights': button_heights, 'button_widths': button_widths }) def allData(request): if request.method == "POST": if request.POST.get('buttonColor'): saveValue = insertbutton() saveValue.buttonColor = request.POST.get('buttonColor') saveValue.save() return render(request, 'another.html') else: return render(request, 'another.html') urls.py from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.button, name='home'), path('external/', views.external, name='script'), path('external/details', views.external, name='script'), path('another/', views.allData), ]+ static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) The error After inserting color. [04/Sep/2021 02:17:07] "POST /external/ HTTP/1.1" 200 704 Internal Server Error: /external/ Traceback (most recent call last): … -
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 %}