Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
User Specific Page in TODO List
I am making a simple todolist application but while I am trying to create user specific pages, I am unable to add a new task probably beacause database is not getting all required datas(i.e. owner of the task). models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class value(models.Model): task=models.CharField(max_length=200) complete=models.BooleanField(default=False) created=models.DateTimeField(auto_now_add=True) owner=models.ForeignKey(User,on_delete=models.PROTECT) def __str__(self): return self.task views.py from http.client import HTTPResponse from urllib import response from django.shortcuts import render,redirect from todo.models import value from django.http import HttpResponseRedirect from django.contrib.auth.decorators import login_required from django.contrib.auth.models import User # Create your views here. from .forms import TitleForm from django.urls import reverse from django.contrib.auth.models import User def home(request): values=value.objects.all() form=TitleForm() if request.method=='POST': form=TitleForm(request.POST) if form.is_valid(): new_data=form.save(commit=False) new_data.owner=request.user() new_data.save() return HttpResponseRedirect('/') context={'form':form,'values':values} return render(request,'home.html',context) #update def update(request,id): ggwp=value.objects.get(id=id) form=TitleForm(instance=ggwp) if request.method == 'POST': form=TitleForm(request.POST,instance=ggwp) if form.is_valid: form.save() return redirect('home') context={'form':form,} return render(request,'update.html',context) #delete def delete_data(request, id ): if request.method=="POST": ggwp=value.objects.get(id=id) ggwp.delete() return HttpResponseRedirect(reverse('deldata', kwargs={'id':id})) return redirect("/") forms.py from django import forms from django.forms import ModelForm from .models import value from django import forms class TitleForm(forms.ModelForm): class Meta: model= value fields='__all__' urls.py(app) from django.conf.urls import url from django.urls import path from . import views urlpatterns=[ path('',views.home,name='home'), path('delete/<str:id>', views.delete_data,name='deldata'), path('update/<str:id>',views.update,name='update') ] … -
How to pass one of the form field's data to another page using class based views in Python/Django?
I am working on a project where I present a form to the user asking about their sports interests to help them find local players to play with. Then I want to return other users who play the same sport. I am using a CreateView when presenting this form and have one model called UserCharacteristics asking these questions. I want to pass the sport the user chose to the ShowMatched view so I can filter the result based on the matching/same sport. In views.py, for the first class based view I am doing: class EnterInfo(LoginRequiredMixin, CreateView): template_name = 'myapp/enterinfo.html' fields = ['name', 'age', 'cityfrom', 'gender', 'sport'] model = UserCharacteristics def form_valid(self, form): form.instance.user = self.request.user return super(EnterInfo, self).form_valid(form) def get_success_url(self): return reverse('showmatched', kwargs={'sport': self.kwargs['sport'] }) For the second class based view in views.py I am doing: class ShowMatched(TemplateView): template_name = 'myapp/showmatched.html' model = UserCharacteristics context_object_name = 'allentries' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['allentries'] = UserCharacteristics.objects.filter(kwargs = {'sport' : self.sport}) return context In urls.py I am doing: path('enterinfo/', EnterInfo.as_view(), name='enterinfo'), path('showmatched/<str:sport>/', ShowMatched.as_view(), name ='showmatched'), In enterinfo.html file I am doing: <p>You are logged in as: {{request.user}}</p> <form action="{% url 'showmatched' sport.id %}" method="post"></form> {% csrf_token %} {{ form.as_p }} <input … -
Fastapi starlette Image Crop
i just wanna image crop in image called UploadFile in starlette. @app.post("/analyze/{type}") def analyze(type: str, image: UploadFile = File(...)): # type value validate if type not in AVAILABLE_TYPES: return {"status": "error", "data": {"error": f"type `{type}` is not supported."}} # req id gen req_id = uuid.uuid4() # save file input_dir = f"{DATA_BASE_DIR}/input/{type}" os.makedirs(input_dir, exist_ok=True) image_path = f"{input_dir}/{req_id}.jpg" with open(image_path, "wb") as buffer: shutil.copyfileobj(image.file, buffer) # send message to rabbitmq send_message(req_id, type, image_path) # return req id return {"status": "done", "data": {"request_id": req_id}} my code is here, i was used bytesIO and pillow library. but it doesn't worked. what should i do? -
nginx and django deployment issues
I seem to be having issues with my django and nginx deployment. Everything was running as normal, i'd navigate cd into /srv/www/repo do the usual git pull origin mybranch activate my venv and run python manage.py collectstatic This was my process, it has worked fine..until now. It seems that the database has shat the bed and I have no idea why. The issue first started when I did python manage.py migrate it was complaining django.db.utils.OperationalError: attempt to write a readonly database. I thought this was odd, but ultimately thought nothing of it. Then another issue popped up that files were missing when running python manage.py collectstatic Anyway, when I tried to take a look at the deployed changes it seems like the database has been completely wiped. I'm not even able to create user to start populating the db again as I'm getting django.db.utils.OperationalError: attempt to write a readonly database I'm not sure what to do? Really hoping someone can point me in the right direction -
Reorder Not Working with Filtered Data Ajax
I implemented a filtered view into my app and now my reordering ajax is not working. My app is a simple view of a data table that is filtered to a user and week (e.g. Rob makes a pick selection for the same group every week). I am using my reorder to allow the user to click and drag their selections into the order that they want. The data is already loaded for all weeks/users, and the user is not creating/deleting options, only ranking them. This was working on non-filtered data, but now it's not responding. ajax: class AjaxReorderView(View): def post(self, *args, **kwargs): if self.request.is_ajax(): data = dict() try: list = json.loads(self.request.body) model = string_to_model(self.kwargs['model']) objects = model.objects.filter(pk__in=list) # list = {k:i+1 for i,k in enumerate(list)} for object in objects: object.rank = list.index(str(object.pk)) + 1 model.objects.bulk_update(objects, ['rank']) # for key, value in enumerate(list): # model.objects.filter(pk=value).update(order=key + 1) message = 'Successful reorder list.' data['is_valid'] = True # except KeyError: # HttpResponseServerError("Malformed data!") except: message = 'Internal error!' data['is_valid'] = False finally: data['message'] = message return JsonResponse(data) else: return JsonResponse({"is_valid": False}, status=400) pick_list: {% extends 'base.html' %} {% load cms_tags %} {% block title %} {{ title }} · {{ block.super }} … -
Render multiple objects from Django model using request function
Working on adding some job listings to the front page of my django site. There are currently 20 jobs listed for testing purposes. I have a fairly simple django model which contains attributes of the such as job status (active, inactive, archived) and the time at which the job listing was created, so that I can order these chronologically. I want to be able to display only the 4 most recent jobs at the tope of the page, whilst displaying the remaining 16 jobs in a list below this. Here's what I've got so far... Models.py from django.db import models class Job(models.Model): ACTIVE = 'active' INACTIVE = 'inactive' ARCHIVED = 'archived' CHOICES_STATUS = ( (ACTIVE, 'Active'), (INACTIVE, 'Inactive'), (ARCHIVED, 'Archived') ) status = models.CharField(max_length=20, choices=CHOICES_STATUS, default=ACTIVE) created_at = models.DateTimeField(auto_now_add=True) In order to then render the jobs on the frontpage of the site I then refer to the job model in a view like below. Views.py from django.shortcuts import render, redirect from apps.job.models import Job def frontpage(request): jobs=Job.objects.filter(status=Job.ACTIVE).order_by('-created_at')[0:4] all_jobs=Job.objects.filter(status=Job.ACTIVE).order_by('-created_at') return render(request, 'core/frontpage.html', {'jobs': jobs, 'jobs':all_jobs}) This does make jobs appear on the frontpage however it seems that the configuration is dictated by the last request, i.e. all_jobs=Job.objects.filter(status=Job.ACTIVE).order_by('-created_at'). I know this because … -
avoid error: 'NoneType' object has no attribute in django model admin
I need to show if a client is having a related contract active or no in customized field in django model admin I tried to use try: but it does not work unfortunately here the original code: class ClientAdmin(ExportModelAdminMixin, ModelAdmin): model = Client menu_icon = "pick" menu_order = 100 exclude_from_explorer = False list_display = ["name", "is_active"] search_fields = ["name"] list_filter = [ClientFilter] index_template_name = "wagtailadmin/export_csv.html" csv_export_fields = ["name"] def is_active(self, client: Client) -> bool: any(site.current_contract.is_active for site in client.sites.all()) is_active.boolean = True # type: ignore is_active.short_description = _("active confirmation") # type: ignore I got the error: File "/home/oladhari/reachat-v4/Reachat-v4/backend/crm/admin.py", line 61, in is_active any(site.current_contract.is_active for site in client.sites.all()) File "/home/oladhari/reachat-v4/Reachat-v4/backend/crm/admin.py", line 61, in <genexpr> any(site.current_contract.is_active for site in client.sites.all()) AttributeError: 'NoneType' object has no attribute 'is_active' to resolve this error I tried to use try: and changed the customized field to this: def is_active(self, client: Client) -> bool: try: any(site.current_contract.is_active for site in client.sites.all()) except ObjectDoesNotExist: return False else: return any(site.current_contract.is_active for site in client.sites.all()) but still having the same error unfortunately please could you help me to avoid this error, thank you -
What is the best way to build Django model?
I want to make a website that gives a visualization of football game statistics. Functionality: The user checks a list of games. Selects game to see details. Can select a particular player. If there is no game he/she is interested in, the user uploads a datafile of the game and adds it to the main list of games. I have a script that cleans data and gives me DataFrame with columns: ['Shots', 'SCA', 'Touches', 'Pass', 'Carries', 'Press', 'Tackled', 'Interceptions', 'Blocks'] if I do the Django model is it ok if I simply do model with these columns, or do I need to do a proper database with separate tables like: Is my UML is ok or do I need to fix something? here is link to my UML https://drawsql.app/xml-team/diagrams/football-game-stats -
Auto token refresh and background web scraping in Django Flask project?
I'm working on a personal project using the Django Flask framework and there are two functionalities I'm trying to implement now. Firstly, I'm using a API service that has 30-minute expiry duration on the authentication token. I'd like to store that token in my database and programatically request a new token once every 25 minutes, most tutorials make mention of a JWT refresh token but that is not offered by the API I am using. What other libraries/functions should I be looking to in order to achieve this? Secondly, Each user has a table of items stored in a sqlite3 database (100+), I would like to programatically perform a google maps search using one column and return the category of the first location returned. Currently I am following a selenium tutorial for web scraping but I am unsure if this is the most appropriate service as I would like this process to happen in the background or a hidden div, I'm also wondering if there are any other better ways to achieve my second goal. Thank you for your time and effort in helping as this is my first time attempting a project using Flask/Django -
how to create a Django project that has a Python environment inside lib and what's the difference to have it inside or in another directory?
I'm deepening my Django knowledge and in the process, I discover that when I do some errors (in this case it doesn't matter what the errors are), Django's engine looks for files outside the project folder. Example of error: Template-loader postmortem Django tried loading these templates, in this order: Using engine django: django.template.loaders.filesystem.Loader: C:\Users\b2b\Desktop\Python moje projekty\Dev\Apiarena_django\src\templates\product\product_detail.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\b2b\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\admin\templates\product\product_detail.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\b2b\AppData\Local\Programs\Python\Python39\lib\site-packages\django\contrib\auth\templates\product\product_detail.html (Source does not exist) django.template.loaders.app_directories.Loader: C:\Users\b2b\Desktop\Python moje projekty\Dev\Apiarena_django\src\products\templates\product\product_detail.html (Source does not exist) I have two questions: how to create a Django project that has python inside lib folder? What's the difference to have it inside or in another directory as I have now? Does it a bad idea and if so, why? -
Django-crontab is not working on in ec2 ubuntu virtual environment
i use django-crontab library in mac m1 bigsur # settings.py INSTALLED_APPS = [ 'django_crontab' ] CRONJOBS = [ ('*/5 * * * *', 'diagnoses.croncode.ChangeRegisterView') ] # croncode.py def ChangeRegisterView(): and i used python manage.py crontab add It was installed in a virtual environment. and It works well in a local environment. however it's not working at ec2!! The virtual environment anaconda python=3.8.11 version is installed and used by aws ec2. like this Traceback (most recent call last): File "manage.py", line 10, in <module> execute_from_command_line(sys.argv) File "/usr/local/lib/python3.2/dist-packages/django/core/management/__init__.py", line 338, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.2/dist-packages/django/core/management/__init__.py", line 312, in execute django.setup() File "/usr/local/lib/python3.2/dist-packages/django/__init__.py", line 18, in setup apps.populate(settings.INSTALLED_APPS) File "/usr/local/lib/python3.2/dist-packages/django/apps/registry.py", line 85, in populate app_config = AppConfig.create(entry) File "/usr/local/lib/python3.2/dist-packages/django/apps/config.py", line 86, in create module = import_module(entry) File "/usr/lib/python3.2/importlib/__init__.py", line 124, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "/usr/lib/python3.2/importlib/_bootstrap.py", line 824, in _gcd_import raise ImportError(_ERR_MSG.format(name)) ImportError: No module named django_crontab i want to two things. I want to do a cronlog path in ec2 Ubuntu environment. I want to turn django-crontab in ec2. help bros!! -
Edit Django Filter Style
I am struggling to edit the following filter to do a few things: Remove the field name from outside of the TextInput and use that as the Hint Text Keep all filters on a single line within a flex container (currently, the week filter is the entire page-wide and the submit button is on a third line) Make WEEK_CHOICES based on unique values within the field Week, rather than hardcoded to weeks 1-3 (e.g. once an entry with Week 4 is submitted, auto-include this in the filter) Any help is appreciated. filters.py class PickFilter(django_filters.FilterSet): WEEK_CHOICES = ( ('Week 1', 'Week 1'), ('Week 2', 'Week 2'), ('Week 3', 'Week 3'), ) name = forms.CharField(widget=forms.TextInput(attrs={'class':'form-control text-white text-center'})) week = django_filters.ChoiceFilter(choices=WEEK_CHOICES, widget=forms.Select(attrs={'class': 'form-control form-control-sm'})) class Meta: model = Pick fields = ['name','week',] pick_list.html {% extends 'base.html' %} {% load cms_tags %} {% block title %} {{ title }} · {{ block.super }} {% endblock title %} {% block content %} <div style="font-size:24px"> {{ title }} </div> <div style="font-size:14px; margin-bottom:15px"> Click on the arrows on the right of each contestant and drag them up or down to reorder them based on how far you think they are going to go. </div> <form method="get"> {{ … -
Question regarding taking input from a form in Django and transferring that data to a SQL database
I have 2 html/CSS forms set up and I also have a SQL database set up with values for everything on the forms. What steps would I need to do to ensure that the form and the database are linked? P.S I already created a model and migrated stuff to the SQL database. -
Validate Specific Google ReCaptcha on the backend with multiple ReCaptchas on the Same Page
I have a form page with Google ReCaptcha validation on my Django backend. I also have a small email form on the footer where I would like to add a separate ReCaptcha. They both seem to be rendering fine. Although I don't know exactly how to tell if the invisible ReCapatcha has actually been rendered correctly. On my backend I have attempted to get the Captcha response with request.POST.get('g-recaptcha-response') Do I need to somehow specify which recaptcha element it should check or will it automatically submit the correct one since it is in the form that is being submitted? I'll include my pertaining code below in case the error is in my implementation. <script src="https://www.google.com/recaptcha/api.js?onload=CaptchaCallback&render=explicit" async defer></script> <script type="text/javascript"> const RenderCaptchas = function() { const siteKey = "{{ GOOGLE_RECAPTCHA_SITE_KEY }}"; const hiddenSiteKey = "{{ GOOGLE_HIDDEN_RECAPTCHA_SITE_KEY }}" const captcha_elements = document.getElementsByClassName('captcha'); const hidden_captcha_elements = document.getElementsByClassName('hidden-captcha'); for (let i = 0; i < captcha_elements.length; i++) { grecaptcha.render(captcha_elements[i].id, {'sitekey': siteKey}) } for (let i = 0; i < hidden_captcha_elements.length; i++) { grecaptcha.render(hidden_captcha_elements[i].id, {'sitekey': hiddenSiteKey}) } } window.CaptchaCallback = RenderCaptchas; </script> <form id="email_subscription_form" class="form-inline float-right" method="post" action="/ajax/email-subscription/"> <div class="form-group"> <label for="id_email_address" class="d-none">Email Address</label> <input type="email" id="id_email_address" class="g-recaptcha hidden-captcha form-control border-0 rounded-0" name="email_address" value="" placeholder="Email … -
Head object forbidden
Whenever I try to submit my form with files it does not work. It worked at first but now it shows me this error. I have no idea what I changed to make it give me this error. I did accidentally put the Access key of my user on GitHub and got a bunch of emails from AWS. but I removed that access keys and even added a new user. So I made a new IAM user and also s3 bucket but it still shows me this. I do have a Risk IAM quarantine alert but the effected key does not exist anymore ClientError at / An error occurred (403) when calling the HeadObject operation: Forbidden Request Method: POST Request URL: http://127.0.0.1:8000/ Django Version: 4.0.1 Exception Type: ClientError Exception Value: An error occurred (403) when calling the HeadObject operation: Forbidden Exception Location: C:\Users\Athenix\.virtualenvs\ComsForm-rXtbVY0K\lib\site-packages\botocore\client.py, line 719, in _make_api_call Python Executable: C:\Users\Athenix\.virtualenvs\ComsForm-rXtbVY0K\Scripts\python.exe Python Version: 3.10.0 Python Path: ['C:\\Users\\Athenix\\Desktop\\ComsForm\\home', 'C:\\Users\\Athenix\\AppData\\Local\\Programs\\Python\\Python310\\python310.zip', 'C:\\Users\\Athenix\\AppData\\Local\\Programs\\Python\\Python310\\DLLs', 'C:\\Users\\Athenix\\AppData\\Local\\Programs\\Python\\Python310\\lib', 'C:\\Users\\Athenix\\AppData\\Local\\Programs\\Python\\Python310', 'C:\\Users\\Athenix\\.virtualenvs\\ComsForm-rXtbVY0K', 'C:\\Users\\Athenix\\.virtualenvs\\ComsForm-rXtbVY0K\\lib\\site-packages'] Server time: Tue, 18 Jan 2022 02:17:26 +0000 Internal Server Error: / Traceback (most recent call last): File "C:\Users\Athenix\.virtualenvs\ComsForm-rXtbVY0K\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\Athenix\.virtualenvs\ComsForm-rXtbVY0K\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File … -
When ever I log in and I am redirect to the 'next' parameter, a trailing slash is automatically added to the url, making it double slashes
I have created views in Django that use LoginRequiredMixin. However, whenever I log in and am to be redirected to another url, the url I am redirected to ends with multiple slashes instead of the usual 1 slash at the end of a django url. One of my views: class BookListView(LoginRequiredMixin, ListView): model = Book # paginate enables the list view to fetch a certain number of records per page. This is # useful when the records are plenty and it is not possible to display all in one page. paginate_by = 3 My login.html template: {%extends 'catalog/base_generic.html'%} {%block content%} {%if form.errors %} <p>Your username and password didn't match. Please try again.</p> {% endif %} {%if next %} {% if user.is_authenticated %} <p>Your account doesn't have access to this page. To proceed, please login with an account that has access. </p> {% else %} <p>Please login to view this page.</p> {% endif %} {% endif %} <form method="POST", action="{% url 'login' %}"> {% csrf_token %} <table> <tr> <td>{{form.username.label_tag}}</td> <td>{{form.username}}</td> </tr> <tr> <td>{{form.password.label_tag}}</td> <td>{{form.password}}</td> </tr> </table> <input type="submit" value="Login"/> <input type="hidden" name="next" value={{next}}/> </form> <P> <a href="{% url 'password_reset' %}">Forgot Password?</a> </P> {% endblock %} When I am just logging in, … -
Docker compose. Make DRF container visible only for frontend container
I'm creating a project using docker compose with 3 containers: db, django and frontend. I would like to have django endpoints usable only for frontend container, and frontend container accessible from everywhere. How can I do this? -
Django FOREIGN KEY constraint failed after submitting form
Good day, just learning Django since 3 day now. After typing something in the form, clicking the submit button, I want the title to be assigned to a user. But I'm getting this error: IntegrityError at /todo/ FOREIGN KEY constraint failed Request Method: POST Request URL: http://localhost:8000/todo/ Django Version: 4.0.1 Exception Type: IntegrityError Exception Value: FOREIGN KEY constraint failed In the Admin Dashboard, the form is also saved and "Author" dropdown is displayed, but no user is assigned to the author. // models.py from django.db import models from django.contrib.auth.models import User from django.conf import settings class User(models.Model): username = models.CharField(max_length=255) email = models.CharField(max_length=255, unique=True) password = models.CharField(max_length=255) def __str__(self): return self.username class Todos(models.Model): title = models.CharField(max_length=255) author = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.CASCADE, blank=True, null=True) def __str__(self): return self.title \forms.py from django import forms from django.contrib.auth import get_user_model # check for unique email & username from .models import Todos User = get_user_model() class RegisterForm(forms.Form): username = forms.CharField() email = forms.EmailField() password1 = forms.CharField( label='Password', widget=forms.PasswordInput( attrs={ "class": "form-control", "id": "user-password" } ) ) password2 = forms.CharField( label='Confirm Password', widget=forms.PasswordInput( attrs={ "class": "form-control", "id": "user-confirm-password" } ) ) class LoginForm(forms.Form): username = forms.CharField(widget=forms.TextInput( attrs={ "class": "form-control" })) password = forms.CharField( widget=forms.PasswordInput( attrs={ "class": … -
How to hide column in model django?
My models: title = models.CharField(max_length = 100) text = models.TextField() text2 = models.TextField() Is it possible to hide columns (text2) in the admin dashboard, e.g. with a checkbox (column no active( so that they are not used in the forms? I'd like to configure the visibility of the columns in forms by admin interface. -
Allow users to fill out a Django form on their own personal website?
I am wondering if anyone has dealt with allowing Users to fill out a form on their own personal website, which is connected to the Django applications database? The general idea behind this, is allowing say a User (Party Planner in the Django app) to not have to come to the "Django Application" to input an event, rather they go to their own personal website, and input form information there which is POSTed to the Django applications database? It's an idea I have been throwing around, and just looking for some guidance in the right direction. Thank you in advance! -
authorization in requests.Session() not work with Django. I get AnonymousUser
I'm trying to create an authorized session using requests.Session() and work with files from the django model. import request session = request.Session() session.auth = ('username', 'password') auth = session.get('http://127.0.0.1:8000/login/') file = session.get('http://127.0.0.1:8000/file/123') #here response is (403 forbidden) In views.py i have check: user.is_authenticated; I always get false (get AnonymousUsers). How can I log in via requests with session retention to access files? Can anyone help? -
Django display content of Google Storage PDF within Heroku Site
I have an issue where the service account used to allow the Django application has the permissions to edit and delete the Google storage bucket. However, I use an iframe to load a preview for a PDF, this preview indicates the following: '''AccessDeniedAccess denied.Anonymous caller does not have storage.objects.get access to the Google Cloud Storage object.''' If I use an tag and load the same file from the Google bucket it works completely fine. However, using the messes it up due to insufficient permissions. Keep in mind that the files can not be publicly available due to privacy. Moreover, I would like to use the tag due to the variety of content being displayed. As it sometimes might be a PDF or Video. ScreenshotThe preview of the file unavailable -
How to get a reference to the already loaded leaflet map in Djano's admin page using Django-leaflet
I'm trying to add markers to the leaflet map loaded in Django's admin pages with data retrieved from an ajax call. However I cannot get a reference to the map that I can use in my template used to override the Django admin template. If I load the page, open the console, and run the code below it works. The marker is added to the map. Console: var map = window['leafletmapid_location-map']; L.marker([40.3830621, -111.773658]).addTo(map); However if I include the exact same code in my template it doesn't work because it is not getting the reference to the map, and I can't figure out why. Template: {% extends "admin/change_form.html" %} {% load i18n admin_urls %} {% block content %}{{ block.super }} <script> var map = window['leafletmapid_location-map']; L.marker([40.3830621, -111.773658]).addTo(map); </script> {% endblock %} If I replace the entire script tag with the following I get undefined which I believe is the cause of the problem. Template: <script> console.log(window['leafletmapid_location-map']) </script> However if in change the template to the following I get the window object, and it shows it has the leafletmapid_location-map object available. Template: <script> console.log(window) </script> -
How can I deploy a django to app to heroku?
I am trying to deploy my django app to heroku. I have followed this tutorial word for word. After I have successfully deployed the application and open the app on the browser it says to me that there is an application error. It tells me to look at my logs. Here is my logs: 2022-01-17T21:45:19.636590+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=testshamir.herokuapp.com request_id=c045b7f7-0364-41c7-be06-b644b3131dff fwd="130.70.15.5" dyno= connect= service= status=503 bytes= protocol=https 2022-01-17T21:45:20.139456+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=testshamir.herokuapp.com request_id=504625b3-1fb2-4016-96b2-32d3952cce93 fwd="130.70.15.5" dyno= connect= service= status=503 bytes= protocol=https 2022-01-17T21:45:24.591640+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/polld" host=testshamir.herokuapp.com request_id=46c3e46b-2abc-406d-a420-fcd67d112493 fwd="130.70.15.5" dyno= connect= service= status=503 bytes= protocol=https 2022-01-17T21:45:24.887285+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=testshamir.herokuapp.com request_id=95afd40f-1d54-4638-90c6-2cfa935d3fd7 fwd="130.70.15.5" dyno= connect= service= status=503 bytes= protocol=https 2022-01-17T21:45:28.377476+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/polls" host=testshamir.herokuapp.com request_id=880e0585-b93a-4b09-a878-80995cf007df fwd="130.70.15.5" dyno= connect= service= status=503 bytes= protocol=https 2022-01-17T21:45:28.658839+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=testshamir.herokuapp.com request_id=35edc875-62ee-4b79-840c-98fba1aedd60 fwd="130.70.15.5" dyno= connect= service= status=503 bytes= protocol=https 2022-01-17T21:48:05.411725+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/" host=testshamir.herokuapp.com request_id=5bb89c4b-0aae-4f28-9cf9-a14e3e7ff9ec fwd="130.70.15.5" dyno= connect= service= status=503 bytes= protocol=https 2022-01-17T21:48:05.775751+00:00 heroku[router]: at=error code=H14 desc="No web processes running" method=GET path="/favicon.ico" host=testshamir.herokuapp.com request_id=333334a5-0824-4aff-b42b-1ae61403390a fwd="130.70.15.5" … -
Python/Django routing messed up when clicking a button
I am working through a basic django tutorial and I have become stuck. When the favorites button is clicked I am trying to redirect the user to reviews/favorite, which will then redirect to reviews/review_id, which is where they started. Instead, whenever I click the favorite button on the page it redirects me to reviews/reviews/review_id which fails. Interestingly enough if I remove the /reviews/ part from the form action in single-review.html then it routes me to /favorite, which fails because it doesnt exist, but when I put it back to reviews/favorite I go back to reviews/reviews/favorite as the routing. Anyone know what I am doing wrong? Views.py from django.http.response import HttpResponse from django.shortcuts import render from django.http import HttpResponseRedirect from django import forms from django.views import View from django.views.generic.base import TemplateView from django.views.generic import ListView from django.views.generic.detail import DetailView from django.views.generic.edit import FormView, CreateView from .forms import ReviewForm from .models import Review # Create your views here. # uses createview to handle all the data processing and then save data to database. Removes need for class ReviewForm in forms.py unless you want to customize class ReviewView(CreateView): model = Review form_class = ReviewForm template_name = "reviews/review.html" success_url = "/thank-you" class ThankYouView(TemplateView): template_name …