Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
viewing UserDetail template causes user to switch
I have a simple Group model: class Group(models.Model): leader = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=55) description = models.TextField() joined = models.ManyToManyField(User, blank=True) In the DetailView for every Group other Users have the ability to see who has joined and also to check out the User's profile: {% extends 'base.html' %} <ul> {% for member in group.joined.all %} <li><a href="{% url 'user_detail' member.id %}">{{ member }}</a></li> {% endfor %} </ul> This works but with a slight catch. When I click on the link and go to that User's DetailView, suddenly I'm signed in as them. But only on that page it seems because when I go back to my home page, I'm suddenly signed back in as the original User. To be more clear, when I (as the User 'admin') go and click on another User link, I'm brought to the correct UserDetail view: <h6>{{user.username}}</h6> <div>Username: {{user.username}}</div> <div>Email: {{user.email}}</div> <div>First: {{user.first_name}}</div> <div>Last: {{user.last_name}}</div> <div>Groups Joined: {% for group in user.account.joined_group.all %} <a href="{% url 'group_detail' group.pk %}">{{group}}</a> {% endfor %} </div> <div>Groups Created: {% for group in user.account.created_groups.all %} <a href="{% url 'group_detail' group.pk %}">{{group}}</a> {% endfor %} </div> {% if user.is_authenticated and user.id == user.account.id %} <a href="{% url 'update_user' … -
Django whitenoise is fine for production but gives 404 for debug mode
I use django white noise and it works when DEBUG = False; however when setting DEBUG = True, I cannot load the image anymore and get 404 response. Note: I am aware of hard-refresh. I already used static collection and django migrations. Here is my code: django-admin startproject mysite python3 manage.py makemigrations python3 manage.py migrate python3 manage.py startapp polls python3 manage.py collectstatic pip show whitenoise|grep Version Version: 6.2.0 mysite/mysite/wsgi.py import os from whitenoise import WhiteNoise from django.core.wsgi import get_wsgi_application from mysite.settings import BASE_DIR os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_wsgi_application() application = WhiteNoise(application, root=os.path.join(BASE_DIR, "staticfiles") ) mysite/mysite/asgi.py import os from django.core.asgi import get_asgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'mysite.settings') application = get_asgi_application() mysite/mysite/urls.py from django.contrib import admin from django.urls import include, path from django.conf.urls.static import static from django.conf import settings urlpatterns = [ path('admin/', admin.site.urls), path('', include('polls.urls')), ] mysite/mysite/settings.py from pathlib import Path import os BASE_DIR = Path(__file__).resolve().parent.parent SECRET_KEY = 'django-insecure-u5pg-ef=-o0zzi16fk)xf1p8dsz7t$$vayc$3x1y(r01kb0rkg' DEBUG = True ALLOWED_HOSTS = ['*'] INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'polls', ] MIDDLEWARE = [ "django.middleware.security.SecurityMiddleware", "whitenoise.middleware.WhiteNoiseMiddleware", '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', ] ROOT_URLCONF = 'mysite.urls' TEMPLATES = [ { 'BACKEND': 'django.template.backends.django.DjangoTemplates', 'DIRS': [], 'APP_DIRS': True, 'OPTIONS': { 'context_processors': [ 'django.template.context_processors.debug', 'django.template.context_processors.request', 'django.contrib.auth.context_processors.auth', 'django.contrib.messages.context_processors.messages', ], }, }, ] WSGI_APPLICATION … -
Django 'POST" returning 'Subscriber' object has no attribute 'title'
I am attempting to send a POST Request to add a 'Subscriber' to my database. The POST Request goes through without error. I am Posting this { "email":"email@app.com","campaign":1 } and it returns { "id": 2, "email": "email@app.com", "created_at": "2022-08-02T19:49:55.509018Z", "updated_at": "2022-08-02T19:49:55.509018Z", "campaign": 1 } The ID is 2 because it is the second POST I have made This is my Subscriber Class class Subscriber(models.Model): campaign = models.ForeignKey(to = Campaign, on_delete=models.CASCADE) email = models.EmailField(max_length=254) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) class Meta: ordering=('-created_at',) def __str__(self): return self.title() This is my Campaign Class class Campaign(models.Model): title = models.CharField(max_length=200) description = models.TextField() slug = models.SlugField(max_length=255, null = True, blank = True) created_at = models.DateTimeField(auto_now_add=True) updated_at = models.DateTimeField(auto_now=True) logo = CloudinaryField('Image', overwrite=True, format="jpg") class Meta: ordering=('-created_at',) def __str__(self): return self.title def save(self, *args, **kwargs): to_assign=slugify(self.title) if Campaign.objects.filter(slug=to_assign).exists: to_assign = to_assign + str(Campaign.objects.all().count()) self.slug = to_assign super().save(*args, **kwargs) And These are my current Serializers.py class CampaignSerializer(serializers.ModelSerializer): class Meta: model = Campaign fields = "__all__" class SubscriberSerializer(serializers.ModelSerializer): class Meta: model = Subscriber fields = "__all__" My Views.py class CampaignListAPIView(generics.ListAPIView): serializer_class=CampaignSerializer def get_queryset(self): return Campaign.objects.all() class CampaignDetailAPIView(generics.GenericAPIView): serializer_class=CampaignSerializer def get(self, request, slug): #serialize the below python object! query_set = Campaign.objects.filter(slug=slug).first() if query_set: # If you're serializng more … -
ModuleNotFound Error when trying to import variable from script
I have a python script named "WhatsApp_to_Excel.py". There is a variable there that I need to use for a Django project I'm making. So I'm trying to import the module to the models.py file. This is my folder hierarchy- Then I make my import like this- But even though pycharm auto-completed the module's name, when I run the server I get the no module found error. I'm running my code from a virtual environment, but I don't see how this can be the problem. I've tried to import the module in an absolute way, but it didn't work and it's rather weird that pycharm DOES recognize the module. Does anybody Have any ideas on how to solve the problem? Would appreciate any help :-) -
How to get or show every object from newest to latest in Django
I'm pretty new to python and django. I was able to create an simple CRUD logic with template, but i'm getting a small problem. When i update a specific task and then querrying all object from a model, the one that was updated is now querried on the last position (views.py below): def create_task(request): tasks = Task.objects.all() if request.method == 'POST': task_id_update = request.POST.get('task_id_update') task_id_delete = request.POST.get('task_id_delete') if task_id_update: task = Task.objects.filter(id=task_id_update).first() task.finished = True task.save() elif task_id_delete: task = Task.objects.filter(id=task_id_delete).first() task.delete() else: form = TaskForm(request.POST) if form.is_valid(): task = form.save(commit=False) task.author = request.user task.save() return redirect('/create_task') form = TaskForm() return render(request, 'main/create_task.html', {'form': form, 'tasks': tasks}) And i want to render it on a ONE-PAGE like template, and this is what i did in my html: <table class="table table-hover"> <thead> <tr> <th scope="col">Title</th> </tr> </thead> <tbody> {% for task in tasks %} {% if task.finished == False %} <tr> <td>{{task.title}}</td> <td> <form method="post"> {% csrf_token %} <button type="submit" class="btn btn-warning" name= "task_id_update" value="{{task.id}}">Mark as finished</button> </form> </td> <td> <form method="post"> {% csrf_token %} <button type="submit" class="btn btn-danger" name= "task_id_delete" value="{{task.id}}">Delete</button> </form> </td> </tr> {% else %} <tr class="table-success"> <td>{{task.title}}</td> <td> <form method="post"> {% csrf_token %} <button type="submit" class="btn btn-danger" … -
Forcing evaluation of prefetched results in django queries
I'm trying to use select_related/prefetch_related to optimize some queries. However I have issues in "forcing" the queries to be evaluated all at once. Say I'm doing the following: fp_query = Fourprod.objects.filter(choisi=True).select_related("fk_fournis") pf = Prefetch("fourprod", queryset=fp_query) # products = Products.objects.filter(id__in=fp_query).prefetch_related(pf) With models: class Fourprod(models.Model): fk_produit = models.ForeignKey(to=Produit, related_name="fourprod") fk_fournis = models.ForeignKey(to=Fournis,related_name="fourprod") choisi = models.BooleanField(...) class Produit(models.Model): ... ordinary fields... class Fournis(models.Model): ... ordinary fields... So essentially, Fourprod has a fk to Fournis, Produit, and I want to prefetch those when I build the Produits queryset. I've checked in debug that the prefetch actually occurs and it does. I have a bunch of fields from different models I need to use to compute results. I don't really control the table structure, so I have to work with this. I can't come up with a reasonable query to do it all with the queries (or using raw), so I want to compute stuff python-side. It's a few 1000 objects, so reasonable to do in-memory. So I cast to a list to force the query evaluation: products = list(products) At this point, I would think that the Products and the related objects that I have pre-fetched should have been fetched from the DB. In … -
Linux / Django / Site not reachable
Something wrong. 2 months ago I was able to access my django server to this url/port http://212.47.245.79:8000/ Today I went back to this machine, as connection was down. I have restarted django, and I got ERR_CONNECTION_REFUSED in my browser With netstat -tulpn | grep LISTEN I can see the port is in LISTEN mode. What could be the cause ? -
Editable comments django blog
I'm having trouble making my comments editable. They work fine if I leave them uneditable, but I do want them editable. I think it has something to do with primary keys but I'm not quite getting the hang of it. I was able to edit comments earlier, but it would always edit the latest comment. Here is my code: models.py class Tee_times(models.Model): viable_courses = [ ("Eslövs GK","Eslövs GK"), ("Lunds Akademiska GK","Lunds Akademiska GK"), ("Söderåsens GK","Söderåsens GK") ] title = models.CharField(max_length=100, choices=viable_courses, default=1) content = models.TextField() pub_date = models.DateTimeField(auto_now_add=True) player = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return self.title def get_absolute_url(self): return reverse("post-detail", kwargs={"pk": self.pk}) class Comment(models.Model): text = models.CharField(max_length=200, default="Write a comment") tee_time = models.ForeignKey(Tee_times, related_name="comments", on_delete=models.CASCADE) pub_date = models.DateTimeField(auto_now_add=True) player = models.ForeignKey(User, on_delete=models.CASCADE) class Meta: ordering = ("pub_date",) def __str__(self): return f"{self.player} - {self.pub_date}" def get_absolute_url(self): return reverse("post-detail", kwargs={"pk": self.tee_time.pk}) def set_time(self): self.pub_date = models.DateTimeField(auto_now_add=True) urls.py urlpatterns = [ path('', TeeListView.as_view(), name="index"), path('post/<int:pk>/', DetailTeeView.as_view(), name="post-detail"), path('post/<int:pk>/comment/new/', CommentCreateView.as_view(), name="comment-create"), path('post/<int:pk>/comment/<int:pkc>/update/', CommentUpdateView.as_view(), name="comment-update"), path('post/<int:pk>/comment/<int:pkc>/delete/', CommentDeleteView.as_view(), name="comment-delete"), path('post/new/', TeeCreateView.as_view(), name="post-create"), path('post/<int:pk>/update/', TeeUpdateView.as_view(), name="post-update"), path('post/<int:pk>/delete/', TeeDeleteView.as_view(), name="post-delete"), path("second/", views.second, name="second"), path("register/", user_views.register, name="Register") ] views.py ``` class TeeListView(ListView): model = Tee_times template_name = "testapp/index.html" context_object_name = "posts" ordering = ["-pub_date"] class DetailTeeView(DetailView): model = Tee_times … -
Django Template, how to parse items with symbols
I have an XML file that I've converted to a python dictionary and passed into a template. I am attempting to do something like this: <audio controls> <source src={{ episode.enclosure.@url }} type={{ episode.enclosure.@type }}> Your current browser does not support the audio player. </audio> The XML file uses @ at the beginning of the key for URL and TYPE. The problem is, this throws off the parser and crashes the site. How can I call a key with a symbol like @? -
State is being cleared on page reload
I am building a web site using Django and React and I just realized I've got this problem. Basically every time I log in to my page, while not refreshing everything is okay, my state is persistent and my user stays logged in. My logout functionality also works okay, whenever I need to log out the state is being cleared, the local storage is being cleared and everything is okay. The problem comes up when I reload my page. When I do that, my local storage persists but my state doesn't. I can't figure out a way to fix this issue. export const login = (email, password) => async (dispatch) => { try { dispatch({ type: USER_LOGIN_REQUEST, }); const config = { headers: { "Content-type": "application/json", }, }; const { data } = await axios.post( "/api/users/login/", { username: email, password: password }, config ); dispatch({ type: USER_LOGIN_SUCCESS, payload: data, }); localStorage.setItem("userInfo", JSON.stringify(data)); } catch (error) { dispatch({ type: USER_LOGIN_FAIL, payload: error.response && error.response.data.detail ? error.response.data.detail : error.message, }); } }; export const logout = () => (dispatch) => { localStorage.removeItem("userInfo"); dispatch({ type: USER_LOGOUT }); dispatch({ type: USER_DETAILS_RESET }); dispatch({ type: ORDER_LIST_MY_RESET }); dispatch({ type: USER_LIST_RESET }); }; These are my … -
Django Rest CORS with Vue JS
I have a django rest framework api running on http://127.0.0.1:8000/ and a Vue JS app running on http://127.0.0.1:5173/. When I make a request from the vue app I get the origin has been blocked by CORS policy: Request header field access-control-allow-methods is not allowed by Access-Control-Allow-Headers in preflight response. I have installed django cores and below are the setting in my settings.py Installed Apps "corsheaders", Middleware MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'corsheaders.middleware.CorsMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] And allowed CORS_ORIGIN_ALLOW_ALL = True Vue JS Code axios.defaults.baseURL = 'http://127.0.0.1:8000/'; # In axios.js async login() { const response = await axios.get('users', { username: this.username, password: this.password }); console.log(response) }, -
Django - Filtering String Between Two Values
I have a model like so: class Model(...): code = models.CharField(...) My model table is populated like so: ID | CODE -----|------------ 1 | c-AB-xyz 2 | c-AC-edf 3 | c-BB-mng 4 | c-BC-lmp 5 | c-CB-qrs 6 | c-CC-tuv I want to filter for instances based off what their code string starts with. I also want to specifiy a start and stop. For example, how can I filter instances that have a starting code value between c-BB and c-CB? Something like: Model.objects.filter( code__startswith__between = ['c-BB', 'c-CB'] ) Which should return instances 3, 4, and 5. -
How should I be storing query parameters for saved searches in web app? (best practices)
I have a web app that displays articles and each article has several fields all searchable with parameters and they have many to many and many to one relationships . There are several places in my database that store these parameters for something like a saved search or permissions to allow a user to only view certain articles. These parameters are stored as strings, or python query objects, or json objects. The problem is that when one of the names of the parameters changes, the query object, json object, or string isn't updated. So for example, if a article is published by 'U.S. Department of Justice', then a user saves a search with that agency, when we change the name of the agency (lets say there's a misspelling in the name), the search will not find that agency unless we go in an update the stored string object manually. This seems incorrect, but I'm not sure what the correct way is. Is there a best practices for something like this? Should the parameters be stored in a table with object references so that things like name changes are unaffected? OR do I just have to go into these strings and … -
Django positive validation not checking python
But with my below code it is not checking the validation rule and allowing the positive start and positive end values in the conjunction. my code in django form.py d=[] b=[] my_tuple = [] for i in range(count): start_new = int(self.data.get(f'applicationruntime_set-{i}-start_new') or 0) start_old = int(self.data.get(f'applicationruntime_set-{i}-start_old') or 0) end_new = int(self.data.get(f'applicationruntime_set-{i}-end_new') or 0) end_old = int(self.data.get(f'applicationruntime_set-{i}-end_old') or 0) d.append((start_new,start_old)) b.append((end_new,end_old)) my_tuple.append((d[0],b[0])) for i in my_tuple[0]: my_result = [sub for sub in i if all(element >= 0 for element in sub)] if len(my_result)>2: raise ValidationError( f" Positive Start values and Positive End values are not allowed to be used in conjunction") -
Django: How to stop a value from incrementing when i refresh a page in Django?
I have two some fields in my Profile model called: class Profile(models.Model): ... main_all_earning = models.IntegerField(default=0) earning_point = models.IntegerField(default=0) referral_point = models.IntegerField(default=0) indirect_sign_up = models.IntegerField(default=0) and i also have the logic in views.py def profile(request): ... user = request.user profile = request.user.profile my_count = Profile.objects.filter(recommended_by__profile__recommended_by=user).count() profile.indirect_sign_up = my_count * signup_point.ind_signup_point profile.main_all_earning = profile.main_all_earning + profile.indirect_sign_up profile.save() Now whenever i call this profile view, the main_all_earning add whatever is in the indirect_sign_up and give the new value and so on... How do i stop this? what i want is for the main_all_earning to add whatever that is in the indirect_sign_up only once and till there is a new value in the indirect_sign_up and not whenever i refresh the page -
Model using many models (Django)
I have a project where a Monster can have many Actions, but I don't want to relate the Action to any particular Monster. How can I do that? The code is as follows: Monsters(I divided that way so I can expand and create a Character Sheet based o the BaseSheet as well): from django.db import models from actions.models import Action # Create your models here. from django.utils.text import slugify class BaseSheet(models.Model): name: str = models.CharField(max_length=50) race: str = models.CharField(max_length=30) size: str = models.CharField(max_length=30) ac: int = models.IntegerField() ac_type: str = models.CharField(max_length=20) hp: int = models.IntegerField() hp_dices: str = models.CharField(max_length=10) movement: str = models.CharField(max_length=30) strength: int = models.IntegerField() dexterity: int = models.IntegerField() constitution: int = models.IntegerField() intelligence: int = models.IntegerField() wisdom: int = models.IntegerField() charisma: int = models.IntegerField() languages: str = models.CharField(max_length=100, default="None") slug: str = models.SlugField(blank=True, null=True) def __str__(self): return self.name def save(self, *args, **kwargs): if not self.slug: self.slug = slugify(f'{self.name}-{self.id}') return super().save() class Monster(BaseSheet): challenge: str = models.CharField(default="0", max_length=3) description: str = models.TextField(default="") actions = models.ForeignKey(Action, on_delete=models.DO_NOTHING) Action: from django.db import models # Create your models here. class Action(models.Model): name: str = models.CharField(max_length=30) description: str = models.TextField() is_attack: bool = models.BooleanField(default=False) weapon_type: str = models.CharField(max_length=50, blank=True, null=True) attack: int … -
Reset PeriodicTask's interval timer to 0
I have a very simple problem: kick off a new periodic task (with 30 minutes interval) after the first model instance is created and reset the task's timer every time a new model is created. If no model is being created just let the scheduler keep firing the task every 30 minutes. Do I need to delete the previous task and create a new one, or is there another way of just having one task and keep postponing it? -
syntax error: unexpected end of file (expecting "then")
I have an entrypoint.sh file, and I try command docker-compose run web python manage.py runserver. But I get this error: : not found.sh: line 2: /entrypoint.sh: line 25: syntax error: unexpected end of file (expecting "then") ERROR: 2 My entrypoint.sh file: #!/bin/sh if [ "$DATABASE" = "postgres" ] then echo "Waiting for postgres..." while ! nc -z $SQL_HOST $SQL_PORT; do sleep 0.1 done echo "PostgreSQL started" fi if [ "$DEBUG" = "FALSE" ] then echo "run migrations and static" python manage.py migrate python manage.py collectstatic --no-input fi rm -f /app/web/app/celerybeat.pid # you can run celery worker and celery beat from here, all in one container exec "$@"* I use Windows -
django project cloned from github
Here am providing the error I am facing during run the project, firstly am cloned this project from Github and further add the .env file after that run the program and I get this error, please tell me the complete steps for cloning the project from Github and also the steps to run that project /*****************************************************************************/ Exception in thread django-main-thread: Traceback (most recent call last): File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\site- packages\django\apps\config.py", line 245, in create app_module = import_module(app_name) File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\importlib_init_.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "", line 1050, in _gcd_import File "", line 1027, in _find_and_load File "", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'base' During handling of the above exception, another exception occurred: Traceback (most recent call last): File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\threading.py", line 1009, in _bootstrap_inner self.run() File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\threading.py", line 946, in run self._target(*self._args, **self._kwargs) File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\site- packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\site- packages\django\core\management\commands\runserver.py", line 125, in inner_run autoreload.raise_last_exception() File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\site- packages\django\utils\autoreload.py", line 87, in raise_last_exception raise _exception[1] File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\site- packages\django\core\management\__init__.py", line 398, in execute autoreload.check_errors(django.setup)() File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\site- packages\django\utils\autoreload.py", line 64, in wrapper fn(*args, **kwargs) File "C:\Users\its simi\AppData\Local\Programs\Python\Python310\lib\site- packages\django\__init__.py", line 24, in setup apps.populate(settings.INSTALLED_APPS) File "C:\Users\its … -
how can I put image from list in template
I'm studying django and i would like to show an image of a list in the template views.py data = [ { "titulo": "image card 1", "imagem": img/image2.png", }, { "titulo": "image card 2", "imagem": "img/image1.png", }, ] return render(request, 'projects/dev.html',{'data':data}) template = index.html <div class="pb-5 container"> <div class="row"> {%for item in data%} <div class="card-deck col-md-6 pt-4 mx-auto"> <div class="card"> <a href="#"> <img class="card-img-top" src="{{item.imagem}}" alt=""> </a> <div class="card-body"> <h5 class="card-title"> {{item.titulo}}<br> </h5> </div> </div> </div> {%endfor%} </div> </div> </div> obs: I'm using static files -
Django CSS Configuration doesn't show expected styling
I'm new to Django, and I'm trying to use static files to color my website. this is my directory hierarchy- This is the HTML I'm trying to style, by using this code- This is the CSS code I'm using- This my settings.py- No matter what I do, or if I refresh or restart the server completely- nothing happens. I've watched so many articles and videos related to this, but I still can't figure out what am I doing wrong... Would appreciate any help :-) -
DDoS crashes my site that uses Gunicorn in a docker container, nginx throws connection refused errors, yet Gunicorn is still running?
I am running a Django site with Gunicorn inside a docker container. Requests are forwarded to this container by nginx, which is running non-dockerized as a regular Ubuntu service. My site sometimes comes under heavy DDoS attacks that cannot be prevented. I have implemented a number of measures, including Cloudflare, nginx rate limits, gunicorn's own rate limits, and fail2ban as well. Ultimately, these attacks manage to get through due to the sheer number of IP addresses that appear to be in the botnet. Now, I'm not running anything super-critical, and I will later be looking into load balancing and other options. However, my main issue is that the DDoS attacks do not just take down my site - it's that the site doesn't restore availability when the attack is over. Somehow, the sheer number of requests is breaking something, and I cannot figure it out. The only way to bring the site back is to restart the container. Nginx service is running just fine, and shows the following in the error logs every time: 2022/08/02 18:03:07 [error] 2115246#2115246: *72 connect() failed (111: Connection refused) while connecting to upstream, client: 172.104.109.161, server: examplesite.com, request: "GET / HTTP/2.0", upstream: "http://127.0.0.1:8000/", host: "examplesite.com" … -
How can I log a user in without password in django?
I am trying to log a user in and I currently only know the user's email but I know for a fact that it's the correct user. The user has created a password and this is not a log in page. So the question is how do I log the user in without the password. I currently log people in using this: user = authenticate(email=email,password=password) if user is not None: login(request, user) else: #do something but I want to do something like this: user = authenticate(email=email) if user is not None: login(request, user) else: #do something Is this possible? -
Link element tags are disabled when a background image is set
I've got this base.html from which other html documents extend base.html <!DOCTYPE html> <html> <head> <--!some css links and jquery source headers--> <style> {% block style %} .container{ position: relative; } {% endblock style %} </style> <\head> <body> <div class="container"> {% block breadcrumb %}{% endblock breadcrumb %} {% block content %}{% endblock content %} </div> </body> <script type="text/JavaScript"> {% block script %} var imgName = "{% url 'img_file.png' %}"; document.body.style.backgroundImage = "url('"+ imgName.src +"')"; {% endblock script %} </script> <\html> a document that extends from base.html index.html {% extends 'base.html' %} {% block breadcrumb %} <div class="nav nav-bar nav-bar-dark> <a href="some url"> some link</a> </div> {% endblock %} {% block content %} <form action="view-url" method="post"> {{ form }} <input type="submit" class="btn" value"Submit"> </form> {% endblock %} the submit input works well but the link (to some url) seems to be disabled. When I remove the background image from the base.html, the link works just fine. Any help on what I'm missing here please , -
Filter rows based on a pair of conditions in Elasticsearch in Django
I'm working on a QA (survey) application. I have implemented Elastic Search in the application. I want to filter users based on their answers. Suppose, there are questions: Do you have a passport? Yes/No Do you have a driving license? Yes/No Now I want to fetch those users who answered Yes to both questions. My answer document looks like this. @registry.register_document class AnswerDocument(Document): user = fields.ObjectField(properties={ 'id': fields.IntegerField(), 'name': fields.TextField(), }) question = fields.ObjectField(properties={ 'id': fields.IntegerField(), 'name': fields.TextField(), 'description': fields.TextField(), }) class Index: name = 'answers' settings = { 'number_of_shards': 1, 'number_of_replicas': 0, } class Django: model = Answer fields = [ 'id', 'yes_no_ans', ] I have built a query expression but it's not working as expected. expression = (Q('bool', should=[ Q('match', question__name='passport'), Q('match', yes_no_ans='yes'), ], minimum_should_match=2) ) & (Q('bool', should=[ Q('match', question__name='driving license'), Q('match', yes_no_ans='yes'), ], minimum_should_match=2)) response = AnswerDocument.search().query(expression).execute() Can anyone help me with this? Thank you.