Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
No module named... in Django proyect
I have a pretty standart Django project and i can't find a way to import /middleware/utils/compare.py from /middleware/utils/request.py This is the proyect tree: |--middleware/ | |--utils/ | | |--compare.py | | |--request.py | |--__init__.py | |--asgi.py | |--settings.py | |--urls.py | |--views.py | |--wsgi.py |--manage.py Where __init__.py, asgi.py, settings.py, urls.py, wsgi.py have no major modifications. (__init__.py is empty) # middleware/views.py from .utils.request import requests # This line works fine # middleware/utils/request.py from compare import compare # ModuleNotFoundError: No module named 'compare' from .compare import compare # Attempted relative import beyond top-level package pylint(relative-beyond-top-level) # ^^^ This line absolutly breaks my code, but it runs from utils.compare import compare # ModuleNotFoundError: No module named 'utils' from .utils.compare import compare # ModuleNotFoundError: No module named 'middleware.utils.utils' Note: compare.py has a function named compare, i also tried renaming it but had the same problems. This might be obvious, but i run the proyect with python manage.py runserver -
Create Array from Model Data in Django Template in <script>
I am trying to use JQuery date picker and I want to make use of the beforeShowDay method in order to block out dates in the date picker. I have been able to get the widget to work and if I define an array, the beforeShowDay method works flawlessly. But my issue is passing the data from my Django model to create an array. Is there a way to create an array within the element in the template in order to achieve this? template <script> # works as intended when the array is defined manually var array = [ "2022-10-01" ] # this is where I am having trouble creating an array from the model data var array = [ {% for x in listing_reservations %} {{x.dates}} {% endfor %} ] $(function() { $( "#id_start_date" ).datepicker( { beforeShowDay: function(date){ var string = jQuery.datepicker.formatDate('yy-mm-dd', date); return [ array.indexOf(string) == -1 ]; } } ); }); </script> -
'EntryPoints' object has no attribute 'get' - Digital ocean
I have made a deplyoment to Digital ocean, on staging (Heroku server) the app is working well, but Digital ocean it's failing with the error below, what could be the issue : AttributeError at /admin/ 'EntryPoints' object has no attribute 'get' Request Method: GET Request URL: https://xxxx/admin/ Django Version: 3.1 Exception Type: AttributeError Exception Value: 'EntryPoints' object has no attribute 'get' Exception Location: /usr/local/lib/python3.7/site-packages/markdown/util.py, line 85, in <module> Python Executable: /usr/local/bin/python Python Version: 3.7.5 Python Path: ['/opt/app', '/usr/local/bin', '/usr/local/lib/python37.zip', '/usr/local/lib/python3.7', '/usr/local/lib/python3.7/lib-dynload', '/usr/local/lib/python3.7/site-packages', '/usr/local/lib/python3.7/site-packages/odf', '/usr/local/lib/python3.7/site-packages/odf', '/usr/local/lib/python3.7/site-packages/odf', '/usr/local/lib/python3.7/site-packages/odf', '/usr/local/lib/python3.7/site-packages/odf', '/usr/local/lib/python3.7/site-packages/odf', '/usr/local/lib/python3.7/site-packages/odf'] Server time: Sun, 02 Oct 2022 21:41:00 +0000 -
Staging syntax error while creating Django model instance
from customer.models import Customer; cust = Customer.objects.create_user(first_name=\"'$first_name'\", last_name='\"'$last_name'\", uuid='\"'$uuid'\"); Getting these errors for the last name: Staging: -c: unexpected EOF while looking for matching `"' Staging: -c: syntax error: unexpected end of file I have tried last_name=$'$last_name' but that does not work and I need it to still be a string if given an empty string. This is in a bash script. -
How to sort a queryset based on a foreign key field?
This is a contest system project. I have these models and I know the contest_id and problem_id. I'm trying to return a queryset that contains users who have solved a problem. A user who solves a problem is the one whose submission's score is equal to score of the problem he tried to solve. At the end I need to sort these users based on the time they have submitted their successful submission. class Contest(models.Model): name = models.CharField(max_length=50) holder = models.ForeignKey(User, on_delete=models.CASCADE) start_time = models.DateTimeField() finish_time = models.DateTimeField() is_monetary = models.BooleanField(default=False) price = models.PositiveIntegerField(default=0) problems = models.ManyToManyField(Problem) authors = models.ManyToManyField(User, related_name='authors') participants = models.ManyToManyField(User, related_name='participants')so class Problem(models.Model): name = models.CharField(max_length=50) description = models.CharField(max_length=1000) writer = models.ForeignKey("accounts.User", on_delete=models.CASCADE) score = models.PositiveIntegerField(default=100) class Submission(models.Model): submitted_time = models.DateTimeField() participant = models.ForeignKey(User, related_name="submissions", on_delete=models.CASCADE) problem = models.ForeignKey(Problem, related_name="submissions", on_delete=models.CASCADE) code = models.URLField(max_length=200) score = models.PositiveIntegerField(default=0) I tried following code but I don't get wrong answer. How can I sort my QuerySet? def list_users_solved_problem(contest_id, problem_id): problem_score = Problem.objects.get(id=problem_id).score successful_submissions_ids = Submission.objects.filter(Q(score=problem_score) & Q(problem_id=problem_id)) \ .values_list('participant__id', flat=True) return Contest.objects.get(id=contest_id).participants.order_by('submissions__submitted_time') -
Setting environment variables using activate.bat
I am using PyCharm on Windows and want to set the environment variables for Django website. I am setting the values in the project's venv: activate.bat @echo off set "VIRTUAL_ENV=D:\Git\QV-PublicWebsite\venv" set DJANGO_SECRET_KEY='random' ... activate.ps1 ... $VIRTUAL_ENV = $BASE_DIR $env:VIRTUAL_ENV = $VIRTUAL_ENV $env:DJANGO_SECRET_KEY='random' ... When I load the project in PyCharm, I can see that the venv is active. But when I start debugging the project, I am not able to read the values: This is the settings that I have for debugging the project: -
How to solve Django ValueError: Field 'id' expected a number
I am making filters in Django to select data from a database. Now it looks like: view.py: def get_current_user(request): current_user = request.user return current_user def is_valid_query_param(param): return param != '' and param is not None def bootstrapFilterView(request): user = get_current_user(request) qs = CompletedWork.objects.filter(checked_by_head=True) struct_divisions = StructuralDivisions.objects.filter( Q(head=user) | Q(management_unit__head=user) | Q(curator=user) | Q(management_unit__curator=user) ) workers = CustomUser.objects.filter( Q(struct_division__head=user) | Q(struct_division__management_unit__head=user) | Q(struct_division__curator=user) | Q(struct_division__management_unit__curator=user) ) workstype = WorksType.objects.filter( Q(available_to__head=user) | Q(available_to__curator=user) ).distinct() work_notes_contains_query = request.GET.get('work_notes_contains') work_scope_min = request.GET.get('work_scope_min') work_scope_max = request.GET.get('work_scope_max') period_min = request.GET.get('period_min') period_max = request.GET.get('period_max') struct_division = request.GET.get('struct_division') worker = request.GET.get('worker') work_done = request.GET.get('work_done') if is_valid_query_param(work_notes_contains_query): qs = qs.filter(work_notes__icontains=work_notes_contains_query) if is_valid_query_param(work_scope_min): qs = qs.filter(work_scope__gte=work_scope_min) if is_valid_query_param(work_scope_max): qs = qs.filter(work_scope__lte=work_scope_max) if is_valid_query_param(period_min): qs = qs.filter(period__date__gte=period_min) if is_valid_query_param(period_max): qs = qs.filter(period__date__lte=period_max) if is_valid_query_param(struct_division) and struct_division != 'Choose...': qs = qs.filter(worker__struct_division__name=struct_division) if is_valid_query_param(worker) and worker != 'Choose...': qs = qs.filter(worker=worker) if is_valid_query_param(work_done) and work_done != 'Choose...': qs = qs.filter(work_done__name=work_done) context = { 'queryset': qs, 'struct_divisions': struct_divisions, 'workers': workers, 'workstype': workstype, } return render(request, 'bootstrap_form.html', context) All works well, except: if is_valid_query_param(worker) and worker != 'Choose...': qs = qs.filter(worker=worker) It's return ValueError at /boot/ Field 'id' expected a number but got 'Chambers Jessica '. I tried different syntax, but nothing helped How … -
Handling JSON response from a Django QuerySet via AJAX
I am getting a JSON response from a Django view. def loadSelectedTemplate(request): # request should be ajax and method should be GET. if request.is_ajax and request.method == "GET": # get the template matching the ID templateID = request.GET.get("templateID", None) # check for the template matching ID in the database. template = list(operationTemplates.objects.filter(templateID = templateID)) if operationTemplates.objects.filter(templateID = templateID).exists(): # if template found return record ser_template = serializers.serialize('json', template ) return JsonResponse({"valid": True, "template": ser_template}, status=200) else: # if nick_name not found, then user can create a new friend. return JsonResponse({"valid": False}, status = 200) the response is received can be logged to the console. // GET AJAX request $.ajax({ type: 'GET', url: "{% url 'loadSelectedTemplate' %}", data: {"templateID": templateID}, success: function (response) { // if valid template, add to textarea if (response["valid"]){ var template = response["template"]; console.log(response); } Json object looks like this; { "valid": true, "template": "[{\"model\": \"opnoteannotator.operationtemplates\", \"pk\": 14, \"fields\": {\"templateCategory\": \"Lower Limb\", \"templateName\": \"Femoral to below knee Bypass using autologous vein\", \"templatePreopBundle\": \"WHO check list completed.\\r\\n Antibiotic Chemoprophylaxis: Co-amoxiclav / Teicoplanin / Gentamicin\", \"templateIndication\": \"CLTI with night pain / rest pain / tissue loss / infection\", I want to add the objects in "fields" to a textarea … -
How to pass a dynamically changing variable from python to HTML and get the browser to re-render the new data without reloading the whole web-page?
I would like to achieve the following: pass a variable from my python script to a HTML page get the browser to display the updated information DO NOT re-render, or reload the WHOLE HTML page as this would take too long (new data will be transmitted from the python script to the HTML page every 250ms or so.) data is generated live by the python script and so the solution have to take this into account After researching the whole day and watching numerous tutorials, I understood that Flask or Django could be used to achieve this via a concept called "templating". Unfortunately I am complete beginner and I got lost in the details without seeing the "big picture" of what is need to be done... So I ended up here, hoping someone can clear up my understanding about the topic without assuming any previous knowledge... So I have a super simple HTML file as below: <!DOCTYPE html> <html> <head> <title>Simple Test</title> </head> <body> <h1>Changing Number:</h1> <h1 id="number">0</h1> and I also have a python script: import random import time for i in range(10): myvar = random.randint(1, 10) time.sleep(1) The goal is to pass myvar to the html element with the … -
how to access an element from a list of dictionaries
I'm trying to build a cart view following a tutorial and I need to print out the quantity of an item. I have two functions in utils.py from where I wanna access the quantity element and print it out in a view, currently getting an error unhashable type: 'list' def cookieCart(request): try: cart = json.loads(request.COOKIES['cart']) except: cart = {} print('Cart:', cart) items = [] order = {'get_cart_total': 0, 'get_cart_items': 0, 'shipping': False} cartItems = order['get_cart_items'] for i in cart: try: cartItems += cart[i]["quantity"] product = Product.objects.get(id=i) total = (product.final_price * cart[i]["quantity"]) order['get_cart_total'] += total order['get_cart_items'] += cart[i]["quantity"] item = { 'product':{ 'id':product.id, 'name':product.name, 'final_price':product.final_price, 'image_URL':product.image_URL, }, **#print the quantity on view** 'quantity':cart[i]["quantity"], 'get_total':total, } items.append(item) except: pass return {"items": items, "order": order, "cartItems": cartItems} def cartData(request): if request.user.is_authenticated: customer = request.user.customer order, created = Order.objects.get_or_create(customer=customer, complete=False) items = order.orderitem_set.all() cartItems = order.get_cart_items else: cookieData = cookieCart(request) cartItems = cookieData['cartItems'] order = cookieData['order'] items = cookieData['items'] return {'cartItems':cartItems ,'order':order, 'items':items} def my_view(request): data = cartData(request) qty = data['item',['quantity']] print(qty) -
nginx not serving statick files django 4.1
i am new in deploy projects my static files not serving with nginx thats look my site-available/myprject file server{ listen 80; server_name mydomain; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { autoindex on; alias /home/user/project/static; } location /media/ { autoindex on; alias /home/user/project/media; } location / { proxy_pass myIp:myPort; } } my static files and media have this path /home/user/project/staict files and media files that's how it looks my settings.py configurations STATIC_URL = '/static/' STATIC_ROOT =os.path.join(BASE_DIR,'static') my debug variable is false i run collectstatic thanks for any answers. -
why I'm getting "Not Found: /api/v1.0/productos/${this.id_product}/"
I got a problem with vue.js. I made a CRUD, and got an issue trying to use PUT to update. when I applied this method to send update information to Django, an error appeared: METHOD IN VUE.JS methods: { onSubmit(evt){ evt.preventDefault() const path = 'http://127.0.0.1:8000/api/v1.0/productos/${this.id_product}/' axios.put(path, this.form).then((response) => { this.form.nombreProd = response.data.nombreProd this.form.precioProd = response.data.precioProd this.form.contenido = response.data.contenido this.form.descripcionProd = response.data.descripcionProd alert("Actualización exitosa") }) .catch((error) => { console.log(error) }) } ANSWER IN DJANGO Not Found: /api/v1.0/productos/${this.id_product}/ [02/Oct/2022 12:57:46] "PUT /api/v1.0/productos/$%7Bthis.id_product%7D/ HTTP/1.1" 404 2609 Trying to understand, I realized that it could be an issue with the curly braces, but I don´t know how to solve it -
Django: Nested Loop In Template
category = ['cat1','cat2','cat3'] inventory = CurrentInventory.objects.all() for cats in categories inventorybycat = inventory.filter(category =cats) setofinventories.append(inventorybycat) dictofstuff = [zip(setofinventories,categories)] context = { 'setofinventories':setofinventories 'category':category 'dictofstuff':dictofstuff } In views.py above this loop creates a list of objects per each category. In the template below this loop prints a filtered object list per every item in the category list. {% for inventory in setofinventories%} {% for item in inventory %} {{ item.category }} {{ item.productName }} {% endfor %} {% endfor %} The only thing I am missing is I do not now how to reference the category in the template. I pass the whole list in context, but {{category{{forloop.counter}}}} is not a valid statement. I would either like to use zip(category,setofinventories) to pass these two items together, or create a category model, filter by that model and then I can reference that model by item? If I zip these items dictofstuff = [zip(setofinventories,categories)] How do I reference the category in the template? {% for inventory in setofinventories%} {{categories{{[forloop.counter]}}}}#This line does not work {% for item in inventory %} {{ item.category }} {{ item.productName }} {% endfor %} {% endfor %} -
Poblem when updating a table using celery task: OperationalError
I use Celery task and got an error I do not understand. I loop over a table (that contain query definitions) to edit missing/inconsistent data in a database (using API) and registered discrepencies in another table. If I run query one at a time, it works but when I try to loop over queries, I got an error OperationalError('server closed the connection unexpectedly\n\tThis probably means the server terminated abnormally\n\tbefore or while processing the request.\n') def DCF_edition(self): DCF_BEFORE_UPDATE = pd.DataFrame.from_records(DataCorrectionForm.objects.all().values()) DCF_BEFORE_UPDATE = DCF_BEFORE_UPDATE.astype({'record_date': str,'created_date': str}) if not DCF_BEFORE_UPDATE.empty else DCF_BEFORE_UPDATE data = [] # load queries definition queries = queries_definitions() if not queries.empty: for index, row in queries.iterrows(): try: missing_or_inconsistent = missing_or_inconsistent_data(row['ide'],row['query_type'],row['crf_name'].lower(),row['crf identification data.append(missing_or_inconsistent[['dcf_ide','category','crf','crf_ide','pat','record_date','field_name','field_label','message','field_value','dcf_status','DEF','deactivated']]) DCF_AFTER_UPDATE = pd.concat(data) DCF_AFTER_UPDATE = DCF_AFTER_UPDATE.drop_duplicates(keep='last') DCF_AFTER_UPDATE = DCF_AFTER_UPDATE.drop(['DEF'], axis=1) DCF_AFTER_UPDATE.rename(columns = {'pat':'patient',}, inplace = True) except Exception as e: Log.objects.create(dcf_edition_status=0,dcf_edition_exception=str(e)[:200]) continue # Cast date into string format to be able to dumps data DCF_AFTER_UPDATE = DCF_AFTER_UPDATE.astype({'record_date': str}) if not DCF_AFTER_UPDATE.empty else DCF_AFTER_UPDATE records = json.loads(json.dumps(list(DCF_AFTER_UPDATE.T.to_dict().values()))) for record in records: if not DCF_BEFORE_UPDATE.empty and record['dcf_ide'] in DCF_BEFORE_UPDATE.values: DataCorrectionForm.objects.filter(dcf_ide=record['dcf_ide']).update(dcf_status=2) else: DataCorrectionForm.objects.get_or_create(**record) # resolved dcf => status=0 if not DCF_BEFORE_UPDATE.empty: records = json.loads(json.dumps(list(DCF_BEFORE_UPDATE.T.to_dict().values()))) for record in records: if record['dcf_ide'] not in DCF_AFTER_UPDATE.values: DataCorrectionForm.objects.filter(dcf_ide=record['dcf_ide']).update(dcf_status=0) Log.objects.create(dcf_edition_status=1) return True -
request not sent from other device in the same network in reactjs/nextjs and django back-end
I have Reactjs and Nextjs front-end and Django backend my laptop IP is: xx.xx.xx.xx I run Django on loopback IP my requests do not send when I connect my front-end with another device with my laptop IP These two devises are in the same network no logs in laptop browser and backend logger -
Django Website Http Error 405; Method Not Allowed (POST): /dashboard/
I am trying to access my 'dashboard' page after signing in on the 'login' page in Django. The url in is throwing http error 405. If I replace the url with another page (eg: 'dbtable') it works absolutely fine. Below is my code in django: urls.py: urlpatterns = [ path('',views.register_login, name='login'), path('dashboard/', DashboardPageView.as_view(), name='dashboard'), path('dbtable/', views.DBTableView, name = 'dbtable'), ] views.py (includes login view and dashboard view): def register_login(request): form = UserCreationForm() if "register" in request.method == 'POST': form = UserCreationForm(request.POST) == "Register" if form.is_valid(): form.save() user = form.cleaned_data['username'] messages.success(request,"Account was Created for " + user) context = {'form':form} return render(request,'login.html',context) if "login" in request.method == "POST": if request.POST['submit'] == 'Login': username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) if user is not None: login(request,user) return redirect('login') else: messages.error(request, 'Wrong Username or password') context = {} return render(request,'login.html',context) class DashboardPageView(TemplateView): template_name = 'dashboard.html' def get_context_data(self, **kwargs): # Call the base implementation first to get a context context = super(DashboardPageView, self).get_context_data(**kwargs) context['plot'] = plot1.cumulative_plot() return context login.html: <!-- SIGN IN --> <div class="col align-items-center flex-col sign-in"> <div class="form-wrapper align-items-center"> <div class="form sign-in"> <div class="input-group"> <form action = "{% url 'dashboard' %}" method="POST" name="login" value="login"> {% csrf_token %} <i … -
string list as a parameter in url in django
i am working in a search view which take two inputs as a filter : search word 2.cities (multi select) i did it using serializer and it worked but paggination does not work because it was a post method , so i'm trying to take these inputs from url parameters , i tried this pattern : path(r"search/<str:search>/(?P<city>\w*)/", SearchView.as_view({"get": "search"}), name="search"), but when i browse : http://127.0.0.1:8000/company/search/taxi/montrial/ it return Not Found: /company/search/ so how to pass the paramteres or is there another way to use paggination with post method -
Send mail using email from user database in django
In Django how can i send email to user by importing email from user database. from django.contrib.auth.models import User class PostCreateView(LoginRequiredMixin, CreateView): model = Post form_class = AdsForm def form_valid(self, form): email = User.email # try to import email from user model database. subject = 'Thanks for adding your trip' message = f'Hi {email}, thank you for Adding your Trip .' email_from = 'xyz@gmail.com' recipient_list = [email] send_mail(subject, message, email_from, recipient_list, fail_silently=False) form.instance.author = self.request.user return super().form_valid(form) In this form i tried to send email to the user that adding trip, the email i tried to pickup from User database. And i get this error while sending the mail. Help would be appreciated as Iam beginner to Django and programming. -
How to delete a specific Django cache by the name of the cache fragment?
Let's assume I don't want to clear the whole cache, but only a specific fragment. I have this in my template: {% cache 500 sidebar %} .. sidebar .. {% endcache %} I know about cache.delete(key), but how can I find the key based on the cache fragment name "sidebar"? I'm using FileBasedCache cache. When I used Redis Cache, there was keys() method which allowed to find the key based on a name pattern, but it doesn't work with FileBasedCache. -
My model form is not showing in the browser. It only appear after I click the submit button as a required field to be filled
My model form is not showing in the browser. It only appear after I click the submit button as a required field to be filled. I have searched similar problems but the context was just a little different and the fixes couldn't work on my project. My models from django.contrib.auth.models import AbstractUser from django.db import models class User(AbstractUser): pass class Post(models.Model): body = models.TextField() date = models.DateTimeField(auto_now_add = True) author = models.ForeignKey(User, on_delete=models.CASCADE, related_name="author", default=None) def __str__(self): return f"{self.body} by {self.author} at {self.date}" Forms.py from django import forms from django.forms import ModelForm from .models import Post class PostForm(ModelForm): class Meta: model = Post fields = ['body'] widgets = { "body": forms.Textarea(attrs={'class': 'form-control col-md-5 col-lg-6'}), } Views.py def create_post(request): posted = False if request.method == "POST": form = PostForm(request.POST) if form.is_valid(): instance = form.save(commit=False) instance.author = request.user instance.save() return HttpResponseRedirect("/create_post?posted=True") else: form = PostForm() if "posted" in request.GET: posted = True return render(request, "network/create_post.html", { "form": form, "posted": posted }) Urls from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("create_post", views.create_post, name="create_post"), path("create_post_page", views.create_post_page, name="create_post_page") ] The template {% extends "network/layout.html" %} {% block body %} … -
django Broken pipe from ('127.0.0.1', 49903)
enter code hereI got this error when I passed an id in the URL. Please check my below code. href url urls from django.contrib import admin from django.urls import path from he_admin import views app_name='he_admin' urlpatterns = [ path('',views.index,name='index'), path('addproductscategory',views.add_products_category,name='addcategory'), path('showcategories',views.ShowCategory,name='showcategories'), path('view/int:pk',views.ViewCategory,name='viewcategory'), ] view function def ViewCategory(request, pk): try: category=ProductCategory.objects.get(id=pk) except: raise Http404('category does not exist') return render(request,"viewcategory.html",{"category":category}) error -
Django static files get from wrong url
I am migrating an old Django 2.2 project to Django 3.2. I use AWS Cloudfront and S3. I have done most of the tasks to do. But i have something weird in my static files serving. When 'static' template tag is called, the rendered url is "https//<cloudfront_url>/static.." instead of "https://<cloudfront_url>/static..". The comma disapears ! It obviously results to a 404 not found. It worked without any problem on Django2.2. So for the moment i dirty patched this by doing a '.replace("https//", "https://")' on django static template tag. My settings relatives to static files are : # settings.py STATICFILES_LOCATION = 'static' AWS_CLOUDFRONT_DOMAIN = <idcloudfront>.cloudfront.net STATICFILES_STORAGE = 'app.custom_storages.StaticStorage' STATIC_URL = "https://%s/%s/" % (AWS_CLOUDFRONT_DOMAIN, STATICFILES_LOCATION) AWS_STORAGE_STATIC_BUCKET_NAME = 'assets' # app.custom_storages.py class StaticStorage(S3Boto3Storage): location = settings.STATICFILES_LOCATION bucket_name = settings.AWS_STORAGE_STATIC_BUCKET_NAME def __init__(self, *args, **kwargs): kwargs['custom_domain'] = settings.AWS_CLOUDFRONT_DOMAIN super(StaticStorage, self).__init__(*args, **kwargs)``` -
User uploaded images not serve after debug=false in django?
install whitenoise urls.py setting urlpatterns += static(settings.STATIC_URL, document_root = STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root = MEDIA_ROOT) urlpatterns += [re_path(r'^media/(?P<path>.*)$', serve, {'document_root': settings.MEDIA_ROOT, }), ] also configure static root and static url in settings.py STATIC_URL = '/static/' MEDIA_URL = '/images/' STATIC_ROOT = BASE_DIR / 'staticfiles' MEDIA_ROOT = BASE_DIR / '/static/images/' STATICFILES_DIRS = [(os.path.join(BASE_DIR, 'static'))] -
How to run python scripts on button click in React?
I don't know how to run .py file on clicking a button in ReactJS . All i want is to fetch the data created by the .py file using flask on clicking a button in React application . I set up a link on that button which will redirect to another webpage on which i want to display that fetched data. The React app and the .py file are on the same machine. I have no idea on how to do this . My app.js file in React app runs on "http://localhost:3000" const onClickHandler = () => { //fetching the data from the server localhost:5000/page_name const url = "http://localhost:5000/user"; const [name, setName] = useState(""); const [password, setPassword] = useState(""); try { const res = await fetch(url); const data = await res.json(); console.log(data); setName(data.name); setPassword(data.password); } catch (error) { console.log(error); } }; return( <div> <button onClick={onClickHandler}>Click me</button> {name} {password} </div> ); My .py file runs on "http://localhost:5000/my_link" from flask import Flask from flask_cors import CORS app = Flask(__name__) CORS(app) @app.route('/data',methods=['GET', 'POST']) def my_link(): print("I got Clicked") return {'name': "geek", "password": "This is PWD"} if __name__ == '__main__': app.run(debug=True) Please help me with this . Thanks in advance . -
How to pass a string to a django url path through a hyperlink
I am creating a Django website that shows overwatch maps for strategic purposes. I have created a page that shows all the maps. Each map is wrapped in a hyperlink that is supposed to dynamically display information about that map. <div id="item"> <a href="{% url 'overwatch:maps/blizzard' %}"> <img src="{% static 'pics/blizzard-world.jpg' %}" alt="Blizzard World" /> </a> </div> When you click on the map picture I want the url to send a string to the url path: app_name = "overwatch" path('maps/<str:mapName>', views.mapStrategies, name='maps/<str:mapName>'), After that this view is supposed to be rendered. def mapStrategies(request, mapName): return render(request, "overwatch/maps/mapStrategies.html", { "mapName": mapName }) The url pattern is not recognized when the map is clicked on. However I can type in the url and it works just fine.