Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Installation of GDAL on MacOS Catalina is failing
I'm trying to install GDAL on my mac (Catalina 10.15.7) using brew: brew install gdal but I'm running into an error that I don't understand: ==> Pouring glib-2.66.4.catalina.bottle.tar.gz cp: utimes: /usr/local/Cellar/glib/.: Operation not permitted cp: chmod: /usr/local/Cellar/glib/.: Operation not permitted Error: Failure while executing; `cp -pR /var/folders/7f/r7941wjd1fj2zlm79hwzlkcc0000gn/T/d20201223-26491-1643kjj/glib/. /usr/local/Cellar/glib` exited with 1. Here's the output: cp: utimes: /usr/local/Cellar/glib/.: Operation not permitted cp: chmod: /usr/local/Cellar/glib/.: Operation not permitted Warning: Bottle installation failed: building from source. ==> Patching Error: An exception occurred within a child process: Errno::ENOENT: No such file or directory @ rb_sysopen - /Users/<my_username>/Library/Caches/Homebrew/downloads/54f3f612bdfc9bfc09633176c7673816fe2a2188e470bf48d60d826bdf6bf21a--hardcoded-paths.diff I've also tried the following: brew install --build-from-source gdal But I run into the exact same error. I don't really understand what's the problem, though it seems to be related to permissions. I need some help on what I should do to resolve it. -
django.template.exceptions.TemplateDoesNotExist:/hello/
I created a function hello>view.py def index (request): return render(request,"hello/index.html") and an HTML file in hello>template>hello>index.html, but the is what I've got Internal Server Error: /hello/ Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/handlers/exception.py", line 47, in inner response = get_response(request) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/handlers/base.py", line 179, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/Users/douju/lecture3/hello/views.py", line 7, in index return render(request,"hello/index.html") File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/shortcuts.py", line 19, in render content = loader.render_to_string(template_name, context, request, using=using) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/template/loader.py", line 61, in render_to_string template = get_template(template_name, using=using) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/template/loader.py", line 19, in get_template raise TemplateDoesNotExist(template_name, chain=chain) django.template.exceptions.TemplateDoesNotExist: hello/index.html -
How to return data in Django model from database
I'm trying to return the data from the database in the Django model. Actually, I'm using my own encryption technique. So, I'm encrypting the data in save view in the model. The project is very big. I have a manual method. But I'm trying if there is any built-in model view like save in Django model to return all the fields data and to decrypt as well in the model. Here is my code. class TestModel(models.Model): testingText1 = models.CharField(null=True, blank=True,max_length=1000) testingText2 = models.CharField(null=True, blank=True,max_length=1000) def save(self,*args,**kwargs): self.testingText1 = encrypt(self.testingText1) self.testingText2 = encrypt(self.testingText2) super(TestModel, self).save(*args,**kwargs) Thanks in advance for any help. -
Problems with Django/Apache setup
I'm trying to host my personal website using Django WSGI deployment on Apache, but I'm getting the following error: AH01276: Cannot serve directory /var/www/django/: No matching DirectoryIndex My Django project folder is /var/www/django <VirtualHost *:80> ServerAdmin root@educorreia932.dev ServerName educorreia932.dev ServerAlias www.educorreia932.dev DocumentRoot /var/www/django ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog ${APACHE_LOG_DIR}/access.log combined Alias /static /var/www/django/static <Directory /var/www/django/static> Require all granted </Directory> <Directory /var/www/django/website> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess django python-path=/var/www/django/ python-home=/var/www/django/venv WSGIProcessGroup django WSGIScriptAlias / /var/www/django/website/wsgi.py RewriteEngine on RewriteCond %{SERVER_NAME} =www.educorreia932.dev [OR] RewriteCond %{SERVER_NAME} =educorreia932.dev RewriteRule ^ https://%{SERVER_NAME}%{REQUEST_URI} [END,NE,R=permanent] </VirtualHost> -
django html editor to add image in CharField form
I m using Django-wiki which use // markItUp! Universal MarkUp Engine, JQuery plugin in article form But in Django-wiki form used for create or edit articles I don't see how to add an image like in stack overflow So I would like to create a JS code to add image as in stack overflow. My question is: how to create that code (is stack overflow code is open source?) and secondly ho can I save image in my Django App? thanks for any link to help -
passing csrf_token through dynamically-generated form
I have a reddit-style threaded messageboard app which includes the functionality to reply in-line to comments via a separate javascript function. In the template file there is a link after each post: <a href="{% url 'posts:comment' post_id=post.id %}" onclick="quick_reply(this, '{% url 'posts:comment' post_id=post.id %}'); return false;">reply</a> The quick_reply function that generates the form is in a self-contained javascript file: function quick_reply(element, formURL){ ... quickReplyForm.innerHTML = ... "<div class=\"quick-reply-wrapper\">"+ "<form method=\"post\" action=\""+formURL+"\">"+ "<label for=\"id_subject\">Subject</label><input type=\"text\" class=\"subject\" name=\"subject\" id=\"id_subject\" maxlength=\"100\"/><br/>"+ "<label for=\"id_body\">Body</label><textarea name=\"body\" id=\"id_body\"></textarea><br/>"+ "<input type=\"submit\" value=\"Submit\" class=\"submit\"/>"+ "<input type=\"button\" value=\"Never mind...\" class=\"button\" onclick=\"quickReplyTransition.toggle();\"/>"+ "</form>"+ "</div>"; ... } (for clarity I have removed the other code from that function which is just dealing with visual effects) At the moment submitting the contents of the form generates a 'CSRF verification failed' error - but how can I pass through the csrf token from the template so that it can be placed in the dynamically-generated form? I can see that one answer would be to include the javascript function within the template file itself and add the form field there, but I would prefer to keep this in a separate javascript file in the static app if at all possible. Can this be done? … -
add images in a Django form CharField
I'm working on a wiki site with Django-wiki. When I want to create a new article, my issue is that I cannot copy paste an image in charfield. If I use drag and drop, the path is add to my CharField but not the image. I want to do like in Wikipedia having text and image in the article. Code is like this: create_article"html <form method="POST" class="form-horizontal"> {% wiki_form form %} <div class="form-group form-actions"> <div class="col-lg-2"></div> <div class="col-lg-10"> <button type="submit" name="save_changes" class="btn btn-primary btn-lg"> {% trans "Create root" %} &raquo; </button> </div> </div> </form> form is like this in Django-wiki: class CreateRootForm(forms.Form): title = forms.CharField( label=_("Title"), help_text=_( "Initial title of the article. May be overridden with revision titles." ), ) content = forms.CharField( label=_("Type in some contents"), help_text=_( "This is just the initial contents of your article. After creating it, you can use more complex features like adding plugins, meta data, related articles etc..." ), required=False, widget=getEditor().get_widget(), ) # @UndefinedVariable and model is -
can't adapt type 'InMemoryUploadedFile' in S3DirectField Django
I'm trying to store images in s3 of AWS and I got the error. I'm using postman to post data. Body is format data and header is multipart/form-data. I'm following these two tutorial. https://simpleisbetterthancomplex.com/tutorial/2017/08/01/how-to-setup-amazon-s3-in-a-django-project.html https://django-storages.readthedocs.io/en/latest/backends/amazon-S3.html setting.py INSTALLED_APPS = [ 'storages', 's3direct', ... ] AWS_ACCESS_KEY_ID = '*****' AWS_SECRET_ACCESS_KEY = '****' AWS_STORAGE_BUCKET_NAME = 'example-storage' AWS_S3_REGION_NAME = 'us-east-2' AWS_S3_ENDPOINT_URL = 'https://s3.us-east-2.amazonaws.com' AWS_S3_CUSTOM_DOMAIN = '%s.s3.amazonaws.com' % AWS_STORAGE_BUCKET_NAME AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': 'max-age=86400', } AWS_LOCATION = 'static' S3DIRECT_DESTINATIONS = { 'primary_destination': { 'key': 'images/', 'allowed': ['image/jpg', 'image/jpeg', 'image/png'], }, } STATIC_URL = 'https://%s/%s/' % (AWS_S3_CUSTOM_DOMAIN, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' DEFAULT_FILE_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' { "Version": "2012-10-17", "Statement": [ { "Effect": "Allow", "Action": [ "s3:GetObject", "s3:PutObject", "s3:PutObjectAcl", "s3:ListMultipartUploadParts", "s3:AbortMultipartUpload" ], "Resource": "arn:aws:s3:::speakup-image-storage/*" } ] } urls.py urlpatterns = [ path('s3direct/', include('s3direct.urls')), ... ] models.py class Image(models.Model): image = S3DirectField(dest='primary_destination', blank=True) default = models.BooleanField(default=False) width = models.FloatField(default=100, null=True) length = models.FloatField(default=100, null=True) album = models.ForeignKey(Profile, related_name='images', on_delete=models.CASCADE) def __str__(self): return '{}'.format(self.image) My s3 has the folder called images and CORS is like this [ { "AllowedHeaders": [ "*" ], "AllowedMethods": [ "POST", "GET", "PUT" ], "AllowedOrigins": [ "*" ], "ExposeHeaders": [] } ] Do I miss something or Did I add something too mach? If you need views.py … -
How to get Content-Disposition header
I want to get the content of the "Content-Disposition" my backend code using Django Rest Framework, the specific code like following: with open(results['filepath'], 'rb') as target: response = HttpResponse(target) response['Content-Type'] = 'application/octet-stream' filename = results['filename'] disposition = "attachment; filename*=UTF-8''{}".format(filename) response["Content-Disposition"] = disposition return response my frontend code use vue, the specific code like following: this.$axios.post( `/api/v1/applications/pod-dlfiles/?cluster=${this.dialogFile.cluster}&name=${this.dialogFile.name}&ns=${this.dialogFile.namespace}&cr=${this.dialogFile.container}`, data ).then((res) => { console.error('restest', res) var fileURL = window.URL.createObjectURL(new Blob([res])) var fileLink = document.createElement('a') fileLink.href = fileURL fileLink.setAttribute('download', `${this.dialogFile.name}` + '.txt') document.body.appendChild(fileLink) fileLink.click() }) I printed the value of the 'res', and the result is the contents of the file. There are no other attributes. why? -
Django Bootstrap - How to change width of dropdown menu items
I have created a menu and then submenu for my website. The links are all working as expected but I have an issue with layout. When I click on particular menu item, a submenu appears but the width of submenu box is too big as I just have to show 2 items (rent and buy). Can you please assist as to what can I do to correct this? I am using Bootstrap.min.css. Please see template file below [![{% load static %} <!-- Navbar --> <div id="sticky-header" class="header-middle-area transparent-header hidden-xs"> <div class="container"> <div class="full-width-mega-drop-menu"> <div class="row"> <div class="col-md-12"> <div class="sticky-logo"> <a href="{% url 'index' %}"> <img src="{% static 'index1/images/logo/logo3.png' %}" alt=""> </a> </div> <nav id="primary-menu"> <ul class="main-menu text-center"> <li><a href="{% url 'index' %}">{% if '/' == request.path %} <mark>Home</mark> {% else %} Home {% endif %}</a> </li> <li class="nav-item dropdown"> <a class="nav-link dropdown-toggle" href="#" id="navbarDropdown" role="button" data-display="static" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> {% if 'listings_residential_rent' in request.path %} <mark>Residential Rent</mark> {% else %} Residential {% endif %} </a> <div class="dropdown-menu aria-labelledby="navbarDropdown"> <a href="{% url 'listings_residential_rent' %}">Rent</a> <a href="https://www.youtube.com/"> Buy </a> </div> </li> <li><a href="{% url 'admin:index' %}">Realtor Login</a> </li> </ul> </nav> </div> </div> </div> </div> </div>][1]][1] -
why let's encrypt certificate(SSL) error installing django site which is hosted in Ubuntu vps
I have successfully deployed the Django project in my ubuntu VPS server. but when i try to install sudo certbot --apache -d amritshahi.com. I am getting the following error. Enabling available site: /etc/apache2/sites-available/365-le-ssl.conf Error while running apache2ctl configtest. Action 'configtest' failed. The Apache error log may have more information. AH00526: Syntax error on line 25 of /etc/apache2/sites-enabled/365.conf: Name duplicates previous WSGI daemon definition. Rolling back to previous server configuration... Error while running apache2ctl configtest. Action 'configtest' failed. The Apache error log may have more information. AH00526: Syntax error on line 25 of /etc/apache2/sites-enabled/365.conf: Name duplicates previous WSGI daemon definition. inside 365.conf file: <VirtualHost *:80> ServerAdmin me@amritshahi.com ServerName amritshahi.com ServerAlias www.amritshahi.com DocumentRoot /var/www/personal Alias /static /var/www/personal/Personal_Blog/static <Directory "/var/www/personal/Personal_Blog/static"> Options Indexes FollowSymLinks Order allow,deny Allow from all Require all granted </Directory> Alias /media /var/www/personal/Personal_Blog/media <Directory "/var/www/personal/Personal_Blog/media"> Options Indexes FollowSymLinks Order allow,deny Allow from all Require all granted</Directory> ErrorLog ${APACHE_LOG_DIR}/shahi_error.log CustomLog ${APACHE_LOG_DIR}/shahi_access.log combined WSGIDaemonProcess Personal_Blog python-home=/var/www/personal/Personal_> WSGIProcessGroup Personal_Blog WSGIScriptAlias / /var/www/personal/Personal_Blog/project/wsgi.py <Directory /var/www/personal/Personal_Blog/project> <Files wsgi.py> Require all granted </Files> </Directory> </VirtualHost> Help Please?? -
Django: exclude some objects
i want to exclude some user from the User model, who are exists in friends, i_requested, requested_me . models.py: class Relation(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) friends = models.ManyToManyField(User, related_name='my_friends', blank=True) i_requested = models.ManyToManyField(User, related_name='i_requested', blank=True) requested_me = models.ManyToManyField(User, related_name='requested_me', blank=True) views.py: def allUser(request): me = request.user f = Relation.objects.get(user=me) ff = f.friends.all() users = User.objects.all() exclude = users.exclude(id__in=ff) print(exclude) print(ff) serializer = SimpleUserSerializer(user, many=True) return Response(serializer.data) when i run this code, it prints: <QuerySet [<User: test5>, <User: test3>, <User: test2>]> <QuerySet [<User: test5>]> why it don't exclude test5? -
Method \"POST\" not allowed in Django rest framework ModelViewset
I am trying to POST with extra actions in Django Rest, but am getting this error {"detail":"Method \"POST\" not allowed."} This is the method for POST : class TemplateView(ModelViewSet): @action(detail=False, methods=['POST'], url_path=r'process_version_template/') def process_version_template(self, request): print("request", request) return JsonResponse({}, safe=False, status=200) In my urls.py : api_router = DefaultRouter() api_router.register(r'template', views.TemplateView, 'template') urlpatterns = [ path('predefined-comments', PredefinedCommentListView.as_view(), name='predefined_comments'), ] urlpatterns += api_router.urls Then my endpoint am using in Postman to send data is : http://127.0.0.1:8000/api/v1/financing-settings/template/process_version_template/ then, the body is : { "id":1784, "param":"block", "target":315 } What am I doing wrong ? -
How to use same django filter(filters.py) in two different views
I have a filter class defined below. filters.py class CTAFilter(django_filters.FilterSet): id = django_filters.NumberFilter(label="DSID") class Meta: model = CTA fields = ['id', 'EmailID','id','Shift_timing'] Now I want to use this CTAFilter in normal template(table data)view and in download views. I have observed that It is working fine for normal render view but when I am using it in my download views it is not working and I am getting all model data in the .xls file. Please find the below questions which I have posted. how to use Django filtered class data to 2 seperate view I am not able to resolve this problem I have tried to check if I can define it globally so that the filter will work for all views(like RESTAPI). Is there any way I can make my download view as a child view class of normal render view so that I will use the below code from the parent view(as it is working fine)? cta_list = CTA.objects.all() cta_filter = CTAFilter(request.GET, queryset=cta_list) allcta = cta_filter.qs A>Normal View where the filter is working fine. def retrievecta_view(request): if request.method == 'GET': allcta = CTA.objects.all() allcta1 = allcta allctagen = allcta1.filter(Shift_timing__exact='General') allctamor = allcta1.filter(Shift_timing__exact='Morning') allctseve = allcta1.filter(Shift_timing__exact='Evening') allctatotal = allcta1.filter(Shift_timing__exact='Total') … -
Watching for file changes with StatReloader Exception in thread django-main-thread, when i run python manage.py runserver using django
just started learning Django, this is what happened when I use python manage.py runserver SyntaxError: invalid syntax maonanbei:lecture3 duomi$ python3 manage.py runserver Watching for file changes with StatReloader Exception in thread django-main-thread: Traceback (most recent call last): File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 950, in _bootstrap_inner self.run() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/threading.py", line 888, in run self._target(*self._args, **self._kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run autoreload.raise_last_exception() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception raise _exception[1] File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/core/management/__init__.py", line 357, in execute autoreload.check_errors(django.setup)() File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/utils/autoreload.py", line 53, in wrapper fn(*args, **kwargs) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/registry.py", line 91, in populate app_config = AppConfig.create(entry) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/site-packages/django/apps/config.py", line 116, in create mod = import_module(mod_path) File "/Library/Frameworks/Python.framework/Versions/3.9/lib/python3.9/importlib/__init__.py", line 127, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 972, in _find_and_load_unlocked File "<frozen importlib._bootstrap>", line 228, in _call_with_frames_removed File "<frozen importlib._bootstrap>", line 1030, in _gcd_import File "<frozen importlib._bootstrap>", line 1007, in _find_and_load File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked ModuleNotFoundError: No module named 'hellodjango' I added a new application call "hello", a function to send a request to ask for respond and in hello/view.py look … -
updated queue in RabbitMQ
I have a task that is to be executed after a POST or PATCH for an object, say ABC The code goes as follows: models.py class ABC(models.Model): start_at = models.DateTimeField() task.py @app.task def do_something(obj_id): try: abc = ABC.objects.get(id=obj_id) except ObjectDoesNotExist: return eta = settings.ETA do_something.apply_async([abc.id], eta=eta) return views.py class ABCPost(CreateAPIView): serializer_class = ABCSerializer def post(self, request): # create object # call task do_something def patch(self, request): # update the `start_at` field for ABC # call task do_something So, when the field is updated, the queued message should be executed at the updated start_at value. However, with the code above two messages are queued for the same object but different timestamps. How can I avoid that? Thanks in advance -
Fat Models, working out variables based on other date
I am still fairly new to Django but I am trying to stick to the fat model, thin controller aspects of Django. I have a price input that could change so this has been assigned to a form: class AdminData(models.Model): year1 = models.IntegerField() year3 = models.IntegerField() I want to work out the day_rate for these services based on different factors such as weeks in a year and hours per day which are fixed outside my model weeksinyear = 52 How can I get a day_rate fixed variable based on the user input for a 1 year and 3 year options, my initial thoughts were to create a variable like below, which does not work. week_rate_year1 = year1 / weeksinyear Any help is greatly appreciated, am I suppose to do this via models or should this code run in the template or view? As it is a static value based on the user inputted value I am not sure. Thanks for helping a noob. -
i need to host a django app to a shared VPS (latin cloud)
https://la.latincloud.com/938948-Soporte-para-Python i have to host a django website on a shared vps (latin cloud ).they provided in their document how to deploy i have provide the link but could not understand how to link to the env and wsgi file.i have to host a django website on a shared vps (latin cloud ).they provided in their document how to deploy i have provide the link but could not understand how to link to the env and wsgi -
Django + init.js + breakpoints
I am very new to Django. I am also not very knowledgeable in JS (at this point I am mainly interested in the backend side of things). I downloaded a portfolio and it seems to have JS scripts connected between each other (I am unsure if this is related to the issue). The init.js file controls the breakpoints and then depending of size of window opens up the appropiate CSS file. This might be a newbie thing but I used {% static '...' %} in the js files but the they don't load up when refreshing website. Do I meant to do something different? Below are few excepts from my files. Home.html init.js (I changed the init.js back to normal without {% static '...' %} -
Connect Django to MySql database on VPS
I am trying to run my Django project on a VPS. My Django project uses MySQL. While running it on my local computer I used the following code to connect MySQL to Django DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'db_name', 'USER': 'root', 'PASSWORD': 'password', 'HOST': 'localhost', 'PORT': 3306} } What must be the 'USER','HOST','PORT' here while connecting to MySQL? -
Modal dialogue does not open
I want a confirmation window to popup when a record is clicked for deletion. Below is mylibre/cms/templates/cms/base.html. {% load i18n static %} <!DOCTYPE html>{% get_current_language as LANGUAGE_CODE %} <html lang="{{ LANGUAGE_CODE|default:"en-us" }}"> <head> <meta charset="UTF-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="{% static 'cms/css/bootstrap.min.css' %}"> {% block extra_css %}{% endblock %} <title>{% block title %}My books{% endblock %}</title> </head> <body> <div class="container"> {% block content %} {{ content }} {% endblock %} </div> <script src="{% static 'cms/js/jquery-3.5.1.min.js' %}"></script> <!-- <script src="https://code.jquery.com/jquery-3.1.1.min.js"></script> --> <script src="{% static 'cms/js/bootstrap.bundle.min.js' %}"></script> {% block extra_js %}{% endblock %} </body> </html> From which mylibre/cms/templates/cms/info_list.html is created. "Modal Dialogue Confirming Deletion" does not get called. At least I don't see any evidence of it being called. {% extends "cms/base.html" %} {% block title %}List of Comments{% endblock title %} {% block content %} <h4 class="mt-4 border-bottom">List of Comments<small class="text-muted ml-3">{{ ward.name }}</small></h4> <a href="{% url 'cms:info_add' ward_id=ward.id %}" class="btn btn-primary btn-sm my-3">Add</a> <table class="table table-striped table-bordered"> <thead> <tr> <th>ID</th> <th>コメント</th> <th>Manipulate</th> </tr> </thead> <tbody> {% for info in infos %} <tr> <td>{{ info.id }}</td> <td>{{ info.comment|linebreaksbr }}</td> <td> <a href="{% url 'cms:info_mod' ward_id=ward.id info_id=info.id %}" class="btn btn-outline-primary btn-sm">Modify</a> <button class="btn btn-outline-danger btn-sm del_confirm" data-toggle="modal" data-target="#deleteModal" data-pk="{{ … -
Django form not visible after redirect
I'm trying to make django form to appear after user is logged in and authenticated but the form just does not appear on the page here is my code. Is it something I do wrong in redirects or something else? If you guys could help me figure this out that would be nice views.py code from django.shortcuts import render from django.http import HttpResponse, HttpResponseRedirect from django.urls import reverse from loginas.auth_helper import get_sign_in_url, get_token_from_code, store_token, store_user, remove_user_and_token, get_token from loginas.graph_helper import get_user from .forms import Prasymas from .models import Post def home(request): context = initialize_context(request) return render(request, 'loginas/home.html', context) def initialize_context(request): context = {} # Check for any errors in the session error = request.session.pop('flash_error', None) if error != None: context['errors'] = [] context['errors'].append(error) # Check for user in the session context['user'] = request.session.get('user', {'is_authenticated': False}) return context def sign_in(request): # Get the sign-in URL sign_in_url, state = get_sign_in_url() # Save the expected state so we can validate in the callback request.session['auth_state'] = state # Redirect to the Azure sign-in page return HttpResponseRedirect(sign_in_url) def callback(request): # Get the state saved in session expected_state = request.session.pop('auth_state', '') # Make the token request token = get_token_from_code(request.get_full_path(), expected_state) # Get the user's profile user … -
Django url prefix association
I'm very new to Django & hoping I can get some guidance on a question I had. I want to have multiple URL prefixes each with a different site prefix for my client's projects for example client1.website.com. Each prefixed site will have a different database associated. Is this something that's possible to do with Django? Can some please point me in the right direction? -
Copy data between Django-Models (from View to table)
I’m new to Python and Django, and I’m trying to create WebApp with Django. I was trying to find a solution for two days. Thank you for your help in advance. Problem. In the app, I have a "view" where ingredients from Larder are listed, I want to choose ingredients and specify how much of it a ate and save it in the Ingredients_eaten model, but to do this, I need to pass few data from Larder (Ingredient name, quantity, unit). How can I do it? In View.py I know how to save data from the form (two fields), but I miss those three fields from Larder, and I don’t know to do it. I have three models Ingredients_bought – where the user specifies what kind of ingredient he/she buy, e.g. Milk, Eggs Larder – this is a MySQL view which group data from ingredients_bought by name and unit (e.g., If I buy milk twice, I will see one line with quantity two) Ingredient_eaten – in this model, I want to store information about what I ate. And here I have a problem. View: def larder_detail_view(request): obj = Larder.objects.all() form = EatForm() if request.method == 'POST': form = EatForm(request.POST) if … -
Django : filter object based on a date
I'm trying to filter my request based on a date field. I would like to check if a date is greater than the current date. This is what I tried, based on this answer : How do I filter query objects by date range in Django? orders.object.filter(deliveryDay__gt = date.today()).order_by('-id') Unfortunately it didn't work in my query which returns all orders to me regardless of the date. I don't understand where is my error. Thank you by advance for your help.