Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and Oracle Database
I'd like to connect an Oracle 8i database to Django. I tried using cx-Oracle, but the terminal output is 'cx-Oracle does not support this database'. If anyone know this please help. I tried to connect with cx-Oracle. -
Django Cache - using in a class based view with an S3 presigned url
I have added database caching to my class based view like so: @method_decorator(cache_page(30), name='dispatch') class MyListView(ListView): model = MyModel MyModel is a pretty simple model with some varchar fields, along with a foreign key relationship to an image model. class MyModel(index.Indexed, models.Model): sku = models.CharField(max_length=10, unique=True) ... more fields class MyImageModel(models.Model): def get_sku(instance, filename): return f"{instance.parent.sku}/{filename}" parent = models.ForeignKey(MyModel, related_name='images', on_delete=models.CASCADE) image = models.ImageField(upload_to=get_sku) I am using django-s3-storage for my storage backend. This will make a call to get_presigned_url (which uses boto3) when I ask for the image's url in a template: {% for model in object_list %} <p>{{model.sku}}</p> <img src="{{model.images.0.image.url}}"> {% endfor %} I see the view's cache entry show up in my database cache table, but the presigned url that is generated is still unique after reloading the page. Why is this presigned url not cached along with the rest of the generated class based view? -
Email verification not working with deployed django app on heroku
I've deployed a django website with Heroku. When a user creates an account in the app, a validation email is supposed to be sent. Do do that, I'm using smtp from gmail, and in my account settings, I've activated "less secure app access". This works perfectly fine on my local machine, but when using the deployed app, I can't get the email to be sent. The first time, I got a security warning from google saying someone connected to my account. I said it was me and tried again. I didn't get any other security warning but it seems the app is still unable to send emails. Please, let me know if you have any idea what the issue might be. Thanks. -
Why isnt my django heroku admin not working
I created a heroku superuser using the "heroku run python manage.py createsuperuser" command but when i try to log in to my admin pannel in heroku it tells me i am putting wrong login credentials even though they are correct. -
CSS isn't in my website but I wrote in the folder
I created a website (on local host for now), so I linked html with css and my css is ready. I wrote everything, but then the css doesnt show on the website I opened the inspect element > sources > style.css and I found the css empty, but in vs code it has 1200 lines in google its 0 (I saved the folder after writing the css) heres the html code that I used to link html with css <!DOCTYPE html> {% load static %} <html lang="en"> <head> <meta charset="utf-8"> <meta content="width=device-width, initial-scale=1.0" name="viewport"> <link href="{% static 'css/style.css' %}" rel="stylesheet"> -
java script to enable and disable a button based on changes in form
i am using a javscript to enable a button based on the changes in the form field in django python using bootstrap.below is the script $("#employee_name, #employee_name2").on("keyup",function() { $(".btn-action").prop("disabled",false); if( ($("#employee_name").val()) == ($("#employee_name2").val())) { $(".btn-action").prop("disabled",true); } }); also the below code in html to initially disable button <button type="submit" class="btn btn-primary mt-3 btn-action" disabled>Save</button> but the button stays disabled even after changing values in the field.any help would be appreciated -
Even though password is incorrect the user is validated and passes the authentication check in django
I am using landsatxplore API to download satellite images and now I am creating a web application to do that using the same API in Django. In simple python script. from landsatxplore.api import API username = 'username' password = 'password' api = API(username, password) if the username and password are correct it creates an API instance/Key and if the username and password is incorrect it throws an exception: landsatxplore.errors.USGSAuthenticationError: AUTH_INVALID: User credential verification failed. I am trying the same logic in Django but even if I type the wrong username and password it passes the authentication and sends me to the next page homepage.html which should only be accessible if the username and password is correct. views.py from landsatxplore import errors from django.shortcuts import render,redirect from django.contrib import messages from landsatxplore.api import API # Create your views here. def index(request): username = request.POST.get('username') password = request.POST.get('password') if username == None or password == None: messages.info(request,"please Enter the username and password") else: try: # Initialize a new API instance and get an access key api = API(username, password) except errors.USGSUnauthorizedError: messages.info(request,"Username and password is wrong") else: return render(request,"homepage.html") return render(request, 'index.html') def homepage(request): return render(request,'homepage.html') HTML: {% for message in messages … -
Install Django on windows
Pretty Printed 81 k suscribers In this video I will show you how to install Django on Windows and get started with a simple "Hello World" example. -
How to Compare ManyToManyField to another ManyToManyField
I have a model of Partner class Partner(models.Model): name = models.CharField(max_length=100, blank=True, null=True) group = models.OneToOneField( Group, on_delete=models.DO_NOTHING, blank=True, null=True) def __str__(self): return self.name I have 2 other models one is CustomUser and other is Quote class CustomUser(AbstractUser): #... name = models.CharField(max_length=160, null=True, blank=True) partner = models.ManyToManyField( Partner, blank=True) class Quote(models.Model): #... visibility = models.CharField(max_length=10) partner = models.ManyToManyField( Partner, blank=True) Both have a partner field related with ManyToManyField to Partner Model Now I want to compare them in the views like: partner field can have multiple partners like partner1, partner2, partner3 how to to find the partners matching to each other inside the Quote and CustomUser model Lets say, One of the Quote object have set of [partner1 and partner6] in the ManyToManyField and I only want to have access to that quote to users who also have partner1 and partner6 in their partner ManyToManyField set. So how can I filter and compare them ? I also read the docs but didn't able to reproduce the solution. help would be appreciated. -
I want to get users by their role and loop through them and send mail to them django
Pls I want to get all users by their specific role, loop through them, and send mail to them using office 365 send_mail( 'Subject here', 'Here is the message.', 'stack@gmail.com', ['mail@gmail.com'], fail_silently=False, ) -
Django Admin Search Results Doesn't List All Results
The Django Admin change list isn't displaying all of the search results. It says that there's 14 results but it only lists 5 of them. Sometimes it says how many results there are, but it doesn't even show any of them at all. Any ideas what could be going on here? -
Django - [Errno 13] Permission denied: '/audio'
I am facing this error with my django server in production mode. While developping, everything was working fine. Here is the Model concerned : class Music(models.Model): name = models.CharField(max_length=100) cover = models.TextField() prix_son = models.FloatField(default=0) stripe_audio_price_id = models.CharField(max_length=100, default='none') lien_deezer = models.CharField(max_length=500) lien_spotify = models.CharField(max_length=500) audio_file = models.FileField(blank=True, upload_to='audio') def __str__(self): return(self.name) Here is the traceback : Environment: Request Method: POST Request URL: https://www.algorabsdream.fr/admin/test_django/sortie/1/change/ Django Version: 4.0.3 Python Version: 3.8.10 Installed Applications: ['django.contrib.admin', 'django.contrib.auth' , 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'test_django'] Installed Middleware: ['django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware'] Traceback (most recent call last): File "/test_django/algorab_env/lib/python3.8/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/test_django/algorab_env/lib/python3.8/site-packages/django/core/handlers/base.py", line 197, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/test_django/algorab_env/lib/python3.8/site-packages/django/contrib/admin/options.py", line 683, in wrapper return self.admin_site.admin_view(view)(*args, **kwargs) File "/test_django/algorab_env/lib/python3.8/site-packages/django/utils/decorators.py", line 133, in _wrapped_view response = view_func(request, *args, **kwargs) File "/test_django/algorab_env/lib/python3.8/site-packages/django/views/decorators/cache.py", line 62, in _wrapped_view_func response = view_func(request, *args, **kwargs) File "/test_django/algorab_env/lib/python3.8/site-packages/django/contrib/admin/sites.py", line 242, in inner return view(request, *args, **kwargs) File "/test_django/algorab_env/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1888, in change_view return self.changeform_view(request, object_id, form_url, extra_context) File "/test_django/algorab_env/lib/python3.8/site-packages/django/utils/decorators.py", line 46, in _wrapper return bound_method(*args, **kwargs) File "/test_django/algorab_env/lib/python3.8/site-packages/django/utils/decorators.py", line 133, in _wrapped_view response = view_func(request, *args, **kwargs) File "/test_django/algorab_env/lib/python3.8/site-packages/django/contrib/admin/options.py", line 1745, in changeform_view return self._changeform_view(request, object_id, form_url, extra_context) File "/test_django/algorab_env/lib/python3.8/site-packages/django/contrib/admin/options.py", line … -
how to count the number of users with a certain group in django?
num_moder = django.contrib.auth.models.Group.objects.count() this command count only the number of group dont count members of this group :D the name of the Group - Librerian. How to count the number of this Group. -
How to use javascript variable in django if statement (template)?
I'm trying to update my html element with django if statement: element.innerHTML= `{% if person.name == ${value} %} something {% endif %}` but I receive an error: TemplateSyntaxError at / Could not parse the remainder: '${value}' from '${value}' I also tried: `{% if person.name == ${value} %} something {% endif %}` But the statement doesn't work properly. Is there anything I can do to combine javascript with Django variables? -
Django heroku application wont run
i was deploying a django project this is my prjoect github https://github.com/EpicGL/CM1 im getting this[ 2022-03-25T19:04:21.335972+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=my-cm1.herokuapp.com request_id=8c9ac21d-96a7-4563-80df-8e2c60bd98ea fwd="202.134.14.132" dyno= connect= service= status=503 bytes= protocol=https. 2022-03-25T19:04:22.514399+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=my-cm1.herokuapp.com request_id=bcd22f6d-8ddb-43b0-8a66-5e5c79f0d2d7 fwd="202.134.14.132" dyno= connect= service= status=503 bytes= protocol=https error can anyone please help hi there, i was deploying a django project this is my prjoect github https://github.com/EpicGL/CM1 -
Django - Can't get the specific primary key (id) for an object in a list of objects
I am trying to get the specific pk of the selected object when the user accepts a delivery. My problem is that I'm getting only the first object's pk in the list every time. I want to get the pk of the selected object. views: @login_required(login_url="/signin/?next=/driver/") def deliveries_available_page(request): deliveries = Delivery.objects.filter( status_of_delivery__in=[Delivery.DELIVERY_POSTED] ) #When driver accept delivery then status of delivery changes to delivering if request.method == 'POST': delivery = get_object_or_404(Delivery, pk=request.POST.get('receipt_number')) if delivery: delivery.status_of_delivery = Delivery.DELIVERY_DELIVERING delivery.driver = request.user.driver messages.success(request, 'Delivery Accepted') delivery.save() return redirect(reverse('driver:deliveries_available')) return render(request, 'driver/deliveries_available.html', { "GOOGLE_API_MAP": settings.GOOGLE_API_MAP, "del": deliveries }) HTML: <div class="d-flex flex-column h-100" style="padding-bottom: 50px"> <div id="map"></div> {% if del %} {% for d in del %} <div class="card" id="delivery-popup"> <div class="card-body p-2"> <div class="details"> <div class="p-2"> <strong id="address"></strong> <div> <strong id="show-info"></strong> </div> <div> <strong id="show-distance"></strong> <strong id="show-duration"></strong> </div> <div> <strong id="show-price"></strong> <strong id="show-id"></strong> </div> <div> <form method="POST"> {% csrf_token %} <button type="submit" class="btn btn-primary" name="accept">Accept</button> <input type="hidden" value="{{ d.receipt_number }}" name="receipt_number"> </form> </div> {% if messages %} {% for m in messages %} {% if m.tags %} <script>alert("{{ m }}")</script> {% endif %} {% endfor %} {% endif %} </div> </div> </div> </div> {% endfor %} {% endif %} I need the … -
Query across all schemas on identical table on Postgres
I'm using postgres and I have multiple schemas with identical tables where they are dynamically added the application code. foo, bar, baz, abc, xyz, ..., I want to be able to query all the schemas as if they are a single table !!! I don't want to query all the schemas one by one and combine the results I want to "combine"(not sure if this would be considered a huge join) the tables across schemas and then run the query. For example, an order by query shouldn't be like 1. schema_A.result_1 2. schema_A.result_3 3. schema_B.result_2 4. schema_B.result 4 but instead it should be 1. schema_A.result_1 2. schema_B.result_2 3. schema_A.result_3 4. schema_B.result 4 If possible I don't want to generate a query that goes like SELECT schema_A.table_X.field_1, schema_B.table_X.field_1 FROM schema_A.table_X, schema_B.table_X But I want that to be taken care of in postgresql, in the database. Generating a query with all the schemas(namespaces) appended can make my queries HUGE with ~50 field and ~50 schemas. Since these tables are generated I also cannot inherit them from some global table and query that instead. I'd also like to know if this is not really possible in a reasonable speed. EXTRA: I'm using django … -
Emitting a subquery in the FROM in Django
I am trying to produce SQL like so: SELECT ... FROM bigtable INNER JOIN ( SELECT DISTINCT key FROM smalltable WHERE smalltable.x = 'user_input' ) subq ON bigtable.key = subq.key I have tried a handful of stuff with Django, and so far I've got: subq = Smalltable.objects.filter(x='%s').values("key").distinct("key") queryset = Bigtable.objects.extra( tables=[f"({subq.query}) subq"], where=["bigtable.key = smalltable.key"], params=["user_input"], ) The goal here is a cross join on bigtable and the DISTINCT smalltable. The ON clause is then replaced by a condition in the WHERE. In other words, a valid old-school inner join. And Django ALMOST has it. It is producing SQL like so: SELECT ... FROM bigtable, "(SELECT DISTINCT ...) subq" WHERE (bigtable.key = subq.key) Note the double quotes - Django expects a table literal only there and is escaping it as so. How can I get this query done, in either this way or another way? It is important for me that it's an actual join vs IN or EXISTS for query planning purposes. -
Django 4 - depending on choices , how show different fields using admin
Anyone please tell me depending on choices , show to fields using admin === Models.py from django.db import models class Project(models.Model): A = 'A' B = 'B' PROJECT_TYPE_CHOICES = ( (A, 'Plan Type A'), (B, 'Plan Type B'), ) project_type = models.CharField(max_length=100, choices=PROJECT_TYPE_CHOICES) name = models.CharField(max_length=500) business = models.CharField(max_length=500) === admin.py from django.contrib import admin from .models import Project admin.site.register(Project, ProjectAdmin) i want if i choices A show fields name if i choices B show fields business Thanks -
CustomAccounManager.create_user() missing 1 required positional argument: 'email'
I am trying creating a custom user model in django - which I am using as a backend. On django admin I can create users without issue. My problem arises when I try to register a new account via postman. In postman I have the email field filled out in the body, yet I still get the error missing 1 required positional argument: 'email'. models.py from django.db import models from django.contrib.auth.models import AbstractBaseUser, PermissionsMixin, BaseUserManager from django.utils.translation import gettext_lazy as _ class CustomAccounManager(BaseUserManager): def create_superuser(self, email, username, password, **other_fields): other_fields.setdefault('is_staff', True) other_fields.setdefault('is_superuser', True) other_fields.setdefault('is_active', True) return self.create_user(self, email, username, password, **other_fields) def create_user(self, email, username, password, **other_fields): if not email: raise ValueError(_('You must provide an email address')) email = self.normalize_email(email) user = self.model(email=email, username=username, **other_fields) user.set_password(password) user.save() return user class User(AbstractBaseUser, PermissionsMixin): email = models.EmailField(_('email address'), unique=True) username = models.CharField(max_length=150, unique = True) is_student = models.BooleanField(default=False) is_teacher = models.BooleanField(default=False) is_staff = models.BooleanField(default=False) is_superuser = models.BooleanField(default=False) is_active = models.BooleanField(default=True) objects = CustomAccounManager() USERNAME_FIELD = 'email' REQUIRED_FIELDS = ['username'] def __str__(self): return self.username serializers.py from rest_framework import serializers from rest_framework.authtoken.models import Token from .models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id', 'username', 'password') extra_kwargs = {'password': {'write_only': … -
Use python eval() in method calls
I have used eval() before but I'm trying to use it in a method call and it's not working. if level == 'info': logging.info( f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}" ) elif level == 'warning': logging.warning( f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}" ) elif level == 'error': logging.error( f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}" ) elif level == 'critical': logging.critical( f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}" ) How do I make less code by using something like: level == 'info': logging.eval(level)( f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}" ) I really thought this last one was gonna work: level = 'info' log = f"{logging}.{eval(level)}" eval(log)(f"Date:{datetime.now().strftime('%Y-%m-%d %H:%M:%S')}, Ran with args: {args}, and kwargs: {kwargs}") Anyone knows a way to make this work? -
How to create re-send verification code system in Django?
I have a problem and that is whenever a user creates her/his account and doesn't enter her/his code(it means the code is expired) the user can't get code again because the account can be created once. I want to know how can I change this code to work in a way that the user can get the verification code again and again. serilizer.py: class RegisterationSerializer(serializers.ModelSerializer): password = serializers.CharField(write_only=True, required=True, help_text=_("Enter a valid password")) repeated_password = serializers.CharField(write_only=True, required=True, help_text=_("Enter your password again")) class Meta: model = User fields = ["email", "username", "name", "password", "repeated_password"] extra_kwargs = { 'email': {'help_text': _("Enter your email")}, 'username': {'help_text': _("Enter your username")}, 'name': {'help_text': _("Enter your name"), 'required': False, 'allow_blank': True}, } def validate(self, data): print(User.objects.filter(email=data["email"], is_active=False)) if data["password"] and data["repeated_password"] and data["password"] != data["repeated_password"]: raise serializers.ValidationError(_("Password and repeated password must be the same")) if data["email"].strip() == data["username"].strip(): raise serializers.ValidationError(_("Email and username must be different")) return data class ConfirmCodeSerializer(serializers.ModelSerializer): email = serializers.EmailField(write_only=True, max_length=220, min_length=6, help_text=_("Enter your email")) class Meta: model = VerficationCode fields = ["email","code"] extra_kwargs = { 'email': {'help_text': _("Enter your email")}, 'code': {'help_text': _("Enter your code")}, } views.py: class RegisterationApiView(APIView): """ Get username, email, name, and password from the user and save it in … -
How can I solve the problem as mentioned below?
I am new to Django and while I was doing some stuff with Django Framework, I came across some problems My Python Code [views.py] def create(request): if request.method == "POST": print(request.POST) and My JavaScript Code is const formdata = new FormData() formdata.append('itemOne', itemValue) formdata.append('itemTwo', itemValue) fetch("/create", { method: 'POST', credentials: 'same-origin', body: formdata, headers:{ // 'Accept': 'application/json', 'Content-Type': 'application/json', 'X-CSRFToken': getCookie("csrftoken") }, }) .then(response => response.json()) .then(response => { console.log(response) }) .catch(err => { console.log(err) }) when I make a POST request as above from my JavaScript code, I get an empty dictionary. What might be the problem here? this is my urls.py files' code from django.urls import path, include from . import views urlpatterns=[ path('', views.index, name='home'), path('create', views.create, name='backend') ] How can I resolve the problem? I tried solutions from different websites and videos and none of them worked. -
Django wont upload images to media directory
Today I tried to have images in my project and the idea is simple - create news with an image, title, and description. I wonder why when I set up my media files So I make my news in this view: class NewsCreate(views.CreateView): template_name = 'web/create_news.html' model = News fields = ('title', 'image', 'description') success_url = reverse_lazy('home') Here is the model: class News(models.Model): TITLE_MAX_LENGTH = 30 title = models.CharField( max_length=TITLE_MAX_LENGTH ) image = models.ImageField( upload_to='news/', blank=True ) description = models.TextField() Here is the set-up in settings.py: MEDIA_ROOT = BASE_DIR / 'mediafiles' MEDIA_URL = '/media/' Here is the urls.py file: from django.contrib import admin from django.urls import path, include urlpatterns = [ path('admin/', admin.site.urls), path('', include('University_Faculty.web.urls')), ] if settings.DEBUG: urlpatterns += static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) I've noticed that when I try to go to none existing URL this happens : wrong ulr page showing media as a correct one This is the result in my media folder after 10+ POST requests it shows in the database that it is actually creating the news, but the images won't go anywhere: no files media folder -
Convert from dash html to regular html string
I've been using plotly to generate a few charts and used dash to render them on a simple heroku server. Now I am moving the dash component to Django, I have a very nice html layout generated with dash function, which is composed of some charts and some styling with it. I am trying to read it as html so that I can use a function in view to call the page. When I checked the layout data type, it is dash.html.Div.Div rather than html, or string of "html". I am wondering if I can convert it directly into HTML, so that I can render it like normal html code. Thanks