Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Why is my like function not working for my django code?
I'm currently doing the CS50 week 4 network problem and I keep having issue with my 'like' and 'unlike' button. It refuses to change even though I click and refresh it multiple times. I've been at it for days and cant seem to figure out what is wrong. Here is my code. Like handler function: function likeHandler(id, whoYouLiked){ if(whoYouLiked.index0f(id) >= 0){ var liked = true; } else { var liked = false; } if(liked === true){ fetch(`/remove_like/${id}`) .then(response => response.json) .then(result => { console.log(result) }) } else{`your text` fetch(`/add_like/${id}`) .then(response => response.json) .then( result => { console.log(result) }) } } Btn for liking in index: {% if post.id in whoYouLiked %} <button class = "btn btn-info fa fa-thumbs-down col-1" onclick="likeHandler({{ post.id }}), {{ whoYouLiked }}" id="{{ post.id }}" ></button> {% else %} button class = "btn btn-info fa fa-thumbs-up col-1" onclick="likeHandler({{ post.id }}), {{ whoYouLiked }}" id="{{ post.id }}" ></button> {% endif %} Like function in my views as well as my URL: def remove_like(request, post_id): post = Post.objects.get(pk=post_id) user = User.objects.get(pk=request.user.id) like = Like.objects.filter(user=user, post=post) like.delete() return JsonResponse({"message": "Like removed!"}) def add_like(request, post_id): post = Post.objects.get(pk=post_id) user = User.objects.get(pk=request.user.id) newLike = Like(user=user, post=post) newLike.save() return JsonResponse({"message": "Like added!"}) Please … -
user = authenticate(request,username=username) returns 'None'
I'm currently working on a Django app in which I'm trying to make a login page. I have used a custom db to store the input into. I have successfully been able to make a signup page, but for some reason I cant authenticate the user every time I try to login. the authenticate function returns None as a return every time and I don't know where I have made a mistake. There are many similar topics like this and I have searched most of them. they didn't seem to solve my problem. Here's my code: views.py def signin(request): if request.method == "POST": username = request.POST["username"] pass1 = request.POST["pass1"] token = ld.login_user(username, pass1)# This is a custom login function which i made for my db. This returns a token which i havent made a use of yet if User.is_active==False: messages.error(request, "User Inactive!") return redirect("home") user = authenticate(request,username=username) if user is not None : login(request,user) fname = user.first_name return render(request, "authentication/index.html", {"fname": fname}) else: messages.error(request, "Bad credentials!") return redirect("home") return render(request, "authentication/signin.html") models.py I don't know if this is a necessary piece of code. I just put it in in case if its necessary @staticmethod def login_user(username, password): """Authenticate a user … -
How to use ccextractor in a django website to extract subtitles in windows
I am unable to make ccextractor work with django website and if I do it how I will able to deploy the website while ccextractor work locally . I think I am missing something critical, anyone know about this or can suggest any docs . I am expecting to extract subtiles and not know how to do it. -
Django Model Validation: How to validate a model field based on the field value of an instance of a different model?
Background: I have a model Bid that implements "bids" on a specific instance of a Listing model. When a Bid is created, the current_bid field is set through a ModelForm and I want to validate that the current_bid field set via the ModelFormfor that Bid is greater than the current_bid field previously set for the Listing instance the Bid is being created for. For reference, here are the two models I have created in Models.py: from django.conf import settings from django.contrib.auth.models import AbstractUser from django.db import models from django.core.validators import MinValueValidator, DecimalValidator from decimal import Decimal from django.core.exceptions import ValidationError class User(AbstractUser): pass class Listing(models.Model): CATEGORY_CHOICES = [ ("APPAREL", "Apparel"), ("COLLECTIBLES", "Collectibles"), ("COMICS", "Comics"), ("MEMORABILIA", "Sports Memorabilia"), ("SNEAKERS", "Sneakers"), ("TRADING_CARDS", "Trading Cards"), ("OTHER", "Other") ] CONDITION_CHOICES = [ ("BRAND_NEW", "Brand New"), ("NEW_DEFECTS", "New with Defects"), ("LIKE_NEW", "Like New"), ("Good", "Good"), ("LIGHTLY_USED", "Lightly Used"), ("USED", "Used"), ("POOR", "Poor") ] author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="usernames") title = models.CharField(max_length=80) description = models.CharField(max_length=800) starting_bid = models.DecimalField(max_digits=11, decimal_places=2,validators=[MinValueValidator(Decimal('0.00'))]) current_bid = models.DecimalField(default=0, max_digits=11, decimal_places=2,validators=[MinValueValidator(Decimal('0.00'))]) image = models.URLField(blank=True) category = models.CharField(max_length=40, choices=CATEGORY_CHOICES, blank=True) condition = models.CharField(max_length=40, choices=CONDITION_CHOICES, default="Brand New") def __str__(self): return f"{self.title}" class Bid(models.Model): owner = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, related_name="owners") listing = models.ForeignKey(Listing, on_delete=models.CASCADE, related_name="listings") current_bid = … -
My question is about bootstrap responsive grid system
Suppose i have two columns in a row each of them are col-6 in left side i have text and the right side i have an image i gave the text-end class to the 2nd column i want to change the class from text-end to text-center in the md , sm screen how to do that ? can anyone guide me ? i just want to use the bootstrap not the custom class of css and make it to the center through media query ? i have used media query to do my task but i just want the bootstrap class to do it without any type of custom css i am expecting that i will get my answer from this platform .. thanks -
Django - want to use inspectdb to get only one table. Using MS SQL Server
I've been testing the inspectdb with django 4.0. If I do "python manage.py inspectdb --database MSDatabase", it tries to bring all table info into the model. Is there a way to select only few or one tables? The DB server is MS SQL Server. The database is MSDatabase, the schema is MySchema, and the table name is MYTBL. I tried "python manage.py inspectdb --database MSDatabase MYTBL" and got the table not found error. -
Django RQ Worker job enqueue after video uploaded fully (chunk upload)
I want to give the signal after the video has fully uploaded, i tried with delays but the time varies conform the upload speed Here is the model: class Post(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE, null=True) title = models.CharField(max_length=500) description = models.TextField() video = models.FileField(blank=True ,upload_to='media/uploads/video_files/', validators = [FileExtensionValidator(allowed_extensions=['mp4'])]) thumbnail = models.ImageField(blank=True, upload_to='thumbnail/', validators = [FileExtensionValidator(allowed_extensions=['jpeg', 'png', 'gif', 'webp', 'jpg'])]) video_preview = models.ImageField(blank=True, upload_to='thumbnail/') video_compressed = models.FileField(blank=True, upload_to='media/uploads/compressed/', validators= [FileExtensionValidator(allowed_extensions=['mp4'])]) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) comments = GenericRelation(Comment) tags = TaggableManager() categories = models.ManyToManyField('Category', blank=True) hit_count_generic = GenericRelation(HitCount, object_id_field='object_pk', related_query_name='hit_count_generic_relation') existingPath = models.CharField(null=True, unique=True, max_length=1000) eof = models.BooleanField(default=False) iframe = models.URLField(max_length=5000, blank=True) approved = models.BooleanField(default=False) link = models.URLField(max_length=5000, blank=True) duration = models.CharField(max_length=500, default='N/A') javascript for the video to upload in chunks: class FileUpload { constructor(input) { this.input = input this.max_length = 1024 * 1024 * 10; } create_progress_bar() { var progress = `<div class="file-icon"> <i class="fa fa-file-o" aria-hidden="true"></i> </div> <div class="file-details"> <p class="filename"></p> <small class="textbox"></small> <div class="progress" style="margin-top: 5px;"> <div class="progress-bar bg-success" role="progressbar" aria-valuenow="0" aria-valuemin="0" aria-valuemax="100" style="width: 0%"> </div> </div> </div>` document.getElementById('uploaded_files').innerHTML = progress } upload() { this.create_progress_bar(); this.initFileUpload(); } initFileUpload() { this.file = this.input.files[0]; this.upload_file(0, null); } //upload file upload_file(start, model_id) { var id_categories = []; var category = … -
Run task alternatively on celery django python
Suppose there are two task 1 and 2 In a span of 30 min run task1 - 15min later task2 - 15min later task1 - 15min later and so on... Instead of running same task every 15 min run them alternatively So far have tried 'task1-FifteenMinutes': { 'task': 'task1', 'schedule': crontab(minute='*/15'), }, No luck on task2 -
Best way to store Business Availability (Weekday and Time) with possible varing timezones
I am currently developing a work availability calendar for users. And I'm looking for a way to store weekly availability so it can be transformed depending on the timezone. For example: If I store Monday with availability from 4 p.m. to 10 p.m. (GMT -5), it should transform the availability from 9 p.m. Monday to 3 a.m when being saved on UTC. Tuesday. However, as it is currently set, it is available. To summarize, is there any way to store this availability in UTC and then transform it to the desired timezone, taking into account the changes in days from one day to another? Initially, I was thinking of storing the availability with two TimeFields for the start_time and end_time and a CharField storing the day of the week. However, when converting the times to UTC, they may change from one day to another. And like that I will not be aware if the days change. Note: Sorry about my grammar. -
How Can I perform Django Multiple Filter on a Model
I am current working on a Django project where I want user to perform property search using different criterial like Property type, State, Minimum bedrooms, Bathroom type, minimum and max price. I want the search to be flexible such that the user chooses which field to search for and not forcing him to input every form field during search. I have tried my best but no error and no positive result, rather even when the user search matches the Model record, it still does not display it. Here is my Model Code: class Property(models.Model): PROPERTY_TYPE_CHOICES = [ ('Complete House', 'Complete House'), ('Apartment', 'Apartment'), ('Self-Contained', 'Self-Contained'), ] BEDROOM_CHOICES = [ ('1', '1'), ('2', '2'), ('3', '3'), ('4', '4'), ('5', '5+'), ] BATHROOM_CHOICES = [ ('Self-contained', 'Self-contained'), ('General', 'General'), ('Private Detached', 'Private Detached'), ] COUNTRY_CHOICES = [ ('Nigeria', 'Nigeria'), ] STATE_CHOICES = [ ('Abia', 'Abia'), ('Adamawa', 'Adamawa'), ('Akwa Ibom', 'Akwa Ibom'), ('Anambra ', 'Anambra '), ('Bauchi', 'Bauchi'), ('Bayelsa', 'Bayelsa'), ('Benue ', 'Benue '), ('Borno', 'Borno'), ('Cross River', 'Cross River'), ('Delta', 'Delta'), ('Ebonyi', 'Ebonyi'), ('Edo', 'Edo'), ('Ekiti', 'Ekiti'), ('Enugu', 'Enugu'), ('Gombe', 'Gombe'), ('Imo', 'Imo'), ('Jigawa', 'Jigawa'), ('Kaduna', 'Kaduna'), ('Kano', 'Kano'), ('Katsina', 'Katsina'), ('Kebbi', 'Kebbi'), ('Kogi', 'Kogi'), ('Kwara', 'Kwara'), ('Lagos', 'Lagos'), ] agent = … -
My django models keep accepting values that they shouldn't
Ok so here's my model: from django.db import models class PetSex(models.TextChoices): MALE = 'Male', 'Male' FEMALE = 'Female', 'Female' NOT_INFORMED = 'Not Informed', 'Not Informed' class Pet(models.Model): name = models.CharField(max_length=50) age = models.IntegerField() weight = models.FloatField() sex = models.CharField(max_length=20, choices=PetSex.choices, default=PetSex.NOT_INFORMED) def __str__(self): return self.name Every time I try to add an invalid sex it should return an error but it keeep accepting it. >>> from pets.models import Pet >>> petinfos_2 = {"name": "xamaria", "age": 1, "weight": 30, "sex": "Malasdasdde"} >>> test123 = Pet(**petinfos_2) >>> test123.save() >>> test123.name 'xamaria' >>> test123.sex 'Malasdasdde' >>> -
Jenkins - Create an agent with a python script
as the title suggests, I am willing to automate the creation of a jenkins agent using python! I don't have any idea about jenkins or what is it even used for, I just got a task to do in my internship and I can't skip it, so I just installed Jenkins and didn't anything yet! I'm sorry for not giving a code sample because I'm literally stuck in that task! All I have is this django view function: @login_required def create(request): if request.method == 'POST': name = request.POST.get('form-submit') description = request.POST.get('employe-description') employee = Employee(user=request.user, name=name, description=description) employee.save() return redirect('create') return render(request, 'create.html') And all I want is when the form is submitted, a jenkins agent will be created using the same name as the employee's from the request. Thanks in advance. -
How do I separate URLs for different groups in Django?
I am developing a login screen using Django-allauth. I would like to change the design of the login screen for Group A and Group B. To do this, we would like to change the URL settings of the login screen for each. Also, pages other than the login, I want Group A to transition to https://xxxx/groupa/account/login/ https://xxxx/groupa/toppage/ https://xxxx/groupa/editpage/ I want group B to transition to https://xxxx/groupb/account/login/ https://xxxx/groupb/toppage/ https://xxxx/groupb/editpage/ Perhaps it would be better to separate the application for Group A and Group B, but I want to keep the source code common except for the login screen. Below is the code I tried. settings.py LOGIN_URL = 'account/login/' LOGIN_REDIRECT_URL = '/' ACCOUNT_LOGOUT_REDIRECT_URL = '/' urls.py path('<str:group>/account/', include('allauth.urls'), name="account_info"), path('<str:group>/', include('member.urls')), I get an error when accessing https://xxxx/groupa/account/login/ NoReverseMatch at /groupa/account/login/ Reverse for 'account_signup' with no arguments not found. 1 pattern(s) tried: ['(?P<group>[^/]+)/account/signup/\\Z'] Is there some middleware or something that forces the URL to change? I am a beginner and very confused. Please give me some advice. -
How can I upgrade Django along with compatible dependencies listed in the requirements.txt file?
I am trying to install the latest version of django-debug-toolbar but it requires a version of Django >=3.2, and the project I am working on was written in Django 2.2.10. Is this going to pose a problem for me if I go ahead and install it? How can I fix this? -
Django with postgresql is getting slower and slower to create and save objects
With Django 4.2.2 and Posgresql 15.3, I have to migrate data from another database. Basically, I am doing something like that for each of the 1,500,000 rows I have to migrate: asset = Asset() asset.creation_date = a date from old database asset.modification_date = a date from old database asset.flag = a boolean from old database asset.serial = a string from old database asset.quantity = an integer from old database asset.save() Note that I do not want to use bulk_create() because I plan to get the generated primary key at once for other processing. The database I read (it is on a separate server) can give me 500 rows per second, this is stable over the time. At Django side, with a NVMe disk, the first 10,000 rows are copied at the speed of 500 inserts/seconds, after 100,000 copies the speed is 100 inserts/s and I stopped migration when it gradually went to 20 inserts/s. I tried : Wait a little and restart my batch at the point it was stopped (I still got 20 inserts/s) Restart postgresql Run without transactions Run without indexes Fully recreate the database But I have still the problem. I checked postgresql log file, but I … -
trying to update the cart icon status using javascript and django
So i am doing this small webpage project in Django and when its time to update the cart icon in the navbar, it doesn't do anything. I had tried some alternatives but no change. Here is some part of my code. If any body can tell me what I'm missing that would be awesome. I'm pretty much a noob to this. añadir_al_carrito.html {% extends 'paginaV3_app/base.html' %} {% load static %} {% block title %}Carrito{% endblock title %} {% block main-content %} <div class="container my-5"> <div class="row"> <h1 class="text-center mb-5">Carrito de compras de {{ request.user }}</h1> <div class="col-sm-8"> <div class="card"> <div class="card-body"> {% for item in items_carrito %} <div class="row"> <div class="col-sm-3 text-center align-self-center"><img src="{{ item.producto.prod_imagen.url }}" alt="" class="img-fluid img-thumbnail shadow-sm" height="150" width="150"></div> <div class="col-sm-9"> <div> <h3>{{ item.producto.titulo }}</h3> <p class="mb-2 text-muted small">{{ item.producto.descripcion }}</p> <div class="my-3"> <label for="cantidad">Cantidad</label> <a class="minus-cart btn" href="{% url 'disminuir_cantidad' item.id %}"><i class="fas fa-minus-square fa-lg"></i></a> <span id="cantidad">{{ item.cantidad }}</span> <a class="plus-cart btn" href="{% url 'aumentar_cantidad' item.id %}"><i class="fas fa-plus-square fa-lg"></i></a> </div> <div class="d-flex justify-content-between"> <a href="{% url 'remover_del_carrito' item.id %}" class="remove-cart btn btn-sm btn-secondary ,r-3">Quitar Item</a> <p class="mb-0"><span><strong>${{ item.producto.precio }}</strong></span></p> </div> </div> </div> </div> <hr class="text-muted"> {% empty %} <h1 class="text-center mb-5">Carrito Vacío</h1> {% endfor %} … -
Django Rest Framework: All POST APIs only respond with "Forbidden" after logging in a user
After enabling authentication in my Django backend and logging in a user all POST Requests stop to work and only respond with "403 Forbidden". I setup a Django App as my backend and I use ReactJS as my Frontend. All the basics work fine so far. But now I want to add authentication to my project. For this I have installed django-cors-headers. I have also included corsheaders in my INSTALLED_APPS. CORS_ALLOWED_ORIGINS allows http://localhost:3000 (the port my Frontend is running under). CORS_ALLOW_CREDENTIALS is also set to TRUE. The corresponding middleware corsheaders.middleware.CorsMiddleware has also been added to the MIDDLEWARE section. I created three APIs. One each for registering a new user, for logging in an existing user and for logging out a user. All three of them work perfectly fine as long as no user is logged in. The cookies csrftoken and sessionid are set just as they should. Now for my problem: As soon as a user is logged in all POST APIs - including the three mentioned above - stop to work. I get a simple "403 Forbidden" response. GET APIs seem to work just fine. My research suggest that this is a common error that has something todo with … -
Django DB Constraint with grandfathered data / Ignore UniqueConstraint for a test?
Recently added a UniqueConstraint to a model (Project) to enforce uniqueness with no problems. class Meta: constraints = [ models.UniqueConstraint( name="%(app_label)s_%(class)s_unique_name_in_organization", fields=['organization', 'name'] ) ] As I understand database constraints, they do not work retroactively. This creates a blindspot as I am uncertain how the grandfathered entities will behave on future database interactions (e.g. will an IntegrityError be raised when saving even if the only change is for an unrelated field?). To remedy this, I've tried creating a test that populates the test database with a few entities that have the known conflict (e.g. a shared name and organization), but as expected Django raises IntegrityError. How can I circumvent this and create purposely bad data that conflicts with my database constraint? I've tried: with connection.constraint_checks_disabled() Project.objects.create( ... with mock.patch.object(Project._meta, 'constraints', return_value=[]): Project.objects.create( ... with mock.patch.object(Project._meta, 'constraints', new_callable=mock.PropertyMock) as cmock: cmock.return_value = [] Project.objects.create( ... However, an IntegrityError is still raised for each attempt. I've tried deleting the constraint with some sql, but that raises django.db.utils.OperationalError: cannot ALTER TABLE "app_project" because it has pending trigger events with connection.cursor() as cursor: table = Project._meta.db_table sql_ = sql.SQL("ALTER TABLE {table} DISABLE TRIGGER ALL").format(table=sql.Identifier(table)) cursor.execute(sql_) cursor.commit() sql_ = sql.SQL( "ALTER TABLE {table} DROP CONSTRAINT … -
Django framework test features not working
I have been stuck on this feature getting this error that I can't seem to solve, I'm still new to coding. It's giving me errors about things that I feel like I have already done. I have a lot of files but Ill share the ones I just changed most recently and that I think must be the issue. This is my accounts/views.py: from django.shortcuts import render, redirect from django.contrib.auth import authenticate, login from django.urls import reverse from .forms import LoginForm def login_view(request): if request.method == "GET": form = LoginForm() return render(request, "accounts/login.html", {"form": form}) elif request.method == "POST": form = LoginForm(request.POST) if form.is_valid(): username = form.cleaned_data["username"] password = form.cleaned_data["password"] user = authenticate(request, username=username, password=password) if user is not None: login(request, user) return redirect(reverse("projects:list_projects")) return redirect(reverse("accounts:login")) This is my accounts/urls.py: from django.urls import path from . import views app_name = "accounts" urlpatterns = [ path("login/", views.login_view, name="login"), ] This is my accounts/templates/accounts/login.html: <!DOCTYPE html> <html> <head> <title>Login</title> </head> <body> <main> <div> <h1>Login</h1> </div> <form method="post"> {% csrf_token %} {{ form }} <button type="submit">Login</button> </form> </main> </body> </html> I've read the rules of what I need to accomplish and it feels like I've met that criteria but it gives me an … -
Looping in window.location
I am getting lat and lng from sessionStorage and I want to send it to browser with window.location but i get to a infinity loop. var lat = sessionStorage.getItem('lat'); var lng = sessionStorage.getItem('lng'); window.location = '?lat='+lat+'&lng='+lng; I saw other questions about this but they did not work. I tryed to use window.location.hash / href etc... but the result is not what I expect Does someone knows how to build that function to work properly? Thank you very much -
Data from Django form doesn't get saved to MySQL table
I am trying to save data, collected via a Django form, to the DB. The page is designed to first ask user for an input, based on which a list is generated. I am trying to save values corresponding to these generated items. But this data, while I see it in the POST request, just doesn't get saved. I am assuming the error is in my Save logic, but I just cannot find it out. I have the views defined to save this, and also the relevant URLs. The Django logs show no error, and there are none when I look into the DB error log. Here's how my code looks like: Model class MonthlySheet(models.Model): month = models.IntegerField() year = models.IntegerField() org_name = models.ForeignKey(Establishment, on_delete=models.DO_NOTHING) employee = models.ForeignKey(Employee, on_delete=models.CASCADE, null=True, default=None) wages = models.IntegerField() gross = models.IntegerField() total_work_days = models.IntegerField() present_days = models.IntegerField() calc_twelve = models.DecimalField(max_digits=10, decimal_places=2) calc_eight_three_three = models.DecimalField(max_digits=10, decimal_places=2) calc_diff = models.DecimalField(max_digits=10, decimal_places=2) calc_point_seven_five = models.DecimalField(max_digits=10, decimal_places=2) def get_absolute_url(self): return reverse('monthly_sheet_detail', kwargs={'pk': self.pk}) def save(self, *args, **kwargs): self.pk = f"{self.month}.{self.year}" super().save(*args, **kwargs) View: class AddMonthlySheetView(FormView): template_name = 'add_monthlysheet.html' form_class = CustomMonthlySheetForm model = MonthlySheet def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) last_month, year, total_work_days = set_previous_month() context['last_month'] = last_month … -
HTTP 404 error for css and javascript files in Django and Gunicorn
The actual error is Refused to apply style from 'http://127.0.0.1:8000/static/css/home.css' because its MIME type ('text/html') is not a supported stylesheet MIME type, and strict MIME checking is enabled. GET http://127.0.0.1:8000/static/js/home.js net::ERR_ABORTED 404 (Not Found) This error started happening when I started using Gunicorn as app server. The first error for css is a misdirection. The file was not found to begin with. Chrome developer tools shows Request URL:http://127.0.0.1:8000/static/css/home.css Request Method:GET Status Code:404 Not Found Referrer Policy:same-origin Connection:close Content-Length:8559 Content-Type:text/html Date:Wed, 07 Jun 2023 19:32:29 GMT Referrer-Policy:same-origin Server:gunicorn status code. I see the same status code for all the css and javascript files. Here are my relevant settings settings.py INSTALLED_APPS = [ . . 'django.contrib.staticfiles', 'bootstrap4', . . ] STATICFILES_DIRS = [ os.path.join(BASE_DIR, "kubera/static"), ] STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, "static") import mimetypes mimetypes.add_type("text/css", ".css", True) manage.py collectstatic command copied the files correctly ~/workspace/djangoapp/src$ python3 manage.py collectstatic 161 static files copied to '/home/<myhomedir>/workspace/djangoapp/src/static'. index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> {% load static %} {% load bootstrap4 %} {% bootstrap_css %} {% bootstrap_javascript jquery='full' %} {% bootstrap_messages %} <link href="{% static 'css/home.css' %}" type="text/css" rel="stylesheet"> <title>{% block title %}Parier Config Central {% endblock %}</title> </head> … -
How to find out where Django is querying from?
I am relatively new to Django and web development in general. I am working on a project with my company (small company, three developers here currently who all have little to no experience) which has very little documentation, and the person who used to work on it is gone. I am getting errors when building the project, and part of the problem I think is that I may have incorrect data for building the project. My specific question is, when you call something like Model.objects.get(), how can you tell where the program is "getting" this information from? My project has a ton of moving parts - an sqlite db, a csv spreadsheet, a whole directory of audio recording sessions, and is making use of all of them. I am not sure whether this get() is looking at any of these, or possibly an API that no one currently in my company even knows exists. Is there a standard file in most Django projects where I could see what Model.objects.get() looks at when fetching the data? -
How to cache beautified / prettified outputted HTML rendered by Django?
I've implemented a Middleware after researching how to beautify / prettify (format nicely), the outputted HTML rendered in the browser for my Django project. I came across this method here. settings.py # local Memcached CACHES = { 'default': { 'BACKEND': 'django.core.cache.backends.locmem.LocMemCache', 'LOCATION': 'unique-snowflake', } } MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', ... 'django.middleware.gzip.GZipMiddleware', 'myproject.middleware.HTMLBeautifyMiddleware', # needs to come after gzip ] myproject/middleware.py from bs4 import BeautifulSoup class HTMLBeautifyMiddleware(object): TAGS = ["p", "script", "span", "i", "h1", "h2", "h3", "h4", "h5", "h6"] def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) if response.status_code == 200: if response["content-type"].startswith("text/html"): html = BeautifulSoup(response.content, "lxml", preserve_whitespace_tags=self.TAGS) response.content = html.prettify() return response In the discussion on the blog, a comment mentions: I’d advise to cache the output before using this plugin on a production site. My questions are: How would one go about caching the outputted HTML? Does Django or the browser handle caching the outputted HTML for me, or do I need to do something explicitly to make it happen? If I used AWS Cloudfront, would that be a solution? -
Unable to send email using celery in DRF
I'm unable to send email via smtp using celery task and DRF. I have the following constants in settings.py # Celery settings CELERY_BROKER_URL = 'redis://127.0.0.1:6379/0' CELERY_RESULT_BACKEND = 'redis://127.0.0.1:6379/0' # Email settings EMAIL_BACKEND ='django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_HOST_USER = MY_EMAIL EMAIL_HOST_PASSWORD = MY_PASSWORD EMAIL_USE_TLS = True EMAIL_USE_SSL = False tasks.py from django.core.mail import send_mail from celery import shared_task @shared_task def send_verification_email(user_email): send_mail( subject="test email", message="testing", from_email=settings.EMAIL_HOST_USER, recipient_list=[user_email], fail_silently=False ) views.py class RegisterUserAPIView(generics.GenericAPIView): ... user_email = ... send_verification_email.delay(user_email = user_email) ... The error I'm getting is raised unexpected: SSLCertVerificationError(1, '[SSL: CERTIFICATE_VERIFY_FAILED] certificate verify failed: unable to get local issuer certificate (_ssl.c:992)') Also, if i'm using console instead of smtp in below EMAIL_BACKEND, i'm able to send emails to the console without any problem.. EMAIL_BACKEND ='django.core.mail.backends.console.EmailBackend' I have EMAIL_USE_SSL = False but still asking for SSL certificate ? Not understanding how to fix this issue.