Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Calling class view inside of another class view in Django
I have JobCreateViewV1 (old one) view class which works with model in one way, and after upgrade, i created JobCreateViewV2 (new one) class that adds another entry to another model entry of first call. What is the best way to get response form first class and pass it to the second one? Here are my classes: JobCreateView class JobCreateView(AuthenticatedView, generics.GenericAPIView): #some seralizer serializer_class = JobSerializerForUser def post(self, request): #....yada yada yada... job='model is here' return Response(status=status.HTTP_201_CREATED, data=self.serializer_class(job, many=False).data) and JobCreateViewV2 class JobCreateViewV2(AuthenticatedView, generics.ListAPIView): serializer_class = ResponsibleTechnicianSerializer def post(self, request): JobCreateViewV1Response = JobCreateViewV1.post(self, request) # ...yada yadayada... #and here JobCreateViewV1Response equals to {} Old url works perfect, but when i call V2 one, data portion of response from V1 calls equals to {}. Might this problem occur because i call JobCreateView in improper way and serializer is not working the way it should? I've tried to use ShowAppsView.as_view()(self.request) approach, but it seems is not what i need. -
Django: ImageField sets wrong url
I am new to django and set up my first project with one app in the beginning. Some time later I figured out that I need a custom user model so I've created a second app with the custom user model as I've read somewhere that you need the user model as first migration (I'm telling this, because I believe my project structure is causing my problem). Right now I am working on an avatar upload for the user model. I am able to upload an image via DRF and then open the image in my browser, but not with the saved url in my database. Django saves the image like this in the database: http://localhost:8000/api/users/<user_id>/media/avatars/image.jpg. But the correct url would be: http://localhost:8000/media/avatars/image.jpg How do I make django save the correct url? I've set MEDIA_ROOT and MEDIA_URL like this: MEDIA_ROOT = BASE_DIR + 'media' MEDIA_URL = 'media/' My project structure: my project - backend (first app) - - manage.py - - settings.py - users (second app) - - models.py # here is my custom user model Any help is appreciated -
Trying to Package a DRF project with PyInstaller but getting TemplateDoesNotExist at /
I'm trying to package a DRF app as an executable with the PyInstaller library. I haven't coded much other than some basic API before testing out PyInstaller (first time working with it). What I Have Done So Far: I created hook-rest_framework.py with the following code: from PyInstaller.utils.hooks import collect_submodules hiddenimports = collect_submodules('rest_framework') I specified hiddenimports in the .spec file hiddenimports=['rest_framework.urls', 'rest_framework.apps', 'rest_framework', 'app.urls'] However, I get the following error when I initialise the executable TemplateDoesNotExist at / rest_framework/api.html I added "rest_framework" under INSTALLED_APPS in settings.py (please find it below). Could there be additional hooks and/or hiddenimports that I forgot to add? Any help and guidance will be most welcome! """ Django settings for backend project. Generated by 'django-admin startproject' using Django 2.2.12. For more information on this file, see https://docs.djangoproject.com/en/2.2/topics/settings/ For the full list of settings and their values, see https://docs.djangoproject.com/en/2.2/ref/settings/ """ import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = '#k^f##6n@g6--g1s)$&i5_6c(wi2$bvm$gjhsl2jx*c!!d%1%2' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = [] # … -
From file import function (django)
I'm learning django and following a tutorial, the thing is that when I try to import a function in the file urls.py from views.py and when I run the server the cmd throws the error no module named "views", and the guy in the tutorial doesn´t get that error and doesn´t talk anything about it. (They´re in the same directory, I tried importing the function to the module __init__, but throws the exact same error -
my login form is not validating in django
i have made a custom user model. using that model i have made a login form, signup form. but sign up form and logout works fine. but whenever i try to submit login form it does not authenticate. where is the problem? there is two authentication one is in for login in forms.py other is in views.py for login forms.py from django import forms from django.contrib.auth.forms import UserCreationForm from diabetes.models import UserSignupModel from django.contrib.auth import login,authenticate,logout class UserSignupForm(UserCreationForm): email=forms.EmailField(max_length=60,help_text="add a valid email address",required=True) name=forms.CharField(max_length=15,help_text="add a valid name") age=forms.CharField(max_length=15) class Meta: model=UserSignupModel fields=('email','name',"username",'age',"password1","password2") class UserLoginForm(forms.ModelForm): password=forms.CharField(label="password",widget=forms.PasswordInput) class Meta: model=UserSignupModel fields=("email","password") def clean(self): if self.is_valid(): email=self.cleaned_data['email'] password=self.cleaned_data['password'] if not authenticate(email=email,password=password,backend='django.contrib.auth.backends.ModelBackend'): raise forms.ValidationError("Invalid LOGIN") models.py from django.db import models from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class SignUpManager(BaseUserManager): def create_user(self, email,age,name, username, password=None): #if not email: #raise ValueError("insert user") if not username: raise ValueError("insert username") if not name: raise ValueError("insert name") if not age: raise ValueError("insert age") user = self.model( email=self.normalize_email(email), username=username, age=age, name=name, ) user.set_password(password) user.save(using=self._db) return user def create_superuser(self,email,name,age,username, password): user = self.create_user( email=self.normalize_email(email), username=username, password=password, age=age, name=name, ) user.is_admin = True user.is_staff = True user.is_superuser = True user.save(using=self._db) return user class UserSignupModel(AbstractBaseUser): email = models.EmailField(verbose_name="email", max_length=60,unique=True) age = … -
Post comments in Django Homepage
i have this code with me as part of a tutorial i was following for blog post. I have a comment section on my detailview, I want it to be shown in the homepage as well. I tried with some codes, but the problem is same comments are showing in all posts (only) in homepage. please take a look at the code. home view. def myhome(request, tag_slug=None): current_user = request.user following_ids = request.user.following.values_list('id',flat=True) actions = Action.objects.filter(user_id__in=following_ids) #Action notification posts_list = Post.objects.filter(Q(user_id__in=following_ids) | Q(user=current_user)).\ order_by('-post_date') tag = None if tag_slug: tag = get_object_or_404(Tag, slug=tag_slug) posts_list = posts_list.filter(tags__in=[tag]) paginator = Paginator(posts_list, 5) page = request.GET.get('page') try: posts = paginator.page(page) except PageNotAnInteger: posts = paginator.page(1) except EmptyPage: posts = paginator.page(paginator.num_pages) if following_ids: # If user is following others, retrieve only their actions actions = actions.filter(user_id__in=following_ids) actions = actions.select_related('user', 'user__profile').prefetch_related('target')[:10] comments = Comment.objects.filter(post=posts_list.first()) # Correct it later context = { 'page':page, 'posts':posts, 'tag':tag, 'actions':actions, 'comments': comments, } return render(request, 'posts/users/myhome.html', context) I have a comment snippet which I use it in my homepage. <!-- Comment showing section --> <div class="main-comment-section"> <div class="container-fluid mt-2"> <div class="form-group row"> <!-- Comment Form --> <form class="comment-form" method="post" action=".">{% csrf_token %} <div class="form-group"> <textarea name="content" cols="60" rows="2" maxlength="1000" required="" … -
How to upload multiple images in ModelAdmin from single filefields to dynamic location?
I have a model for Gltf files which is like this: def gltf_model_path(instance, filename): customs_name = instance.module.module_name return os.path.join( "uploads", "%s" % instance.module.module_name, filename) def gltf_texture_path(instance, filename): custom_name = instance.module.module_name return os.path.join( "uploads", "%s" % instance.module.module_name,"textures", filename) class GLTFFile(models.Model): module = models.OneToOneField(Module, on_delete=models.CASCADE) gltf = models.FileField(upload_to=gltf_model_path) bin_file = models.FileField(upload_to=gltf_model_path) textures = models.FileField(upload_to=gltf_texture_path) And the ModelAdmin for this model which is like this : @admin.register(GLTFFile) class GLTFFileAdmin(admin.ModelAdmin): form = GLTFAdminForm def save_model(self, request, obj, form, change): files = request.FILES.getlist('textures') for f in files: instance = GLTFFile(textures=f) instance.save() The form is like this: class GLTFAdminForm(forms.ModelForm): class Meta: model = GLTFFile fields = ( 'module', 'gltf', 'bin_file', 'textures', ) labels = { 'gltf' : 'upload GLTF file', 'bin_file' : 'upload bin file', 'textures' : 'upload all files in textures folder', } widgets = { 'textures': forms.ClearableFileInput(attrs={'multiple': True}), } But this setups seems to give error : 'NoneType' object has no attribute 'module_name' at line - custom_name = instance.module.module_name Can somebody tell, what is wrong here, or suggest a better way to do this? -
Create table via django-rest-framework api
1- The problem is that when users will register by the django-rest-api, I want a table to be created for the user. 2- Is it possible that users request to create a table (table with predefined specifications or a custom one)? -
Debug Django signal handlers
I am trying to use signals for the first time. I have a model, UserAlias, and I want to execute some code after a UserAlias record is created. UserAlias is defined in aliases/models.py I created a aliases/signals/handlers.py. Here is that file's contents: from django.db.models.signals import post_save, post_init, post_delete from django.dispatch import receiver from aliases.models import UserAlias @receiver(post_init, sender=UserAlias) def post_init_handler(sender, **kwargs): print('hello there from a signal') @receiver(post_save, sender=UserAlias) def post_save_handler(sender, **kwargs): print('hello there from a signal') @receiver(post_delete, sender=UserAlias) def post_delete_handler(sender, **kwargs): print('hello there from a signal') But when I execute: from aliases.models import * newalias = UserAlias.objects.create(...omitted...) I do not see any of my debug print statements execute. What am I missing here? -
I'm trying to figure out how Django function and encountered this recursion error
i came across this error while separating the contents of the index.html file into base.html and head.html . i tried removing the head tags from this file and putting it in head.html but it didn't work. <!DOCTYPE html> <html > <head> #error in this line {% include 'head.html' %} </head> <body> {% include 'navbar.html' %} {% block content %} {% endblock content %} {% include 'footer.html' %} {% include 'scripts.html' %} </body> </html>` the contents of head.html are:`{% extends 'base.html' %} Readit - Free Bootstrap 4 Template by Colorlib <link href="https://fonts.googleapis.com/css?family=Poppins:300,400,500,600,700,800,900" rel="stylesheet"> <link rel="stylesheet" href="css/open-iconic-bootstrap.min.css"> <link rel="stylesheet" href="css/animate.css"> <link rel="stylesheet" href="css/owl.carousel.min.css"> <link rel="stylesheet" href="css/owl.theme.default.min.css"> <link rel="stylesheet" href="css/magnific-popup.css"> <link rel="stylesheet" href="css/aos.css"> <link rel="stylesheet" href="css/ionicons.min.css"> <link rel="stylesheet" href="css/flaticon.css"> <link rel="stylesheet" href="css/icomoon.css"> <link rel="stylesheet" href="css/style.css">` -
GET and POST requests in testing/ Django
Guy, I need your help. Since I'm newbie and I'm making my first app in Django I came to an issue while testing my app. There is problem with testing views, and since tested manually everything works fine problem occurs while testing automatition. I think the issue may be related to POST / GET requests because I made things in way that, most things are based on GET, even those which change things in DB. POST request is reserved only to forms. When I start tests, every action that is made seems lacking-effect like those GET requests don't work. Ok here comes the code: Views: @login_required def new(request): if request.method == "POST": player = Player.objects.get(name=request.user) hosted = Game(host=player.nick) form = CreateGame(instance=hosted, data=request.POST) if form.is_valid(): form.save() return redirect("home", name="new_room") @login_required def delete_room(request, id): game = Game.objects.get(id=id) player = Player.objects.get(name=request.user) if player.nick == game.host and game.how_many_players_ready == 0: if not game.is_played: game.delete() return redirect("home", name="game_deleted") else: return redirect('detail', id=game.id) else: return redirect('detail', id=game.id) Tests: class TestViews(TestCase): def setUp(self): self.client = Client() self.user = User.objects.create_user(username='testuser', password='12345') self.user2 = User.objects.create_user(username='testuser2', password='12345') usr = self.user self.client.login(username='testuser', password='12345') self.player = Player.objects.create(name=usr, parent = usr.username, nick = 'nie') def test_create_many_rooms(self): #this one works -> POST self.new_room=reverse('new_room') self.client.post(self.new_room, … -
Reactjs nested router does not work on refresh
Hello i am using ReactJs as my frontend for my django project. Im encountering this issue because i wish to separate my login page from my main layout. As such i adopted such a hierarchy of components: App.js -> [Main.js -> (Layout.js, etc..) , Login.js] Apologies for my bad illustration above , here is my code: App.js class App extends Component { ###some code#### render() { if (this.state.checking === true ) { return <Spin size="large" /> } else { console.log('state = complete load') return ( <AlertProvider template={AlertTemplate}{...alertOptions}> <Router> <Alerts/> <Switch> <PrivateRoute exact path="/" component={Main}/> <Route exact path="/login" component={Login}/> </Switch> </Router> </AlertProvider> ) } } } Main.js export class Main extends Component { render() { return ( <Router> <LayoutHeader> <BaseRouter/> </LayoutHeader> </Router> ) } } export default Main; Router.js const BaseRouter = () => ( <div> <Switch> <PrivateRoute path="/" exact component={Home} /> <PrivateRoute path="/hello" exact component={hello} /> <Route exact path="*" component={() => '404 NOT FOUND'} /> </Switch> </div> ); export default BaseRouter; Upon refreshing the page in /hello im greeted with a blank page. I don't understand whats going on here , would someone explain to me? Thank you! -
Problem with MULTPLE SETTINGS File. Django/Python
I am trying to run a Django project on my windows machine. I am getting nomodulefounderror. The project consists of multiple settings files for prod, Development, and Test. I am using a virtual environment, Python 2.7 and Django 1.10 versions I need help to run this project on my local machine. Python manage.py runserver --settings=settings_dev_sai It throws me an error. Here is my error log python manage.py runserver --settings=bridge.settings.settings_dev_sai Traceback (most recent call last): File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 60, in execute super().execute(*args, **options) File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\base.py", line 369, in execute output = self.handle(*args, **options) File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\core\management\commands\runserver.py", line 67, in handle if not settings.DEBUG and not settings.ALLOWED_HOSTS: File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 76, in __getattr__ self._setup(name) File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 63, in _setup self._wrapped = Settings(settings_module) File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\site-packages\django\conf\__init__.py", line 142, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\1\AppData\Local\Programs\Python\Python38-32\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 961, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1014, in _gcd_import File "<frozen importlib._bootstrap>", line 991, in _find_and_load File "<frozen importlib._bootstrap>", line 975, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line … -
CRSF Token failed when using JWT
I'm trying to use JWT authentication (via Simple JWT). But am getting a CRSF verification failed error. The solutions to this problem online state that is because 'DEFAULT_AUTHENTICATION_CLASSES' and DEFAULT_PERMISSION_CLASSES' are both missing. But these have both been set and i'm still getting the error when trying to use Postman. Settings.py: ... REST_FRAMEWORK = { 'DEFAULT_AUTHENTICATION_CLASSES': ( 'rest_framework_simplejwt.authentication.JWTAuthentication', ), 'DEFAULT_PERMISSION_CLASSES': ( 'rest_framework.permissions.IsAuthenticated', ), 'DEFAULT_PAGINATION_CLASS': 'rest_framework.pagination.PageNumberPagination', 'PAGE_SIZE': 3 } ... Views.py: from django.contrib.auth import get_user_model from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import permissions User = get_user_model() class SignupView(APIView): permission_classes = (permissions.AllowAny, ) def post(self, request, format=None): data = self.request.data ... -
Django Media images not loading when debug=False [duplicate]
I can't figure out what went wrong, The project was working fine so I tried to host it on heroku but found some issues with static file, I changed the STATIC_URL in settings.py and then the static files were loading just fine, but the images stored in the database are not visible on the website My file tree C:. ├───accounts │ ├───migrations │ │ └───__pycache__ │ ├───templates │ └───__pycache__ ├───blog │ ├───archives │ │ └───templates │ ├───migrations │ │ └───__pycache__ │ ├───templates │ └───__pycache__ ├───djago_project │ └───__pycache__ ├───media │ ├───blog_covers │ │ └───20 │ │ └───05 │ │ ├───18 │ │ └───19 │ └───images │ └───blocks │ └───20 │ └───05 │ └───18 └───static ├───admin │ ├───css │ │ └───vendor │ │ └───select2 │ ├───fonts │ ├───img │ │ └───gis │ └───js │ ├───admin │ └───vendor │ ├───jquery │ ├───select2 │ │ └───i18n │ └───xregexp ├───images ├───scripts └───styles My settings.py file import os # Build paths inside the project like this: os.path.join(BASE_DIR, ...) BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_ROOT = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') MEDIA_URL = '/media/' My urls.py file from django.contrib import admin from django.urls import path, include from django.conf import settings from django.conf.urls.static import static urlpatterns … -
i am getting error improper configuration or mysqlclient not install ,but i have mysqlclient version site-packages (1.4.6)
i am using ubuntu 20.04 LTS yet ,all was working properly but when i update my os from 18.04 to 20.04 it now showing error in djnago which is django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? after that i try that pip install mysqlclient it give me that Defaulting to user installation because normal site-packages is not writeable Requirement already satisfied: mysqlclient in ./.local/lib/python3.7/site-packages (1.4.6) and i also tried that import pymysql pymysql.install_as_MySQLdb() is given version error please help -
Inlineformset with multiple children
I have a use case in which I put challenges in a model. Each challenge has 1-* vars and 1-* rounds. I want to have CRUD forms for inserting new challenges with their vars and rounds in my db. The model looks the following: class Challenge(models.Model): pass class Var(models.Model): challenge = models.ForeignKey(Challenge, on_delete=models.CASCADE) name = models.CharField(max_length=30) def __str__(self): return self.name class Round(models.Model): challenge = models.ForeignKey(Challenge, on_delete=models.CASCADE) index = models.IntegerField() description = models.CharField(max_length=100) def __str__(self): return f"[{self.index},{self.description}]" I currently use the following inlineformset to update a challenge through its pk: def updates_challenge(request,challenge_id): challenge = Challenge.objects.get(pk=challenge_id) RoundFormset = inlineformset_factory(Challenge, Round, fields=('index','description')) if request.method == 'POST': formset = RoundFormset(request.POST, instance=challenge) if formset.is_valid(): formset.save() return redirect('update_challenges', challenge_id=challenge.id) formset = RoundFormset(instance=challenge) return render(request, 'drinking_game/update_challenge', {'formset': formset}) However, this does not allow me to change the vars at the same time. I could just make a new form for the vars but that means that I have to create a seperate form for the vars and I can not save both rounds and vars at the same time. On saving I first want to apply some logic to check if the amount of vars is equal to the amount of rounds. I hope that anyone can … -
Como puedo reducir el slug size de un modelo en keras?
Estoy intentando desplegar un modelo de machine learning hecho en keras, mediante heroku, y obtengo que 'Compiled Slug Size:533M is too large(max is 500M)', push rejected. Intente usar 'heroku repo:gc --app' para poder arreglarlo, pero obtenia 'curl: (22) The request URL returned error: 404 not found'. Hay alguna manera en que pueda reducir el slug size sin afectar el funcionamiento de mi modelo?. Existe alguna herramienta que me permita hacer el desplegue sin reducir el slug size?. Muchas gracias -
Why isn't django serving my SPA static files correctly?
I'm building a website using a Django backend and Vuejs frontend. In development I started the backend and the frontend separately with python manage.py runserver and yarn serve respectively. This worked great and I now want to deploy the website. To do this I ran yarn build, which created a dist/ folder in my frontend folder. So my structure was like this: cockpit ├── backend/ │ ├── cockpit/ │ │ ├── views.py │ │ ├── css/ │ │ └── etc.. │ ├── settings/ │ │ └── settings.py │ └── manage.py └── frontend/ └── dist/ ├── index.html ├── css/ └── js/ I now want to serve the sources in frontend/dist/ from my django project so that I can run everything using uwsgi. To do this I'm trying to follow this description. I have the following settings/urls.py from django.contrib import admin from django.urls import include, path, re_path from django.views.generic import TemplateView urlpatterns = [ path('admin/', admin.site.urls), path('cockpit/', include("cockpit.urls")), re_path('', TemplateView.as_view(template_name='index.html')), ] and set the following settings in my settings.py: TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': ['static'], # <== ADDED THIS 'APP_DIRS': True, 'OPTIONS': { # removed to keep this example small }, }, ] BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) STATIC_URL = '/static/' STATICFILES_DIRS … -
AJAX request to Django view pulls data but list not populating
Trying to populate a side bar with session status from api server. Having trouble following a modified example shown here: How to dynamically generate html list from json array received via ajax call? I'm able to get the console to log the dict values but when I try to populate a list following the example it fails to show anything on the page. I also don't see any dev console errors. HTML: <div id="sessionstatuslist"> </div> Ajax Function: function sessionStatus(){ var _url = "ajax/get_sessionstatus"; var request = $.ajax({ "url": _url, dataType : 'json', type : 'GET', data: {}, success: function (data) { var list_html = "<ol>"; for( var i=0; i <data.length; i++) { list_html += "<li>" + data[i] + "</li>"; } list_html += "</ol>" $("#sessionstatuslist").html(list_html); }, error: function(data) { console.log('there was a problem'); } }); return false; }; View: def Getsessionstatus(request): sessionstatus_list = {'session 1': 'running', 'session 2': 'idle',} data = sessionstatus_list return JsonResponse(data) -
Django import export imports not showing
I applied the code as the documentation suggested. But my csv data is now being shown -
Django app deployment on Heroku error H10 - "app crashed"
While trying to deploy my Django app on Heroku I am faced with the following error log: 2020-05-18T18:06:10.221386+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=wsb-project.herokuapp.com request_id=656b4ad4-eab1-40b7-b83c-b0b4d2e26913 fwd="85.221.138.216" dyno= connect= service= status=503 bytes= protocol=https 2020-05-18T18:06:10.432496+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=wsb-project.herokuapp.com request_id=94daa255-f8e3-460c-bc84-3ebb32c8310e fwd="85.221.138.216" dyno= connect= service= status=503 bytes= protocol=https I ran heroku ps to try to understand and got this: $ heroku ps Free dyno hours quota remaining this month: 550h 0m (100%) Free dyno usage for this app: 0h 0m (0%) For more information on dyno sleeping and how to upgrade, see: https://devcenter.heroku.com/articles/dyno-sleeping === web (Free): gunicorn WSB_Website.wsgi --log-file - (1) web.1: crashed 2020/05/18 20:16:50 +0200 (~ 3m ago) As I can't find any clear solution I am writing here to know if any of you guys and girls have an idea of what could be done to have it work :) -
Django Swagger landing page
I have some API's in my Django project and I have successfully installed Django Swagger for the API documentation but when I hit the swagger url, I am not able to view any kind of existing API's of my project in the swagger UI. Please suggest a workaround to get all the needed apis visible in the swagger UI Note :- http://localhost:8000/api is the URL. -
Docker + django_extensions + jupyter: OSError: [Errno 99] Cannot assign requested address
I am trying to set up jupyter inside a container that contains a Django app. I am using django-extensions in order to take advantage of the shell_plus command. However, when I run it: docker-compose exec app python manage.py shell_plus --notebook I am getting the following error: Traceback (most recent call last): File "manage.py", line 21, in <module> main() File "manage.py", line 17, in main execute_from_command_line(sys.argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 401, in execute_from_command_line utility.execute() File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 395, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/usr/local/lib/python3.8/site-packages/django_extensions/management/commands/shell_plus.py", line 125, in run_from_argv return super(Command, self).run_from_argv(argv) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 328, in run_from_argv self.execute(*args, **cmd_options) File "/usr/local/lib/python3.8/site-packages/django/core/management/base.py", line 369, in execute output = self.handle(*args, **options) File "/usr/local/lib/python3.8/site-packages/django_extensions/management/utils.py", line 62, in inner ret = func(self, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/django_extensions/management/commands/shell_plus.py", line 517, in handle shell() File "/usr/local/lib/python3.8/site-packages/django_extensions/management/commands/shell_plus.py", line 253, in run_notebook app.initialize(notebook_arguments) File "<decorator-gen-117>", line 2, in initialize File "/usr/local/lib/python3.8/site-packages/traitlets/config/application.py", line 87, in catch_config_error return method(app, *args, **kwargs) File "/usr/local/lib/python3.8/site-packages/notebook/notebookapp.py", line 1769, in initialize self.init_webapp() File "/usr/local/lib/python3.8/site-packages/notebook/notebookapp.py", line 1490, in init_webapp self.http_server.listen(port, self.ip) File "/usr/local/lib/python3.8/site-packages/tornado/tcpserver.py", line 151, in listen sockets = bind_sockets(port, address=address) File "/usr/local/lib/python3.8/site-packages/tornado/netutil.py", line 174, in bind_sockets sock.bind(sockaddr) OSError: [Errno 99] Cannot assign requested address -
Django If statement in HTML not responding
I am trying to show in a nav bar an option where if the user is the designer it appears to him to direct him to user-posts. I know that the link is working because in the post list and post detail when I click the user name it directs me to the user-posts, I am trying to do the same in the nav bar Here is is the template <div class="dropdown-menu" aria-labelledby="navbarDropdownMenuLink"> {% if object.designer == user %} <a class="dropdown-item" href=" {% url 'score:user-posts' post.designer.username %} ">Submitted Posts</a> {% endif %} Here is the post-detail link that I am trying to imitate <a class="post_name" href="{% url 'score:user-posts' object.designer.username %}"> {{ object.designer }} </a> Here is the list view as well link to users post: <a href="{% url 'score:user-posts' post.designer.username %}">{{ post.designer }}</a> Here is the User list view class UserPostListView(ListView): model = Post template_name = "user_posts.html" context_object_name = 'posts' paginate_by = 5 def get_queryset(self): user = get_object_or_404(User, username=self.kwargs.get('username')) return Post.objects.filter(designer=user).order_by('-date_posted')