Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Generating Error "errors": [ { "message": "There is no current event loop in thread 'Thread-5'." using graphql and django
this is the error I'm getting while fetching comments in graphql [ model I have created in django schema I have created is here]3 -
Stencil setup: resolve, rollup version
I have two problems, both related to setting up my project. The ultimate goal is to build some web components that communicate vis OSC using node-osc. My first attempt to set up the project and create a component that uses node-osc resulted in the following message: Bundling Warning UNRESOLVED_IMPORT 'node-osc' is imported by ./src/components/r-channel/r-channel.tsx, but could not be resolved – treating it as an external dependency This gave me a successful build, but my components don't render, so I assume it's not actually all that successful. After some reading, my guess is that I should at least try plugin-node-resolve. I've installed and added to my stencil.config.ts, and am now seeing: Rollup: Plugin Error Insufficient rollup version: "@rollup/plugin-node-resolve" requires at least rollup@2.78.0 but found rollup@2.42.3. (plugin: node-resolve, buildStart) ...although my package-lock.json seems to indicate that I've got rollup@2.79.1 installed. -
Django monolith: How to render front-end while still loading one function from backend
I have a django monolith project; however, one of the objects (a graph) that I pass to the template context to display in the html is slow to load. I'd like to have the rest of the page render first, while this function is still running/loading. That way, users can see the rest of the page while the graph is still loading. Thoughts on the best approach to this? I tried creating a custom tag to load the graph, but the browser still waited for the everything to load before showing anything on the page. I'm wondering if some type of javascript call would accomplish this. -
How to create SO like tags in django?
Given a form, I need it to have tags (preferably) or any form which enables multiple selection with simple search/autocomplete. Something similar to SO tags will do: -
Bootstrap 5.2 Modals not appearing when using docs example
Literally copy pasting documentation Example from https://getbootstrap.com/docs/5.2/components/modal/: <!-- Button trigger modal --> <button type="button" class="btn btn-primary" data-bs-toggle="modal" data-bs-target="#exampleModal"> Launch demo modal </button> <!-- Modal --> <div class="modal fade" id="exampleModal" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h1 class="modal-title fs-5" id="exampleModalLabel">Modal title</h1> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> ... </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> I am using Django to develop a website with Python (which shouldn't matter here), I have an index.html with this headers: <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.3/jquery.min.js" integrity="xxx" crossorigin="anonymous" referrerpolicy="no-referrer"></script> <link rel="stylesheet" href="https://cdn.jsdelivr.net/npm/bootstrap@5.2.3/dist/css/bootstrap.min.css" integrity="xxx" crossorigin="anonymous"> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/2.9.2/umd/popper.min.js" integrity="xxx" crossorigin="anonymous" referrerpolicy="no-referrer"></script> The modal isn't working and I am not sure why, can someone assist? I am not using any javascript on top of that. Isn't it supposed to work already with the '''data-bs-''' tags? Much thanks. I tried taking all CDN's updated versions. I also checked the other StackOverflow posts but they either aren't updated or didn't solve my problem... bootstrap modal not working at all I even tried adding the jquery from here, without success: Bootstrap modal not working after clicking button Maybe I did something incorrect, as I don't have extense experience. -
what comes after begin a Django backend developer?
iam Django backend developer freelancer iam not looking for any kind of jobs idc about money I don't wanna be a normal programmer I have learnt all programming basics and programming logic I almost know every thing about rest api I have reached an advanced level on Django framework, Django restframework, signals, and react js, node js now I want something to focus on! something let me create more advanced and complicated projects like wix.com for example I already done a lot of advanced projects, even ideas from Google or freelance websites what should I start to learn? iam 17 years old I tried to search on YouTube, google but I didn't find what iam looking for I have read about GO programming language but idk what to do now -
Disable admin application for django
I am trying to run the django development server and its failed with below error. Exception in thread django-main-thread: Traceback (most recent call last): File "/my/virtual/lib/python3.8/threading.py", line 932, in _bootstrap_inner self.run() File "/my/virtual/lib/python3.8/threading.py", line 870, in run self._target(*self._args, **self._kwargs) File "/my/virtual/environment/lib/python3.8/site-packages/django/utils/autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "/my/virtual/environment/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 118, in inner_run self.check(display_num_errors=True) File "/my/virtual/environment/lib/python3.8/site-packages/django/core/management/base.py", line 469, in check raise SystemCheckError(msg) django.core.management.base.SystemCheckError: SystemCheckError: System check identified some issues: ERRORS: ?: (admin.E403) A 'django.template.backends.django.DjangoTemplates' instance must be configured in TEMPLATES in order to use the admin application. this is django-rest-framework application and it has no admin application. How to say django runserver to not run admin application? -
request.user.is_authenticated cycling between True and False when logged in Django
I made a middleware that returns 403 Forbidden if the user is not authenticated but after logging in, each time I refresh the page I am logged in then logged out and so on. This is only happening in production on Ubuntu DigitalOcean droplet running Gunicorn and Nginx. middleware.py from django.shortcuts import render def IsAuthMiddleware(get_response): def middleware(request): if (request.path.startswith('/dashboard') or 'account' in request.path) and not request.user.is_authenticated(): context = { "title": "Not logged in", "message": "- You are not logged in." } return render(request, '403.html', context) response = get_response(request) if response.status_code == 403: res = render(request, '403.html', {'message': response.content.decode()}) res.status_code = 403 return res if response.status_code == 404: res = render(request, '404.html', {'message': response.content.decode()}) res.status_code = 404 return res return response return middleware views.py from django.shortcuts import render from .models import Message from dashboard.models import Subscriber, Newsletter, Unsubscription from django.core.exceptions import ObjectDoesNotExist, ValidationError from django.db.utils import IntegrityError from django.http import HttpResponseNotFound from django.core.validators import validate_email from django.views.decorators.csrf import csrf_exempt from django.utils import timezone # Create your views here. def index(request): context = { "title": "Home", } return render(request, 'main/index.html', context) def privacy(request): return render(request, 'main/privacy.html') def contact(request): if request.method == "POST": context = { "title": "Contact", "msg": True, "good": True, "msg_content": … -
Is there a way to register "Comments" model (filtered by post) inside "Posts/SomePost in Django administration?
I'm trying to to make each post (inside admin) have a "Comments" like field that are specific to that post instead of having "Comments" as a separate section from "Posts". Is this possible? -
Cannot Login to Django admin with my superuser account when it is on Deployment, showing CSRF error 403 forbidden
I am super newbie on DJango and Programming. I made a backend server with django and deployed successfully on "render.com". I can approach to admin login screen but cannot login to it with my superuser ID. [it worked in runserver perfect but does not work on deployment... showing error below :-( ] Forbidden (403) CSRF verification failed. Request aborted. You are seeing this message because this site requires a CSRF cookie when submitting forms. This cookie is required for security reasons, to ensure that your browser is not being hijacked by third parties. If you have configured your browser to disable cookies, please re-enable them, at least for this site, or for 'same-origin' requests. I googled some articles about it. and they told me that I have to add CSRF_TRUSTED_ORIGINS= ["mydomain"] on settings.py Here is the questions... Q1. Do I have to put my frontend domain or backend domain in "mydomain" ? Q2. Some articles said that I have to add CSRF_COOKIE_SECURE = False in my settings.py too?? -
How do I pass an IP address to Google geolocation api?
I have a Django web app that deploys on Heroku, so I'm trying to get the actual user's IP, not the heroku server. Everything works fine when I run the project locally. When I deploy it to Heroku, it gives me the Heroku server location, even though I get the correct IP from x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR'). Am I passing it incorrectly to google? def get_latitude_longitude(request): # Get the user's IP address x_forwarded_for = request.META.get('HTTP_X_FORWARDED_FOR') if x_forwarded_for: ip_address = x_forwarded_for else: ip_address = request.META.get('REMOTE_ADDR') url = f"https://www.googleapis.com/geolocation/v1/geolocate?key={settings.GOOGLE_API_KEY}&considerIp=true&ipAddress={ip_address}" # Make the request response = requests.post(url) # Check the response status code if response.status_code != 200: print(response) # Parse the response data data = response.json() latitude = data['location']['lat'] longitude = data['location']['lng'] accuracy = data['accuracy'] return latitude, longitude, data, ip_address -
querying database to give specific need in Class Base View doesn't work
I created a school database to store student informations, as a school database that can be used in different schools, when user try to create Primary model, it shown every Album that is created by other schools, instead of showing an Album that is created by a particular school. I don't want others school to be able see all the Album that isn't their own. Here is how I did it, but doesn't work: Class CreatePrimary(CreateView): Model = Primary Fields = ['profilePicture', 'first_name', 'last_name', 'year_of_graduation'] template_name = 'create_primary.html' success_url = ('Home') #trying to use "filter", but it doesn't work def get_queryset(self): return Album.objects.filter(user=self.request.user) def form_valid(self, form): form.instance.user = self.request.user return super (CreatePrimary, self).form_valid(form) Class Album(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) name = models.charfield(max_length=20) Class Primary(models.Model): profilePicture = models.FilesField(upload_to='image') first_name = models.charfield(max_length=20) last_name = models.charfield(max_length=20) year_of_graduation = models.Foreignkey(Album, on_delete=models.CASCADE) '''' -
It's difficult to say exactly what might be causing the error
[28/Dec/2022 20:24:21] "GET /signup?csrfmiddlewaretoken=l9U4EZMDWweoh7ajcY9HpPrnURHlhdjQUSa0y70d3qaIqGPYwS17WcirJOpxVwEA&username=prashant_1rai&fname=PRA&lname=R&email=prash8%40gmail.com&pass1=1233&pass2=123 HTTP/1.1" 200 1482 it should have proceeded with return redirect('signin') -
Django Regroup with tables and boostrap collapsible menu
I am trying to mix regroup (within a table) with bootstrapp's collpasible menus. I have a long list of product with categories. I was hoping to list the categories and leave the option for the user to look at the product within them by simply clicking on the category title. Example: How the data looks Category 1 Prod1 Prod2 Prod3 Category 2 Prod1 Prod2 Prod3 How I want it to look on the front end Category 1 Prod1 Prod2 Prod3 Category 2 My logic I thought if I was to input data-target="#category" in the grouper(category - first row) and then wrap the list of products within the category in <div id="category" class="collapse">, this should do the trick. For some reason the table seem to impact the way how regroup works. Any advice on how to user django regroup in a table, using boostrap collapsible menus? (I did find an alternative using JQuery (Django roll-up (collapsible) menu), but ideally would like to find out why this is not working) template {% regroup categories by category_menu as category_menu_list %} {% for category_menu in category_menu_list %} <table class="table"> <tr> <th></th> <th> <a class="button-account btn-block mybtn tx-tfm" data-toggle="collapse" data-target="#category">{{category_menu.grouper}}</a> </th> </tr> <div id="category" class="collapse"> … -
Wagtail permission for different user pass
in my wagtail app, I have a model that I want to only allow certain types of users to view that model. In django I would just inherit UserPassesTestMixin. In wagtail, I will allow it based on a session data. If request.session.dados_usuarios.bu == 'Corporate KO', he will be able to view the page. I'm new to wagtail, is it possible to do this? In django I would do it like this class SomeView(UserPassesTestMixin, TemplateView): ... def test_func(self): return request.session.dados_usuario.bu == 'Corporate KO' My model in wagtail app class IframePage(Page): iframe_url = models.URLField() fabricantes_com_acesso = ParentalManyToManyField( Fabricante, blank=True, verbose_name="Fabricas com Acesso" ) content_panels = Page.content_panels + [ MultiFieldPanel([ FieldPanel('iframe_url'), FieldPanel('fabricantes_com_acesso'), ], heading="Informações Principais"), ] -
Why does the number of bytes in this buffer change from the original size when dealing with images?
So i'm looking at some image resizing code in our code base, and i've noticed that after passing an image through PIL the number of bytes of the image increases by just under 2x. I've gutted most of the code out for the purpose of this demonstration just so I could isolate the case: import io from PIL import Image from django.core.files.base import ContentFile def size_test(content_file: ContentFile): with content_file.open("rb") as file: file_bytes = file.read() print("original size of bytes: %s" % len(file_bytes)) image = Image.open(io.BytesIO(file_bytes), formats=["JPEG"]) with io.BytesIO() as buffer: image.save(buffer, format="JPEG") buffer_bytes = buffer.getvalue() print("new size of bytes: %s" % len(buffer_bytes)) Calling the above with the following code, loading in a JPEG file of known size: with open('10mb.jpg', 'rb') as file: cf = ContentFile(file.read()) utils.size_test(cf) Here is the output: original size of bytes: 10174706 new size of bytes: 19538695 Maybe i'm missing something glaringly obvious, but i'm not sure what makes this image's bytes increase by 9MB in memory, unless it's to do with JPEG compression? Maybe by loading the JPEG into memory we are uncompressing it? Just tried this with a 1.7MB PNG file (changing the relevant formats in the original function): def size_test(content_file: ContentFile): with content_file.open("rb") as file: … -
drf-spectacular: Automatic rendering of schema fields
Is there a setting that will automatically display field data? Used: Django==3.0.14 drf-spectacular==0.24.2 drf-spectacular-sidecar==2022.12.1 drf-spectacular settings SPECTACULAR_SETTINGS = { 'SERVE_INCLUDE_SCHEMA': False, # Permission 'SERVE_AUTHENTICATION': ['rest_framework.authentication.SessionAuthentication'], 'SERVE_PERMISSIONS': ['rest_framework.permissions.IsAuthenticated'], # UI settings 'SWAGGER_UI_DIST': 'SIDECAR', # shorthand to use the sidecar instead 'SWAGGER_UI_FAVICON_HREF': 'SIDECAR', 'REDOC_DIST': 'SIDECAR', 'SCHEMA_PATH_PREFIX_TRIM': True, } In the swagger, the data is reflected in this form: swagger UI Is it possible to automatically expand the information of these fields? Example like here: Correct answer -
(I am a newbie in django) can somebody tell me why is this happening
i have created a model in django :- from django.db import models # Create your models here. class items(models.Model): price = models.IntegerField(), name = models.TextField(max_length=100), category = models.CharField(max_length=100) and when i try to insert a data in admin page it is showing that only category field is created and i am only able to fill data in category how can i fix this also it is showing an extra s in table name items for no reason I am expecting that there should be 3 columns to fill data name, price and category but getting only one -
Use password hash created in GO on Django admin auth doesn't work
I'he created a func in GO to simulate the hash password construction in Django. But when i create the user and try to login in Django Admin, i receive invalid password message and the hash of password was changed in database. The function in go to recreate de pass hash builder is: func PasswordEncode(password string, salt string, iterations int) (string, error) { if strings.TrimSpace(salt) == "" { salt = CreateRandomString(12) } if strings.Contains(salt, "$") { return "", errors.New("salt contains dollar sign ($)") } if iterations <= 0 { iterations = 20000 } hash := pbkdf2.Key([]byte(password), []byte(salt), iterations, sha256.Size, sha256.New) b64Hash := base64.StdEncoding.EncodeToString(hash) return fmt.Sprintf("%s$%d$%s$%s", "pbkdf2_sha256", iterations, salt, b64Hash), nil } func CreateRandomString(len int) string { var container string var str = "abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ1234567890" b := bytes.NewBufferString(str) length := b.Len() bigInt := big.NewInt(int64(length)) for i := 0; i < len; i++ { randomInt, _ := rand.Int(rand.Reader, bigInt) container += string(str[randomInt.Int64()]) } return container } So i have this hash to 'example' password : pbkdf2_sha256$20000$rkOZv4FYyskC$gIn13Rsr229e5AbhgYDTflBWOH9k+d6wEyKPmHryIjI= But when i try to login in Django admin, i receive the invalid password message and the application change de hash to: pbkdf2_sha256$390000$M3ntXZosTvxynIk193G107$40btNBSvVzDKXlS3pbrYfxpZV8lyjsTzG+fW/PL7wCY= Obs.: I'he already tryied to put 22 characteres on salt build func , and set … -
Django-Channels sending messages from external processes with auth
I'm using Django-channels 4 to build a simple chat website where users can join any random channel and start chatting. I have AuthMiddleWare in asgi.py application = ProtocolTypeRouter( { "http": django_asgi_app, "websocket": AllowedHostsOriginValidator( AuthMiddlewareStack(URLRouter(client.routing.websocket_urlpatterns)) ), } ) Now, only logged in users can establish WS connection since its using cookie. BUT now what if I want to send a message to any channel from outside of my django app?. Say that could be from a python script running in same machine using websockets lib. In this case i should have; A session within WS header of the external script which won't expire so the script can use it all day long and hence auth is handled smoothly Identify and allow this external script to send message to any channel. I have seen Channels Custom Authentication where we can add token via the WS header. But i really want to use the existing session auth comes out of the box BUT allowing my special client to connect to the WS with say some sort of special cookie which won't expire (if that method exists). Tried copying cookie from a logged in user's WS header and adding in my script does allow … -
Hot to add buttons (links) to Geonode Menu bar using geonode-project 4.1.x?
I just install Geonode-project 4.1.x and try to follow the official documentation (https://docs.geonode.org/en/4.x/devel/workshops/index.html#customize-the-look-and-feel) to customize the look and add some Links (buttons) to the navigarion bar. So far I have created the templatetags folder and create the "get_menu_json.py" file with the following content from django import template register = template.Library() @register.simple_tag(takes_context=True) def get_base_right_topbar_menu(context): #is_mobile = _is_mobile_device(context) #if is_mobile: # return [] return [ { "type": "link", "href": "/", "label": "Custom 3" }, { "type": "link", "href": "/", "label": "Custom 4" }, ] @register.simple_tag(takes_context=True) def get_base_left_topbar_menu(context): #is_mobile = _is_mobile_device(context) return [ { "type": "link", "href": "/", "label": "Custom 1" }, { "type": "link", "href": "/", "label": "Custom 2" }, ] I have also modified the settings.py to add the templatetags TEMPLATES[0]['OPTIONS']['libraries']={ 'my_template_tag_menu': 'templatetags.get_menu_json', } But this is not working. Geonode is still showing the same buttons (Dataset, Maps, etc). My intention is to add (I am saying add, not override) buttons to the Navigation Bar, so i can access the new views I have created for geonode project. I am using geonode-project 4.1.x. Documentations appears to be outdated. -
What is the best way to sort a Django queryset by group?
I have the following model for events: class EventStatus(models.TextChoices): Open = "Open" Closed = "Closed" Completed = "Completed" Archived = "Archived" class Marketplace(models.Model): Creator = models.ForeignKey(User, on_delete=models.CASCADE) Speaking_Event_Name = models.CharField(max_length=100) Location = models.CharField(max_length=500, null=True) Topic = models.CharField(max_length=40) date = models.DateTimeField(default=timezone.now) Status = models.CharField(max_length=9, choices=EventStatus.choices, default=EventStatus.Open) def __str__(self): return self.Speaking_Event_Name def status(self): return EventStatus.Completed if timezone.now() > self.date else self.Status and I also have the following view function to show the list of events: def view_events(request): event_list = Marketplace.objects.filter(Creator=current_user) content = {'events': event_list} return render(request, 'view_events.html', content) I would like to know how to sort the events list in order by Status, where all the "Open" events are listed first, then "Closed" second, "Completed" third and "Archived" listed last. -
sending data from a "form action" to a views function in django
How are you community, I'm a little confused between my newbies and lack of knowledge, I'm working on a small project in Django and I'm also trying to send data from a form action in the html to another view function but I'm not understanding it well How does this work and on top of that I have to send several data not just one and it confuses me even more, I have the following HTML: {% extends "base.html" %} {% block content %} <main class="container"> <div class="row"> <div class="col-md-10 offset-md-1 mt-5"> <form action="/interface/" method="POST" class="card card-body"> <h1>Interface</h1> <h4>{{ error }}</h4> <select name="dv"> <option selected disabled="True">Select Device</option> {% for device in devicess %} <option>{{ device.id }} - {{ device.name }}</option> {% endfor %} </select> <br> {% csrf_token %} <br> <button type="submit" class="btn btn-primary">Send</button> </form> <br> {% for interface in interfaces %} <section class="card card-body"> <h2>{{interface.Interface}}</h2> {% if interface.Description == "" %} <p class="text-secondary">none description</p> {% else %} <P class="text-secondary">{{interface.Description}}</P> {% endif %} <form action= "{% url 'send_description' %}"method="POST"> {% csrf_token %} <input type="text" name="command" class="form-control" placeholder="Change description"> <br> <button type="submit" class="btn btn-primary align-content-lg-center">Send change</button> </form> <br> {% if interface.Status == "up" %} <p class="text-secondary">Interface State: 🟢 Free</p> {% else %} … -
Rename and resize django images on save
I'm currently trying to resize and rename my images on save The problem is that I would like to resize my images in order to make them square without stretching the images, and then change the name of the image to a random number. Currently I'm doing that inside my model : user = models.OneToOneField(User, on_delete=models.CASCADE) bio = models.TextField(null=True, blank=True) image = models.ImageField(default='/profile_pics/default.jpg', null=True, blank=True, upload_to='profile_pics') def __str__(self): return f'{self.user.username} Profile' def save(self, **kwargs): super().save() new_name = random.randint(1, 236325984) img = Image.open(self.image.path) if img.height > 300 or img.width > 300: output_size = (200, 200) img.thumbnail(output_size) if img.height < 299 or img.width < 299: output_size = (200, 200) img.thumbnail(output_size) img.save(self.image.path) I also tried to put in my save function : new_name = random.randint(1, 236325984) name = f'{new_name}.{img.format.lower()}' os.rename(self.image.path, os.path.join(os.path.dirname(self.image.path), name)) But that's not working and giving me an error : [WinError 32] -
AttributeError when building a custom users app in django
I am making a web tool with few apps in django. one of the apps is called "users" for which I made a custom app. I tried to create a superuser using the following command: python manage.py createsuperuser I was expecting the program to ask me for username, password, email and phone number but I was asked only for: username, password but I got the following error: Traceback (most recent call last): File "manage.py", line 22, in <module> main() File "manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/john/PycharmProjects/digital_products/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/john/PycharmProjects/digital_products/venv/lib/python3.6/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/john/PycharmProjects/digital_products/venv/lib/python3.6/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/john/PycharmProjects/digital_products/venv/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 79, in execute return super().execute(*args, **options) File "/home/john/PycharmProjects/digital_products/venv/lib/python3.6/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/john/PycharmProjects/digital_products/venv/lib/python3.6/site-packages/django/contrib/auth/management/commands/createsuperuser.py", line 189, in handle self.UserModel._default_manager.db_manager(database).create_superuser(**user_data) AttributeError: 'UserManager' object has no attribute 'create_superuser' here is the models.py for the users app: import random from django.db import models from django.utils.translation import ugettext_lazy as _ from django.core import validators from django.utils import timezone from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager, send_mail class UserManager(BaseUserManager): use_in_migrations = True def _create_user(self, username, phone_number, email, password, is_staff, is_superuser, **extra_fields): now = timezone.now() if not username: raise ValueError('The given username …