Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - How can I make a list of the choices I've selected in manytomany?
I'm trying to make a list of the choices I've selected. In this case, the logged in Gestor will select the Funcionarios, and will be able to view the list of selected employees. **models.py ** class Equipe(models.Model): gestor = models.ForeignKey(Gestor, on_delete=models.PROTECT, default="") funcionario = models.ManyToManyField(User) def __str__(self): return self.nome def get_funcionario(self): return "\n".join([p.funcionario for p in self.funcionario.all()]) views.py def listaFuncionario(request): gest = Gestor.objects.get(user_id = request.user.id) equipe = Equipe.objects.filter(gestor_id = gest) equipes = gest.equipe_set.all() func = equipes.funcionario.all() context = {'func':func} return render(request, 'listaFunc.html', context) I try, but it doesn't seem to access the selected Funcionarios table I try but shows me func = equipes.funcionario.all() AttributeError: 'QuerySet' object has no attribute 'funcionario' [02/Nov/2022 15:15:06] "GET /funcionarios HTTP/1.1" 500 65882 n -
How to take elevate or run function as administrator in Django
I have a django project and I want to do operation on hosts file in windows but I am not able to do that because it is read only file so how can I do that any suggestion. So, I am expecting any solution so that I can able to make changes in the host file. I am thinking to make my django project able to run as administrator. -
Django navbar css doesn't make any changes
It's probably not about static files configuration because images work and CSS other than navbar's work, navbar's CSS doesn't make any changes it's just like it's not there, even though when I tried to make a simple h1 and color it (as a test) it worked, it's just the navbar's CSS for some reason that I really can't figure out. base.html: {% load static %} <html lang="en"> <head> <meta charset="UTF-8" /> <meta http-equiv="X-UA-Compatible" content="IE=edge" /> <meta name="viewport" content="width=device-width, initial-scale=1.0" /> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}"> </head> <body> {% block navbar %} {% include 'parts/navbar.html' %} {% endblock navbar %} {% block content %} {% endblock content %} </body> </html> homepage.html: {% extends 'base.html' %} {% load static %} {% block content %} {% endblock content %} navbar.html: <head> <link rel="stylesheet" type="text/css" href="{% static 'css/main.css' %}" /> </head> <div class="navContainer"> <div class="navbar"> <img src="{% static 'images/navLogo.png' %}" class="logo" /> <nav> <ul> <li><a href="">Home</a></li> <li><a href="">About</a></li> <li><a href="">Projects</a></li> </ul> </nav> </div> </div> static configuration in settings.py: STATIC_ROOT = path.join(BASE_DIR, 'static') STATIC_URL = 'static/' STATICFILES_DIRS = [ path.join(BASE_DIR, 'staticfiles') ] app's urls.py: from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ … -
suddenly datetime indexing field selection became longer
I have partition table with datetime field indexing In django orm i have 2 variant of requests First variant MyModel.objects.filter(my_datetime_field__gt=date(2022, 1 , 1)) This request is being made 3.5-5 seconds Second variant MyModel.objects.filter(my_datetime_field__date__gt=date(2022, 1 , 1)) This request is being made 0.05 seconds Question Previously, requests were completed in the same time. What could have happened? Some information django: 2.0 postgres: 12.3 index_type: btree I try next VACUUM (VERBOSE, ANALYZE) my_table REINDEX INDEX my_index -
How to find history of commands run on mysql
I sort of have a heart attack of a problem. I had a non-root utility user in mysql that used to be able to see all the databases, tables, etc. on the mysql instance. The user was able to insert records, delete records, create tables, etc. too. This user is used by scripts to edit records, or view the data as someone who's not root via phpmyadmin. I don't know how Django fits into this or if it was even the cause but a contractor needed access to the db to work on their project we asked them to work on. They said they were using Django and needed to create some auth tables in the database (auth_group, auth_user, auth_user_groups, etc.) However, after they added their tables for Django, that user can't see anything except the "information_schema" database. Luckily, I checked using the root user in mysql and can see the databases but somehow, the viewing privileges are removed from the non-root user. I want to see what commands the contractor ran to get us into this situation to tell them not to do this again. I was going to check the .mysql_history file in the unix root user directory … -
I get a 404 error when passing as a parameter to the path an int that is a foreign key
This is the url i am trying: http://localhost:8000/blog/categoria/1/ The foreign key is categoria_id that comes from relationship many to many of Post and Categoria. I am using Sqlite3. This file is the models.py from django.db import models from django.contrib.auth.models import User class Categoria(models.Model): nombre=models.CharField(max_length=50) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: verbose_name='categoria' verbose_name_plural='categorias' def __str__(self): return self.nombre class Post(models.Model): titulo=models.CharField(max_length=50) contenido=models.CharField(max_length=50) imagen=models.ImageField(upload_to='blog', null=True, blank=True) autor=models.ForeignKey(User, on_delete=models.CASCADE) categorias=models.ManyToManyField(Categoria) created=models.DateTimeField(auto_now_add=True) updated=models.DateTimeField(auto_now_add=True) class Meta: verbose_name='post' verbose_name_plural='posts' def __str__(self): return self.titulo This file is the views.py: from django.shortcuts import render from blog.models import Post, Categoria def blog(request): posts=Post.objects.all() return render(request, "blog/blog.html",{"posts":posts}) def categoria(request, categoria_id): categoria=Categoria.objects.get(id=categoria_id) posts=Post.objects.filter(categorias=categoria) return render(request, "blog/categoria.html",{'categoria': categoria, "posts":posts }) This file is the urls.py from django.urls import path from . import views from django.conf import settings from django.conf.urls.static import static urlpatterns = [ path('', views.blog, name='Blog'), path('categoria/<int:categoria_id>/', views.categoria, name="categoria") ] -
model inheritance authentication on several children
I would like to have opinions on how to proceed to set up my models. I have a father entity which has two sons simpleman and superman. Both can authenticate but simpleman does not have access to all pages and other limitations. To highlight simpleman I had thought of adding a method that returns true I would like to know do I have to create a Father model with its attributes and its primary key (regNumber: CharField) then with this children I would put this primary key in foreign key ? In the code i think to do this: class Superman(AbstractBaseUser): #regNumber = models.CharField(..., primary_key=True) ... # other property objects = customManagerSuper() # where user.is_admin=True and user.is_superuser=True class Simpleman(AbstractBaseUser): #regNumber = models.CharField(..., primary_key=True) ... # other property objects = customManagerSimple() # where user.is_admin=False and user.is_superuser=False def heIsSimple(self): return True How will authentication work? How could I get him to look in the right table? To limit access to certain page for the simpleman I had thought of setting up a decoration like this in my views.py @user_passes_test(lambda user: u.heIsSimple()) -
how to display defalt value radio button in django form
My form allows the user to select between two roles. I struggle to understand why I cannot display it in the template. The model role default value, and the form role initial values, are both set to 'regular_user'. The models ae migated and the om values ae displayed as needed, but without the deault value. Any input on what I'm doing wrong would be highly appreciated. models.py: ROLES = (('regular_user', 'Regular_user'), ('collaborator', 'Collaborator')) class CustomUser(AbstractUser): display_name = models.CharField(verbose_name=("Display name"), max_length=30, help_text=("Will be shown e.g. when commenting")) ... role = models.CharField(choices = ROLES, max_length = 50, default = 'regular_user', help_text =("Click below Collaborator, if you wish to join us")) ... class Meta: ordering = ['last_name'] def get_absolute_url(self): return reverse('account_profile') def __str__(self): return f"{self.username}: {self.first_name} {self.last_name}" Forms.py: class SignupForm(forms.Form): first_name = forms.CharField(max_length=30, label=_("First name")) ... role = forms.ChoiceField(choices=ROLES, widget=forms.RadioSelect(), label="Role", required=True, help_text=_("Click below 'Collaborator', if you wish to join us")) ... def signup(self, request, user, **kwargs): ... user.role = self.cleaned_data['role'] ... user.save() If I render it with all other form fields like: {% with "form-control input-field-"|add:field.name as field_class %} {% render_field field class=field_class %}{% endwith %} It renders without radio widget that cannot be checked. When I render the role field separately, … -
Django passing references to request/user django.contrib.auth.models
In this example Django code, how is request able to reference user? And user able to reference profile? p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) -
problemas con heroku
tengo un problema con heroku, ya se desplego la pagina pero al momento deentrar solo dice internal server error. ayuda, tengo 2 meses desplegando esta pagina https://watchalo.herokuapp.com/ intente desplegarla dos veces pero no pude hacer nada -
is there a way to diable django abstract base user is_staff and is_superuser fields
Is there a way to disable is_staff and is_superuser abstractbaseuser fields and instead use one user_role choice field to handle all permissions. -
Django and Celery testing issue
I use Celery in my Django (DRF) app to perform async tasks. Everything works fine, except the testing. The problem seems to be related to the APITestCase that it is executed before the Celery APITransactionTestCase deleting the database. Here a representative code: test_drf_views.py class DRFTestCase(APITestCase): @classmethod def setUpTestData(cls): ''' Init database ''' from myapp.init import init_data # this loads the database def setUp(self): self.login = reverse('login') # ... just a setup def test_foo(self): # ... just a test that works fine test_celery_task.py class CeleryTaskTestCase(APITransactionTestCase): @classmethod def setUpClass(cls): super().setUpClass() app.loader.import_module('celery.contrib.testing.tasks') cls.celery_worker = start_worker(app) cls.celery_worker.__enter__() @classmethod def tearDownClass(cls): super().tearDownClass() cls.celery_worker.__exit__(None, None, None) def setUp(self): super().setUp() self.login = reverse('login') # here I call the DB and it FAIL The error I got when running pytest is: "matching query does not exists", because when the testing procedure reaches the test_celery_task.py the DB seems to be deleted. I also tried to reload the DB in the celery test, but nothing changes. Does anybody have an idea how to approach and solve the issue? -
How instanciate table in createsuperuser
I have two tables Employee and Sector, the employee table has for foreign key the sector code (sectorCode) property of the Sector table. The Employee table inherits from the AbstractBaseUser class. I would like to create a superuser with the command python manage.py createsuperuser. I get an error: ValueError: Cannot assign "'Code1'": "Employee.sectorCode" must be a "Sector" instance. (I added in the Sector table a row NameSector1; Code1) I input these values: λ python manage.py createsuperuser registrationNumber: 001 Name: TestN1 FirstName: TestFN1 sectorCode: Code1 Password: ... Error ... How can I instantiate sector class in dialog ? from django.db import models from django.contrib.auth.models import AbstractBaseUser, BaseUserManager class MyUserManager(BaseUserManager): def create_user(self, registrationNumber, firstName, name, sectorCode, password=None): if not firstName: raise ValueError("firstName required") if not name: raise ValueError("name required") if not registrationNumber: raise ValueError("registrationNumber required") if not sectorCode: raise ValueError("sectorCode required") user=self.model(firstName = firstName, name = name, registrationNumber = registrationNumber, sectorCode = sectorCode) user.set_password(password); user.save() return user def create_superuser(self, firstName, name, registrationNumber, sectorCode, password=None): user=self.create_user(firstName = firstName, name = name, registrationNumber = registrationNumber, sectorCode = sectorCode, password = password) user.is_admin=True; user.is_superuser=True user.save() return user class Sector(models.Model): nameSector = models.CharField(verbose_name = "nameSector", max_length=50) sectorCode = models.CharField(verbose_name = "sectorCode", max_length=3, primary_key=True) class Meta: db_table … -
Why am I getting this Django custom command error: 'datetime.timezone' has no attribute 'now'
Why am I getting the error "'datetime.timezone' has no attribute 'now'" when trying to run this custom command in Django that deletes guest accounts older than 30 days? It works elsewhere in views.py where I have imported it the same way. Do I have to import it differently since the command is in a different folder? (management/commands/) from django.core.management.base import BaseCommand from datetime import timezone, timedelta from gridsquid.models import User, Tile DEFAULT_TILE_IMG_NAME = "defaultsquid.svg" MAX_GUEST_ACCOUNT_DAYS = 30 class Command(BaseCommand): def handle(self, *args, **options): """ Deletes all guest user accounts and their media if older than MAX_GUEST_ACCOUNT_DAYS """ # Get all guest accounts created before the limit expired_guests_count = User.objects.filter(guest=True).filter(date_joined__lt=timezone.now()-timedelta(days=MAX_GUEST_ACCOUNT_DAYS)).count() expired_guests = User.objects.filter(guest=True).filter(date_joined__lt=timezone.now()-timedelta(days=MAX_GUEST_ACCOUNT_DAYS)) for guest in expired_guests: tiles = Tile.objects.select_related("user").filter(user=guest).all() for tile in tiles: # Delete image if not default image if DEFAULT_TILE_IMG_NAME not in tile.image.url: tile.image.delete() # Delete audio file if there is one if tile.audio is not None: tile.audio.delete() # Delete guest account guest.delete() -
Django: How do you use an image in your template and let your views.py know it was pressed like a button?
I want to show an image that the user can click on that will act like a button and return the data to my views.py. For example, <input type="submit" value="Add Selected Other Service to Included Service" class="button" name="Add Other Service"/> will create a very long button which I can "grab" in my views.py with: add_other_service = request.POST.get('Add Other Service') I can then test add_other_service and term if that was the button pressed. Hence, I can have multiple buttons on the page and determine which one as pressed. I know I can use the tag with the type="image" to click on the image, but I cannot find a way to get name of the button in the views.py. -
Django - How to encapsulate multiple values in a JSON Response?
I would like to know how I can put the following JsonResponse: return JsonResponse({ 'stuff_a': stuff_a_serializer.data, 'stuff_b': stuff_b_serializer.data, 'stuff_c': stuff_c_serializer.data, }, safe=False) to something like this: return JsonResponse({ 'stuff_a': stuff_a_serializer.data, { 'stuff_b': stuff_b_serializer.data, 'stuff_c': stuff_c_serializer.data, } }, safe=False) Using the Django REST Framework. I simply want to encapsulate the result of two serializes inside the result of another to later unpack them properly at my Angular Frontend. How can I do this? Thanks in advance and kind regards :) -
Django Integration with React router dom
I am trying to serve web static files on my backend Django framework. I am using react with router Dom on my frontend and Django with rest framework. The problem now is that I am able to serve the page with route '' on Django but for other routes defined in frontend like posts are not able to be served on Django. Frontend react: App.js import React from 'react'; //import { Switch, Redirect } from 'react-router-dom'; //import { Navigate } from 'react-router-dom'; import "../stylesheets/templatemo-style.css"; // importing components from react-router-dom package // import { // BrowserRouter as Router, // Routes, // Route, // } from "react-router-dom"; import { HashRouter as Router, Route, Routes } from "react-router-dom"; // import Home component import Home from "./Home.js"; import User from "./User.js"; // import Post component import Comment from "./Comment.js"; import Post from "./Post.js"; import Account from "./Account.js"; //import User from "./components/User"; class App extends React.Component { render(){ return ( <> <div className = "App"> {/* This is the alias of BrowserRouter i.e. Router */} <Router> <Routes> <Route exaxt path = '' element={<Account/>} /> <Route path = 'posts'element={Post}/> </Routes> </Router> </div> </> ); } } export default App; And App is rendered in index.js import … -
Want to add '?id= ' in urls.py
I have urls.py in my project. I want to create URL like localhost:8000/v1/user?id=1 Can anyone help me how I can create the above URL. Thanks -
React-relay vs Apollo client for a react native app with Python-Django graphql backend
I am trying to build an app with react-native front end and django-graphene (graphql api) on the backend. Need some help to decide on pros/cons of using Apollo client vs React-relay for integrating the front end and backend which can be more efficient and scalable. Or if there are some other alternatives technology/libs which could be a great fit for loading data on the front end with graphql api on backend server. Any pointers on some great tutorials for the same would be very helpful. -
In Django Models, At Admin Area, how to auto assign the 'requesting' user to one of the foreign key User relation field
In the following mode in my project, I want to assign the author variable of class upon the creation of model, on user end this could be done via request.user but as the class can be only instantiated from the admin area, this doesn't work. class Blog(models.Model): title = models.CharField(max_length=300) content = RichTextField() author = models.ForeignKey(User, related_name="Author", auto_created= True, on_delete= models.CASCADE) date = models.DateTimeField(auto_now_add= True) -
Why and how is Django filter-by BooleanField query translated to SQL WHERE or WHERE NOT rather than 1/0?
I noticed that a query that used to be fast in legacy version of Django is now much slower in 4.0.8. There is a fairly large table with a FK 'marker' and a boolean 'flag' that has an index attached. The following queries could reasonably return tens of thousands of rows. In my codebase, there is a query like MyModel.objects.filter(marker_id=123, flag=False).count() In Django Debug Toolbar (and also in shell when I examine str(qs.query)) it now resolves to the following SQL syntax: SELECT ••• FROM `myapp_mymodel` WHERE (`myapp_mymodel`.`marker_id` = 123 AND NOT `myapp_mymodel`.`flag`) In extreme cases, this query runs for 20s or so. Meanwhile, in legacy Django version (1.11+) the same query becomes the following SQL: SELECT ••• FROM `myapp_mymodel` WHERE (`myapp_mymodel`.`marker_id` = 123 AND `myapp_mymodel`.`flag` = 0) This works, since the table schema contains 'flag' as a TINYINT(1), but most importantly, it works much faster - returning in under a second. Why is the difference in ORM-to-SQL translation, and where can I find the code responsible (I have checked db.backends.mysql to no avail, or failed to recognize the culprit)? Is there a way to hint to Django that I'd much prefer the equals-zero behaviour? The only workaround I see so … -
How to send binary as file using requests.request POST?
I have a field in db that contains binary (So i don't have a file, i have only it's representation as bytes). I have a server that is waiting file to be uploaded, so the question is how can i upload this bytes as file? How do i convert these bytes to file to send it to server? Example of what i have -> file = b'\x89PNG\r\n\x1a\n\x00\x00\x00\rIHDR\x00\x00\x05\xd8\x00\x00\x018\x08\x06\x00\x00\x00HD\x91\x99\x00\x00\x0cmiCCPICC' Field in django that i need to be sent file = models.FileField(default='') I'm trying to do it like this -> tmp_file = open('tmp.pdf', 'wb') tmp_file.write(file) and then response = requests.request( "POST", url, headers=headers, data=payload, files={ 'file': ( open('tmp.pdf', 'rb'), ) } ) but i got error raise ValueError("Data must not be a string.") ValueError: Data must not be a string. Headers -> headers = { 'Authorization': 'Token ' + config['token'], 'Content-Type': 'application/json' } -
run automatically Nginx and Python script
I have a Django application that's lunched in Windows server 2016. using Nginx so my problem is I should start the application manually every time the server is rebooted. First I should open CMD and start Nginx.exe then I must run a python script in second CMD as python runserver.py -
redirecting to homepage after user submits a blog post?
I'm very new to using Django and coding in general. So I have figured out how to make the form submit to my database but now when it submits, it just brings you to the blank blog_post view and I'm not understanding how to redirect correctly. here is the views.py: from django.shortcuts import render, redirect from .models import post from django.views import generic, View from django.views.decorators.http import require_GET from django.http import HttpResponse, HttpResponseRedirect from .forms import PostForm # Views for post list class postslist(generic.ListView): model = post queryset = post.objects.filter(status=1).order_by('-created_on') template_name = 'home.html' paginate_by = 4 # view for individual post class postdetail(generic.DetailView): model = post template_name = "post.html" def blog_post(request): form = PostForm(request.POST or None) if request.method == "POST": if form.is_valid(): form.instance.user = request.user form.save() return redirect("blog:success") context = {'form': form, } return render(request, "create_post.html", context) def success(request): return HttpResponseRedirect("home.html") urls.py: from . import views from django.urls import path, include from .views import * urlpatterns = [ # home path('', views.postslist.as_view(), name='home'), # add post path('blog_post/', views.blog_post, name='blog_post'), # success for blog post path('success/', views.success, name='success'), # posts path('<slug:slug>/', views.postdetail.as_view(), name='post_detail'), ] I have tried a few variations of httpresponseredirect and redirect but i just cant wrap my head … -
After setting up ssl I cannot access my site django&apache
I created a demo for my domain www.example.com which only returns the index as you can see below. def index(request): return HttpResponse("This is a demo") urlpatterns = [ path('admin/', admin.site.urls), path("",index), ] I was able to access my site with domain name (I made the "A" dns record in godaddy site) and this was the <VirtualHost *:80> <VirtualHost *:80> ServerName loopingaround.com ServerAlias www.loopingaround.com ErrorLog /django-pro/site/logs/error.log CustomLog /django-pro/site/logs/access.log combine alias /static /django-pro/site/public/static <Directory /django-pro/site/public/static> Require all granted </Directory> alias /media /django-pro/site/public/media <Directory /django-pro/site/public/media> Require all granted </Directory> <Directory /django-pro/src/tutorial> Require all granted </Directory> WSGIDaemonProcess tutorial python-home=/django-pro/venv python-path=/django-pro/src/ WSGIProcessGroup tutorial WSGIScriptAlias / /django-pro/src/tutorial/wsgi.py </VirtualHost> then I used "ssl for free" for creating a ssl certificate for my site and set the files they provided. <VirtualHost *:80> ServerName loopingaround.com ServerAlias www.loopingaround.com Redirect / https://loopingaround.com </VirtualHost> <VirtualHost *:443> ServerName loopingaround.com ServerAlias www.loopingaround.com ErrorLog /django-pro/site/logs/error.log CustomLog /django-pro/site/logs/access.log combine SSLEngine on SSLCertificateFile /etc/ssl/certificate.crt SSLCertificateKeyFile /etc/ssl/private/private.key SSLCertificateChainFile /etc/ssl/ca_bundle.crt alias /static /django-pro/site/public/static <Directory /django-pro/site/public/static> Require all granted </Directory> alias /media /django-pro/site/public/media <Directory /django-pro/site/public/media> Require all granted </Directory> <Directory /django-pro/src/tutorial> Require all granted </Directory> WSGIDaemonProcess tutorial python-home=/django-pro/venv python-path=/django-pro/src/ WSGIProcessGroup tutorial WSGIScriptAlias / /django-pro/src/tutorial/wsgi.py </VirtualHost> now even if I revert the changes I made, I cannot access my site as …