Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Object Not created after form submission
Hi I am using Django and Ajax for users create 'Posts' on their website. However, After the form submission the post is not shown. I do not know what's causing this as I see no errors. My views for the homepage and creating a post is: @login_required def home(request): posts = Post.objects.all() context = {'posts':posts} return render(request, 'home/homepage/home.html', context) @login_required def post_create(request): data = dict() if request.method == 'POST': form = PostForm(request.POST) if form.is_valid(): form.save() data['form_is_valid'] = True posts = Post.objects.all() data['posts'] = render_to_string('home/posts/home_post.html',{'posts':posts}) else: data['form_is_valid'] = False else: form = PostForm context = { 'form':form } data['html_form'] = render_to_string('home/posts/post_create.html',context,request=request) return JsonResponse(data) my post_create.html: {% load crispy_forms_tags %} <form method="POST" data-url="{% url 'home:post-create' %}" class="post-create-form"> {% csrf_token %} <div class="modal-header"> <h5 class="modal-title" >Create a Post</h5> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> {{ form|crispy }} </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-dismiss="modal">Close</button> <button type="submit" class="btn btn-primary">Post</button> </div> </form> My home.html: {% extends "home/homepage/base.html" %} {% load crispy_forms_tags %} {% load static %} {% block javascript %} <script src="{% static 'js/post.js' %}"></script> {% endblock javascript %} {% block content %} <div class="card"> <div class="card-body"> <div class="media mb-0 align-items-center"> <img class="img-create-post rounded-circle my-0 mr-3" style="width: 50px;height: 50px;" … -
Testing Keras Model using Django
I downloaded a Django API which I wanted to test with my Keras model, but whenever I tried to run the server it shows me this error, what's wrong? (base) C:\Users\vipek\PAS>python manage.py runserver Traceback (most recent call last): File "manage.py", line 15, in <module> execute_from_command_line(sys.argv) File "C:\Users\vipek\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 371, in execute_from_command_line utility.execute() File "C:\Users\vipek\Anaconda3\lib\site-packages\django\core\management\__init__.py", line 317, in execute settings.INSTALLED_APPS File "C:\Users\vipek\Anaconda3\lib\site-packages\django\conf\__init__.py", line 56, in __getattr__ self._setup(name) File "C:\Users\vipek\Anaconda3\lib\site-packages\django\conf\__init__.py", line 43, in _setup self._wrapped = Settings(settings_module) File "C:\Users\vipek\Anaconda3\lib\site-packages\django\conf\__init__.py", line 106, in __init__ mod = importlib.import_module(self.SETTINGS_MODULE) File "C:\Users\vipek\Anaconda3\lib\importlib\__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1006, in _gcd_import File "<frozen importlib._bootstrap>", line 983, in _find_and_load File "<frozen importlib._bootstrap>", line 967, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 677, in _load_unlocked File "<frozen importlib._bootstrap_external>", line 728, in exec_module File "<frozen importlib._bootstrap>", line 219, in _call_with_frames_removed File "C:\Users\vipek\PAS\api\settings.py", line 23, in <module> SECRET_KEY = os.environ['SECRET_KEY'] File "C:\Users\vipek\Anaconda3\lib\os.py", line 678, in __getitem__ raise KeyError(key) from None KeyError: 'SECRET_KEY' -
django channel deploy with nginx redis
I try to deploy Django app with a part based on Django channels on locall there is no problem and it works correctly but for deploying it on a server I have a problem ws routs are missing I tried to deploy as this and there are my files: nginx.conf upstream django { server 127.0.0.1:8000;} upstream channels-backend {server 127.0.0.1:8000;} server { listen 192.168.177.128:80; charset utf-8; server_tokens off; access_log /etc/nginx/log/access.log; error_log /etc/nginx/log/error.log; location /static/ {alias /home/reza/Desktop/Project/env/repo/project/mysite/MySiteProject/static/;} location /media/ {alias /home/reza/Desktop/Project/env/repo/project/mysite/MySiteProject/media/;} location / { include uwsgi_params; uwsgi_pass django; try_files $uri @proxy_to_app;} location @proxy_to_app {proxy_pass http://channels-backend; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Host $server_name; } } uwsgi.ini [uwsgi] chdir= /home/reza/Desktop/Project/env/repo/project/mysite/MySiteProject/ processes=10 module=MySiteProject.wsgi:application callable=application daemonize=/home/reza/Desktop/Project/env/repo/networkconfig/log_uwsgi.log socket=127.0.0.1:8037 virtualenv=/home/reza/Desktop/Project/env/ enable-threads=true env=DJANGO_SETTINGS_MODULE=MySiteProject.settings master = true chmod-socket = 660 vacuum = true supervisor.conf [fcgi-program:asgi] socket=tcp://127.0.0.1:8000 directory=/home/reza/Desktop/Project/env/repo/project/mysite/MySiteProject command=daphne -u /run/daphne/daphne%(process_num)d.sock --fd 0 --access-log - --proxy- headers MySiteProject.asgi:application numprocs=1 process_name=asgi%(process_num)d autostart=true autorestart=true stdout_logfile=asgi.log redirect_stderr=true -
Connection with nginx and uwsgi by http
I am struggling with the connection of nginx and django (in the same service docker-swarm) My strategy is like this , run uwsgi http option and 8001 port. (not socket) uwsgi --http :8001 --module myapp.wsgi --py-autoreload 1 --logto /tmp/mylog.log then I confirmed wget http://127.0.0.1:8001 works. but from, nginx, It can't connect somehow. (111: Connection refused) error I googled around and found, this error is related with backend. however I have confirmed. wget http://127.0.0.1:8001 works. Is there any places I need to check??? web_nginx.0.xj2y7mzem9ke@manager | 10.255.0.2 - - [23/Mar/2020:20:40:23 +0000] "GET /favicon.ico HTTP/1.1" 502 568 "http://localhost/" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36" "-" web_nginx.0.xj2y7mzem9ke@manager | 10.255.0.2 - - [23/Mar/2020:20:40:23 +0000] "GET / HTTP/1.1" 502 568 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_5) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/80.0.3987.149 Safari/537.36" "-" web_nginx.0.xj2y7mzem9ke@manager | 2020/03/23 20:40:23 [error] 8#8: *20 connect() failed (111: Connection refused) while connecting to upstream, client: 10.255.0.2, server: 127.0.0.1, request: "GET / HTTP/1.1", upstream: "http://127.0.0.1:8001/", host: "localhost" web_nginx.0.xj2y7mzem9ke@manager | 2020/03/23 20:40:23 [error] 8#8: *20 connect() failed (111: Connection refused) while connecting to upstream, client: 10.255.0.2, server: 127.0.0.1, request: "GET /favicon.ico HTTP/1.1", upstream: "http://127.0.0.1:8001/favicon.ico", host: "localhost", referrer: "http://localhost/" web_nginx.0.xj2y7mzem9ke@manager | 10.255.0.2 - - [23/Mar/2020:20:40:23 … -
Django-taggit tag value retrieval and formatting failing
I am trying to implement a tagging process for profiles so you can add your hobbies for example. I have chosen django-taggit as it seemed quite simple and does what I need it to, plus don't really know how to do it myself from scratch. I have managed to make it work to some extent but I am having issues with 3 things: Not really sure what's the best way to control the form field for these tags as I generate the form automatically with widget adjustments in meta function of the form, but it might work fine after resolving the below two issues. When there is no data for the field hobbies (tags) the field gets populated with a single tag of value "[]" as per below image. When I add a tag of "music" and submit the form after I reload the page I get this "[]" as per image. I assumed this will be dealt with by the library, but I cannot see another similar scenario online. My model is: class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) hobbies = TaggableManager() My form is: class UserProfileForm(forms.ModelForm): class Meta: model = UserProfile fields = ['hobbies',] def __init__(self, *args, **kwargs): super(UserProfileForm, … -
Rendering Crispy Form + no submit button
I trying to use crispy layout for my form. I have followed instruction and tutorial but because I am new to Django and python I got lost and it does not render my form as well as submit button. I have model form defined: class nowyPhForm(forms.ModelForm): class Meta: model = Phandlowy fields = ('imie', 'nazwisko', 'email', 'telefon', 'firma', 'filia') def __init__(self, *args, **kwargs): super(nowyPhform, self).__init__(*args, **kwargs) self.helper = FormHelper() self.helper.form_method = 'post' self.helper.form_action = 'submit_survey' self.helper.add_input(Submit('submit', 'Submit')) self.helper.layout = Layout( Row( Column('imie', css_class='form-group col-md-6 mb-0'), Column('nawisko', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), Row( Column('email', css_class='form-group col-md-6 mb-0'), Column('telefon', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), Row( Column('firma', css_class='form-group col-md-6 mb-0'), Column('filia', css_class='form-group col-md-6 mb-0'), css_class='form-row' ), Submit('submit', 'Sign in') ) and HTML {% load crispy_forms_tags %} {% block content %} <div class="container"> {% crispy form %} </div> {% endblock %} I would appreciate if someone could spot problem. -
Changing the data type of values in the Django model
I have data which is loaded into a dataframe. This dataframe then needs to be saved to a django model. The major problem is that some data which should go into IntegerField or FloatField are empty strings "". On the other side, some data which should be saved into a CharField is represented as np.nan. This leads to the following errors: ValueError: Field 'position_lat' expected a number but got nan. If I replace the np.nan with an empty string, using data[database]["df"].replace(np.nan, "", regex = True, inplace = True), I end up with the following error: ValueError: Field 'position_lat' expected a number but got ''. So what I would like to do, is to check in the model whether a FloatField or IntegerField gets either np.nan or an empty string and replace it with an empty value. The same for CharField, which should convert integers (if applicable) to strings or np.nan to an empty string. How could this be implemented? Using ModelManager or customized fields? Or any better approaches? Sorting the CSV files out is not an option. import pandas as pd import numpy as np from .models import Record my_dataframe = pd.read_csv("data.csv") record = Record entries = [] for e … -
What is the clean way to integrate another service to django
I have a Django 3 application, using an LDAP service class, like this : class LDAPService: def init(self, host: str, user: str, password: str, ssl: bool = True): ... def bind(): # The connection is done here, __init__ just sets values .... def create_ou(base: str, ou_name: str): .... Where (or when) should I initialize the service to use it in views ? The bind step takes about 2 seconds to apply, I can not do it on every request. How can I keep an instance of this class shared, and not done every single time ? I may have a solution using singleton, and/or initializing it in like settings files, but i think there is a better way to do it. I know in production, there may be multiple workers, so multiple instances, but i am ok with it. Another question: How can everything above be done, with connections credentials from a database model (so not at django startup, but at anytime) I am totally new to the django ecosystem, the things i have found about a service layer were all about django models. I think the LDAP connection itself should not be there, only the CRUD methods, but i … -
djangorestframework ModelSerializer serialize model Object but data is empty{}
I use djangorestframework, when I serializer a list of model objects,serializer.data is work, but when I serializer the model object only,serializer.data is the empty{}, why? model: class WindowInfo(models.Model): user = models.ForeignKey(WxAccount, on_delete=models.DO_NOTHING) add_time = models.DateTimeField(default=datetime.datetime.now) ModelSerializer: class WindowInfoSerializer(serializers.ModelSerializer): class Meta: model = WindowInfo fields = '__all__'enter code here view: class WindowInfoViewset(viewsets.GenericViewSet, mixins.CreateModelMixin): serializer = WindowInfoSerializer queryset =WindowInfo.objects.all() authentication_classes = [CustomerAuthentication] def create(self, request: Request, *args, **kwargs): window_info_list = WindowInfo.objects.all() window_info = window_info_list[0] window_info_list = WindowInfoSerializer(data=window_info_list, many=True) window_info_list.is_valid() window_info = WindowInfoSerializer(data=window_info, many=False) window_info.is_valid() print("window_info_list.data:") print(window_info_list.data) print("window_info.data:") print(window_info.data) then console: window_info_list.data: [OrderedDict([('id', 1), ('add_time', '2020-03-24T03:43:13.091961'), ('user', 1)])] window_info.data: {} why the window_info.data is {}? -
Use mongodb as second database for django app
I'm trying to setup two databases for my django app. The first is used for users and the second for any type of user content. The app is dockerized via docker compose. Here's the docker-compose.yaml file version: '3' services: postgres: image: postgres:latest environment: - POSTGRES_PASSWORD=test ports: - "5432:5432" restart: always mongodb: image: mongo:latest command: ["--bind_ip_all"] ports: - "27017:27017" restart: always django: build: . command: bash -c " python service_platform/manage.py makemigrations && python service_platform/manage.py migrate && python service_platform/manage.py runserver 0.0.0.0:8000 " volumes: - .:/code ports: - "8000:8000" depends_on: - postgres - mongodb links: - postgres - mongodb Below are the db settings of django's settings.py DATABASE_ROUTERS = [ 'content_manager.content_db_router.ContentDBRouter', ] DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'NAME': 'postgres', 'USER': 'postgres', 'HOST': 'postgres', 'PASSWORD': 'test', 'PORT': 5432, }, 'content': { 'ENGINE': 'djongo', 'NAME': 'mongodb', 'CLIENT': { 'host': 'mongodb', 'port': 27017, }, } } Here's the custom router I wrote class ContentDBRouter(object): content_db = 'content' default_db = 'default' def db_for_read(self, model, **hints): if model._meta.app_label == 'content_manager': return self.content_db return None def db_for_write(self, model, **hints): if model._meta.app_label == 'content_manager': return self.content_db return None def allow_migrate(self, db, app_label, model_name=None, **hints): if db == self.content_db: return True elif db == self.default_db: return True else: raise … -
Django: python manage.py runserver abort
I'm trying to set up a repo locally but facing an issue i.e python manage.py runserver command gets aborted as soon as I hit localhost URL (http://127.0.0.1:8000/) error - [1] 7398 abort python manage.py runserver Django version 1.6.6 Python 2.7 OS -> MacOS Catalina (10.15.3) Database postgres (PostgreSQL) 12.2 -
Django 3.0: Page not found at /polls/1/{url 'polls:vote' question.id}
I'm stucked at Django's official tutorial (see Writing your first Django app, part 4). I get the following error: In this Django project, inside the poll app I'm making, we're supposed to make a vote() view in views.py which should process the POST request data of the poll and redirect us to the results() view (there's no template for the vote()view, it's just in charge of processing the data we send through the poll). At first I thought I had a typo error, but I then copy-pasted everything directly out of the documentation tutorial (which I linked at the beginning of this question) and the error persisted. My directory structure looks like this for the app: (nevermind the errors, VSCode doesn't recognize Django'S ORM queries that's it) My urls.py file looks liket his: from django.urls import path from . import views app_name = 'polls' urlpatterns = [ path('', views.index, name='index'), path('<int:question_id>/', views.detail, name='detail'), path('<int:question_id>/results/', views.results, name='results'), path('<int:question_id>/vote/', views.vote, name='vote'), ] my views.py looks like this: from django.http import Http404, HttpResponse, HttpResponseRedirect from django.shortcuts import render, get_object_or_404 from django.urls import reverse from .models import Choice, Question def index(request): latest_question_list = Question.objects.order_by('-pub_date')[:5] context = {'latest_question_list': latest_question_list} return render(request, 'polls/index.html', context) def detail(request, … -
Django: Object attribute not saving/updating
I have following model: class Device(models.Model): #more_code supplier = models.ForeignKey( Supplier, on_delete=SET_NULL, blank=True, null=True, related_name="devices" ) I need a Patch endpoint to change the supplier from a Device. Everything in the view looks to work, only the device.save() doesn't update the state of the object This is my view: def patch(self, request, site_pk): """ PATCH the device's supplier info of the site. """ all_device_token = False if request.data.get("device") == "ALL": all_device_token = True arguments = {} else: device_pk = request.data.get("device") arguments = {"id": device_pk} devices = Device.objects.filter(site_id=site_pk, **arguments).all() if not devices.exists(): raise PermissionDenied("The device does not belong to the site.") if all_device_token: serializer_class = self.get_serializer_class() serializer = serializer_class( devices, many=True, data=request.data, partial=True, ) serializer.is_valid(raise_exception=True) new_supplier = get_object_or_404(Supplier, pk=request.data.get("supplier")) for device in devices: device.supplier.id = new_supplier.pk device.supplier.name = new_supplier.name device.save() else: device = devices.first() serializer_class = self.get_serializer_class() serializer = serializer_class(device, data=request.data, partial=True,) serializer.is_valid(raise_exception=True) if "supplier" in self.request.data: new_supplier = serializer.validated_data["supplier"] device.supplier.id = new_supplier.pk device.supplier.name = new_supplier.name device.save() # serializer.save() return Response(serializer.data, status=status.HTTP_200_OK) My serialiser is returning the correct info to. Do I see something overhead? -
Django 2 models 1 from
I am creating a project and I will have multiple pdfs per timeline, so I have created these following models: As a beginner to Django, I am confused as to how to upload the pdf file (that will be uploaded by the user). When I display it on forms, it shows me a field that resembles the one displayed for CHOICES. If I try for one file, it works perfectly but for 2 it doesn't. Question is: How can I display the FileField from the pdf model? class Pdf(models.Model): pdf = models.FileField(upload_to='timelinepdfs') class Timeline(models.Model): header = models.CharField(max_length=30, choices=HEADER_CHOICES) age = models.CharField(max_length=6, choices=AGE_CHOICES) pdfs = models.ForeignKey(Pdf, on_delete=models.CASCADE) This is my forms.py file: class TimelineForm(forms.ModelForm): class Meta: model = Timeline fields = ('header', 'age') class PdfForm(forms.ModelForm): class Meta: model = Pdf fields = ('pdf',) This is my view.py class: def upload_timeline(request): form = TimelineForm() return render(request, 'upload_timeline.html', { 'form': form }) -
How to use variables in django url path?
I am developing and Django website, and I have an array of some str values(parts of url).When user is redirect to: https://www.example.com/something/name/ how can system system knows that that is part of that arry. I alredy have this: urlpatterns = [ path(r'<name1>, views.example) ] And Array: arr = [name1,name2,name3, ....namen] Thank you in advance. -
How to reach and add new row to web server database which made in Django framework?
I am trying to create a web server which has Django framework and I am struggling with outer world access to server. While saying outer world I am trying to say a python program that created out of Django framework and only connects it from local PC which has only Internet connection. I can't figured it out how can I do this. I am building this project in my local host, so I create the "outer world python program" outside of the project file. I think this simulation is proper. I am so new in this web server/Django field. So maybe I am missing an essential part. If this happened here I'm sorry but I need an answer and I think it is possible to do. Thanks in advance... -
ModuleNotFoundError: No module named 'django_cleanup' while setup django application on Heroku
This is the first time when I try to setup my app on Heroku but I got error like in title. I checked almost everything, recreate requirements many times but it doesn't help. Someone has any idea how to solve this issue? #requirements asgiref==3.2.5 certifi==2019.11.28 chardet==3.0.4 dj-database-url==0.5.0 Django==2.2.10 django-cleanup==4.0.0 django-heroku==0.3.1 gunicorn==20.0.4 idna==2.9 psycopg2==2.8.4 pytz==2019.3 requests==2.23.0 sqlparse==0.3.1 stripe==2.43.0 urllib3==1.25.8 whitenoise==5.0.1 -
Location of settings.py for Django project in an anaconda virtual environment
I am following this tutorial for Django : https://www.youtube.com/watch?v=F5mRW0jo-U4&t=881s and when he talks about the settings.py file, he has it in the src folder in his virtual environment. I have the anaconda version of python on my windows 10 machine, so I installed Django using the following steps in the anaconda command prompt: conda create -n djangoenv python=3.7 anaconda conda activate djangoenv conda install -c anaconda django However, when looking for the setting.py file in C:\Users\billbrad\Anaconda3\envs\djangoenv, there is no src folder, and I cannot find the settings.py folder anywhere. Did I set up the env incorrectly, or am I just looking in the wrong place? -
Redirecting a user when payment is completed in an django e commerce website
I want to Redirect a user when payment is completed in an django e commerce site .IAM using a payment gateway that sends a json object on the submitted webhook that contains payment status. -
Ajax like button doesn't work on django posts list
I create my first site with django and i'm trying to make the Ajax like button works on the listing posts page but actually I have to reload the page to have +1 ... My views : def likes_post(request): post_id = None if request.method == 'GET': post_id = request.GET['post_id'] like = 0 if post_id: post = Post.objects.get(id = int(post_id)) if post: like = post.likes + 1 post.likes = like post.save() return HttpResponse(like) My HTML TEMPLATE : {% for post in posts %} <div class="post-favourite"> <a href="#" data-posts-id="{{post.id}}" class="like text-danger">J'aime <i class="fa fa-heart-o likes_count"aria-hidden="true"> {{ post.likes }}</i></a> </div> {% endfor %} and the Ajax function : <script type="text/javascript"> $('.like').click(function(){ var ps_id; ps_id = $(this).attr("data-posts-id"); $.get('/likes_post/', {post_id: ps_id}, function(data){ $(this).prev().find('.like_count').html(data); }); }); </script> (The Ajax button for the post detail page works good with simply replace by : $('.like_count').html(data); at the last line) Could you please help me ? Thank you in advance for your help ! -
Edit result of annotate in a Django queryset
I have a queryset queryset = BigTable.objects.values('field1__code', 'field2__code').annotate(Sum('field3')) the resulting value field3__sum = "1234567" is an integer and is very long for my template. How can I divide it by 1000 (for example) and get out it a decimal like "1234,5" ? Thank you -
How to make a background script with Django which check regularly on an InfluxDB database?
Context I'm designing a vizualisation application (like Grafana) with Django. The data come from multiples sensors (temperature etc..) and are stored in an InfluxDB database. I'd like to have a front-end where the user can see all his past data. To achieve this i plan to fetch the data in python with the InfluxDB API and plot them in Javascript (with plotly.js for example) when the user click a button or something similar. The really big trend in IoT is to be able to receive an alert when a data, for example temperature, reachs a certain threshold. So i'd like to give the user the opportunity to set custom threshold and to receive mail alert for example when the criteria is met. Problem In a Django environment, python code is executed once you reach a certain ressource, so how i can create a Python code which would run complelty in background (the user can close his browser), and checks periodically if a certain field in the database goes above a certain threshold ? Moreover this threshold needs to be updated dynamically if the user wants to change it. Solution envisaged When the user sets a threshold, Django writes in a … -
Reverse for 'authorize' not found. 'authorize' is not a valid view function or pattern name
CODE - urls.py from django.contrib import admin from django.urls import path, include from django.contrib.admindocs.urls import urlpatterns import oauth2_provider.views as oauth2_views from django.conf import settings from django.contrib.staticfiles.urls import static from django.contrib.staticfiles.urls import staticfiles_urlpatterns from DESKTOP.CORE_INDEX import index_urls from DESKTOP.CORE_INDEX import about_urls from DESKTOP.CORE_INDEX import privacy_urls from DESKTOP.CORE_INDEX import roules_urls from DESKTOP.CORE_INDEX import contacts_urls from typing import List from rest_framework.schemas import get_schema_view schema_view = get_schema_view(title="API_DESKTOP") schema_view = get_schema_view(title="API_MOBAPP") urlpatterns: List[path] = [] urlpatterns += [ path('index/', include(index_urls)), path('about/', include(about_urls)), path('privacy/', include(privacy_urls)), path('roules/', include(roules_urls)), path('contacts/', include(contacts_urls)), path('admin/', admin.site.urls), ] if settings.DEBUG: urlpatterns += static(settings.STATIC_URL, document_root=settings.STATIC_ROOT) urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) ERROR: django.urls.exceptions.NoReverseMatch: Reverse for 'authorize' not found. 'authorize' is not a valid view function or pattern name. [23/Mar/2020 18:13:57] "GET /admin/login/?next=/admin/ HTTP/1.1" 500 170378 I tried to understand what's going on but I can't. It's always giving me the same mistake. Above is the code for the part that is constantly giving me an error and I can't find the error. Can help me? -
Django filter by ForeignKey-attribute as User
I'm using a Django framework to make a database-application. I have a my database structure as classes. A "Horse"-class that have a ForeignKey relationship with a "Rider"'-class, which in turn have a ForeignKey relationship with the User. It's all working, but I want to filter the horses so only the horses that are connected to the current User will show. file: models.py from django.contrib.auth.models import User class Horse(models.Model): name = ... ... owner = models.ForeignKey('Rider') class Rider(models.Model): name = ... ... user = models.ForeignKey(User) So when I render my html-page, I want to filter the horses accordingly: file: views.py from .models import Horse def Horses(request): horses = { 'horses': Horse.objects.filter( ??????? ) } return render(request, 'stable/horses.html', horses) So if I'm logged in as "Admin", how do I pass this into the filter, so all horses that have a relationship with a rider that have a relationship with this user will show? Seems to be something different when referring to a ForeignKey-object instead of just an attribute that I can't figure out. -
is it possible to run celery, celery beat and celery flower from one command?
I have installed celery, celery beat and celery flower all on one container, im using rabbitmq as the broker and Redis as the backend. settings below: app = Celery('itapp', broker='amqp://lcl_rabbit:5672', backend='redis://lcl_redis:6379', include=['itapp.tasks']) im trying to run all three of these on startup of one container, I have the command below, but it looks like its only running celery and flower and skipping beat. as I aren't seeing any scheduled tasks run celery flower -A itapp -l info --beat --scheduler django_celery_beat.schedulers:DatabaseScheduler --port=5555 is this not possible or not avisable? ideally im just looking to see the results of the tasks that have been scheduled with beat, I can see their being run as the last run timestamp is incrementing and I can see them being sent to a worker in the terminal. but not sure where I can see all the results and came across flower... Thanks