Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is there a way to conditionally require a field in a Django Filterset?
Let's say I have a Filterset: class AnimalFilter(filters.FilterSet): animal_family = filters.CharFilter(required=True) is_land_animal = filters.BooleanFilter(required=True) But what if I only want to set required=True for one or the other. Like if someone passes in animal_family, I don't need to receive is_land_animal or vise versa. -
Django mySQL database insert query using .save() and .validate_unique with a composite primary key
I am trying to insert directly into a mySQL database table that has a composite primary key value consisting of 'Fname', 'Lname' and 'DOB'. I want to allow the user to be able to add to the database directly from the web application though using a request.POST form method in Django and getting the user input to insert into the database if it does not violate a duplicate primary key value. However, Django only allows you to assign one primary key value to a model field. This is the table model Athlete_T that also has a Meta class with a unique_together field specifying the composite primary key. class AthleteT(models.Model): fname = models.CharField(db_column='Fname', primary_key=True, max_length=30) # Field name made lowercase. lname = models.CharField(db_column='Lname', max_length=30) # Field name made lowercase. dob = models.CharField(db_column='DOB', max_length=10) # Field name made lowercase. sportsteam = models.CharField(db_column='SportsTeam', max_length=30, blank=True, null=True) # Field name made lowercase. position = models.CharField(db_column='Position', max_length=30, blank=True, null=True) # Field name made lowercase. year = models.CharField(db_column='Year', max_length=15, blank=True, null=True) # Field name made lowercase. height = models.FloatField(db_column='Height', blank=True, null=True) # Field name made lowercase. #upload_to='staticfiles/images' image = models.TextField(db_column='Image', blank=True, null=True) # Field name made lowercase. class Meta: managed = False db_table = 'Athlete_T' unique_together … -
How do I implement reset password link in Django admin of if superuser forgot password then he can reset password using reset_password html template
I want to add forgot password link in django admin panel if superuser forgot password then he don't have to use terminal when project is on product so how to add forgot password option in django admin panel?Django admin login page I've added paths in urls.py and created reset password pages in templates/registration/reset_password_form.html. Please see the images given belowHTML templates for reset passwordpath in urls.pyextended base.html did all this but didn't work -
Django, how i can add item corectly in my cart?
I have a online shop project, in my product detail view i can add to cart items and also this is a cart page which can increase or decrease item there too. the problem is that when i add one myb item in cart page it work like fibonacci sequence and it's add the new number if I have 3 item and use plus one it's gonna be 3+4=7 and if add one more it give me 7+8=15 item. this is my cart.py : def add(self, product, quantity=1): product_id = str(product.id) if product_id not in self.cart: self.cart[product_id] = {'quantity': 0} else: self.cart[product_id]['quantity'] += quantity self.save() and this is view.py def add_to_cat_view(request, product_id): cart = Cart(request) product = get_object_or_404(Products, id=product_id) form = AddToCartProductForm(request.POST) if form.is_valid(): cleaned_data = form.cleaned_data quantity = cleaned_data['quantity'] cart.add(product, quantity) return redirect('cart_detail') and this is cart_detail_view.html <form action="{% url 'cart_add' item.product_obj.id %}" method="post"> {% csrf_token %} <div class="quantity"> <input type="number" class="quantity-input" name="quantity" id="qty-1" value="{{ item.quantity }}"min="1"> {{item.product_update_quantity_form.inplace }} <button type="submit">update</button> </div> </form> -
ImportError: attempted relative import with no known parent package (import from nonexistent parent directory)
I have the following django project structure: └──text_modifier ├── scripts │ ├── reformat.py │ └── upload.py ├── __init__.py ├── admin.py ├── apps.py ├── models.py ├── tests.py ├── views.py └── main.py` I want to import a class (Posts) from models.py to upload.py. I do the following: from ..models import Posts However, it returns an error "attempted relative import with no known parent package" I have tried importing sys and running the following: import sys sys.path.append(r"C:\path\to\your\project") Also, I have tried to rearrange the relative import statement in a different way (from text_modifier.models import Posts, from .models import Posts, etc.) I have flicked through python documentation and some tutorials on relative import, as well as posts here with the same error, but found no solution for my particular set of files. -
How to update Foreign Key, but save data for the old instances
My situation: every student can have at least one Annual Review( if student has changed Department during this year - system has to create new independent Annual Review). As a result we will have 2 reviews: 1 - when student was in dep A, and 2 - for dep 2. But using my code of course I have the same department in both cases. How to prevent first Annual Review instance of Department updates? In step of creation the AnnualReview model I want to extract department from current Student instance. class AnnualReview(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) student = models.ForeignKey('Student', verbose_name='Student', on_delete = models.CASCADE, related_name='+') class Student(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=30, verbose_name='Name') surname = models.CharField(max_length=100, verbose_name='Surname') department = models.ForeignKey('Department', on_delete=models.SET_NULL, null=True, related_name="+", blank=True) -
Errno 10013 An attempt was made to access a socket in a way forbidden by its access permissions
I'm currently working on a django project - real estate app. It's based on internet tutorial from API-Imperfect on youtube. Basically i have been following the steps of that tutorial from the very beginning and this is the err i came across while trying to test api endpoint with insomnia. "[Errno 10013] An attempt was made to access a socket in a way forbidden by its access permissions" I tried to create new user and everything works fine, user has been created and so on but the email confirmation which should be sent after each particular user is registered is actually not being sent whatsoever. I googled the err and it showed me few solutions which i tried. was just to off my antivirus and firewall. was to change my dev server to run on different port. 1+2. i checked if the port that i use was occupied by any other process and it wasn't. I am not using Docker YET but i was planning to, anyway i heard it could potentially be because od docker but as i said i've not been using one yet I tried to find a way to restart hns but i can't find it … -
How to sort the context in def get_context_data | Django Views
I have class based view And i need to sort context of this view I want to show 3 tables: 1. Tasks where author is current user + excluding tasks with complete='Done' 2. Tasks where author is any user but not current user + excluding tasks with complete='Done' 3. All Tasks with complete='Done' Final result should be like this: web page example And it works when veiws.py looks like that class TaskList(LoginRequiredMixin, ListView): model = Task def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['object_list_complete'] = context['object_list'].filter(complete='Done') context['object_list_own'] = context['object_list'].filter(author=self.request.user).exclude(complete='Done') context['object_list'] = context['object_list'].exclude(complete='Done').exclude(author=self.request.user) return context Code that in views.py now works correctly, BUT if change the order of the context lines then everything breaks and looks like this: web page example And it DOESNT work when veiws.py looks like that: class TaskList(LoginRequiredMixin, ListView): model = Task def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) context['object_list'] = context['object_list'].exclude(complete='Done').exclude(author=self.request.user) context['object_list_own'] = context['object_list'].filter(author=self.request.user).exclude(complete='Done') context['object_list_complete'] = context['object_list'].filter(complete='Done') return context I don't know how to fix that please halp T_T models.py class Task(models.Model): STATUS = ( ('Done', 'Done'), ('In progress', 'In progress'), ('Waiting', 'Waiting'), ) author = models.ForeignKey( User, on_delete=models.SET_NULL, null=True ) implementer = models.ForeignKey( User, on_delete=models.SET_NULL, null=True, blank=True, related_name='implementer' ) title = models.CharField(max_length=64) desc = models.TextField() complete = … -
How to centre flex with css
Fairly new to CSS & HTML, I am trying to centre display: flex; and having no luck up to now, I have tried multiple things, justify-content: center; align-items: center; And a few others, the issue I am having is no matter what I change it to the divs stay to the left of the screen, I will add a screenshot of this below HTML PIC Probably something I am doing wrong so any help would be much appreciated, if I can use something else apposed to Flex then I am happy to change this to something else if that is recommended, I just need the divs to be displayed centred at the top of the screen. Here is my CSS: body { background-color: #ffffff; min-height: 120vh; height: 100%; margin: 0; max-width: 120vh; overflow: hidden; } .grid-container{ display: flex; align-items: center; margin: 0; flex-direction: row; height: 440px; width: fit-content; max-width: 880px; flex-wrap: nowrap; gap: 10px; } .grid-container-2{ display: flex; align-items: center; margin: 0; flex-direction: row; height: 440px; width: fit-content; max-width: 880px; flex-wrap: nowrap; gap: 10px; } .Divheaders{ color: #ffffff; padding: 3px; border: 3px solid #000000; } .divONE{ background-color: #ffffff3b; height: 650px; width: 650px; max-width: 50%; max-height: 50%; margin-left: auto; margin-right: auto; … -
CURL -X GET does not return any data
I want to make a get request using CURL, but CURL doesn't return any data. **I have 2 dedicated servers with Ubuntu 20.04. ** First one has API (Django framework), other one handling the game server. So, I'm trying to get info from api, by making get request on machine with game server with curl like that: curl -k https://ymasandbox.ru. And here is the result: CURL request from game server Also, I tried to do this on my main machine, and it works just fine! CURL request from main machine -
Django query with annotated accumulative multiplication
I have these 3 models class Nomenclature(models.Model): name = models.CharField(...) class Price(model.Model): nmc = models.ForeignKey(Nomenclature, ...) price = models.DecimalField(...) year = models.SmallIntegerField(..., verbose_name='Year when price was idicated') class InflationRate(models.Model): year = models.SmallIntegerField(...) coefficient = models.DecimalField(...) In "Price" i put nomenclature, its' price and year when this price was indicated. In InflationRate I have records for each rate which indicates for me how high there is inflation in xxx.xx format. For example product A has price 113.34 in 2022, inflation rate coefficient in 2023 was 113.3, in 2024 predicted and recorded value is 120.5, so the price of product in 2024 is 113.34 * 120.5 / 100 * 113.34 / 100 = 154.79. My question how can I annotate predicted price calculated in the way described above to Price queryset? And furthermore this queryset should be also a part of another Subquery I tried to perform something like this: prediction_year = 2024 inflation = RawSQL( """select exp(sum(ln(coefficient/100))) from app_name_inflationrate where year > %s and year < %s """, [F('year'), prediction_year]) price = Price.objects.filter( nmc_id=OuterRef('id') ).annotate( price=ExpressionWrapper(inflation*F('price'), output_field=DecimalField(max_digits=10, decimal_places=2)) ).values_list('price', flat=True) My idea was to do accumulative multiplication of coefficients starting from year when price was indicated in Price table. The problem … -
Sending mail using django
I keep trying to send a mail using the send_mail funtion from "django.core.mail" but my brower keeps throwing this error. SMTPConnectError at / (421, b'Service not available') Please why is this happening. settings.py DEBUG = True EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_PORT = 587 EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myemailaddress' EMAIL_HOST_PASSWORD = 'myapppassword' views.py from django.core.mail import send_mail from django.conf import settings def index(request): if request.method == "POST": heading = request.POST['heading'] message = request.POST['content'] email = request.POST['email'] print(settings.EMAIL_HOST_USER) send_mail( subject=heading, message=message, from_email=settings.EMAIL_HOST_USER, recipient_list=[email], fail_silently=False ) return render(request, 'index.html') How do I go about to resolve this issue -
Django: Disable CSRF on debug not working
I am debugging my Django project deployed in the cloud. It does not have a domain name yet. I cannot login though the /admin/ page because of the CSRF error: CSRF verification failed. Request aborted. I am also trying to debug it using my frontend deployed in machine at localhost:3000. The same case, I get a 403 response signifying the CSRF verification failure. I want to bypass this on DEBUG=True for the purpose of debugging my APIs. I found this thread, and followed one of its answers: https://stackoverflow.com/a/70732475/9879869. I created a Middleware supposedly disabling the CSRF when DEBUG=True. #utils.py from project import settings from django.utils.deprecation import MiddlewareMixin class DisableCSRFOnDebug(MiddlewareMixin): def process_request(self, request): attr = '_dont_enforce_csrf_checks' if settings.DEBUG: setattr(request, attr, True) I added it to my MIDDLEWARE. It is the last entry in the list. 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", "project.utils.DisableCSRFOnDebug" ] After all of this, I still cannot login to my Django admin and my locally deployed frontend still gets the CSRF verification failure. I do not want the csrf_exempt option since it does not make sense placing it on an important endpoint/view -- the Login. Here are my additional configuration on settings.py. X_FRAME_OPTIONS … -
how to get angular form input value using django api?
Here is the Django Login API Code from django.views.decorators.csrf import csrf_exempt @csrf_exempt def login(request): try: response_data = {} if request.method == 'POST': return HttpResponse(request) // {"user":"Umair","pwd":"12345"}(by returning the request it shows angular form input values) user = request.POST['user'] pwd = request.POST['pwd'] Emp = Employee.objects.filter(Emp_Name=user, Emp_Pwd=pwd).exists() if Emp is True: if 'UserName' not in request.session: request.session['UserName'] = user response_data['response'] = "LOGIN SUCCESS!" response_data['IsLogin'] = "TRUE" return HttpResponse(json.dumps(response_data), content_type="application/json") return HttpResponseRedirect('Dashboard') else: response_data['response'] = "Invalid UserName Or Password!" response_data['IsLogin'] = "FALSE" return HttpResponse(json.dumps(response_data), content_type="application/json") else: response_data['response'] = "Request Method must be POST rather than GET" response_data['REQUIRED METHOD'] = "POST" return HttpResponse(json.dumps(response_data), content_type="application/json") except Exception as e: return HttpResponse("Error !" + str(e)) As you can see in the image given below The API returns angular form input values how to get the POST form values and saved in these variables given below: user = request.POST['user'] pwd = request.POST['pwd'] Here is the attached screenshot -
A model to handle multiple types with different fields in Django
In django I should create this model which I then use in django rest framework for api requests: A criterion model which can be of three types: qualitative, quantitative and multiple. In the quantitative case, the criterion template has only one description field. In the qualitative case, the criterion model has one description field and two other integer fields In the qualitative case, the criterion model has a description field and multiple fields of the type "name" and "weight". I was thinking about such an implementation but it seems too little pythonic to me: class Criterion(models.Model): TYPES_LIST = ( ('QUALITATIVE', 'Qualitative'), ('QUANTITY', 'Quantity'), ('MULTIPLE', 'Multiple choice'), ) type = models.CharField(max_length=64, choices=TYPES_LIST) description = models.TextField() class Meta: abstract = True class QualitativeCriterion(Criterion): decision_scheme = models.ForeignKey(DecisionScheme, on_delete=models.CASCADE, related_name='qualitative_criteria') class QuantityCriterion(Criterion): CLASSIFICATIONS_LIST = ( ('TEST1', 'TEST 1'), ('TEST2', 'TEST 2'), ) MEASUREMENT_UNITS_LIST = ( ('M', 'Meter'), ('CM', 'Centimeter'), ) classification = models.CharField(max_length=64, choices=CLASSIFICATIONS_LIST) measurement_unit = models.CharField(max_length=64, choices=MEASUREMENT_UNITS_LIST) decision_scheme = models.ForeignKey(DecisionScheme, on_delete=models.CASCADE, related_name='quantity_criteria') class MultipleChoicesCriterion(Criterion): decision_scheme = models.ForeignKey(DecisionScheme, on_delete=models.CASCADE, related_name='multiple_choices_criteria') class MultipleChoicesCriterionOption(models.Model): description = models.CharField(max_length=255) weight = models.PositiveIntegerField() criterion = models.ForeignKey(MultipleChoicesCriterion, on_delete=models.CASCADE, related_name='options') I would like that from the decision schema calling a related name of the type "criteria" I get all but implementing … -
Passing task url to initProgressBar in Celery Progress returns 400 (Bad request)
I am building an app with django and docker. I decided to use celery progress to track the progress of a long task. I think it is maybe due to the url that I pass or the way I pass it. Substantially after button click I send an ajax call to start the task and another to wait for the task id on the same view. That returned would trigger the initProgressBar. urls.py(project) from django.contrib import admin from django.urls import path, include, re_path urlpatterns = [ path('admin/', admin.site.urls), path('', include('mappa.urls')), path('celery-progress/', include('celery_progress.urls')), ] main.js const poll_state = function(){ $.ajax({ type: 'POST', url: $('#ProcForm').data('url'), dataType: 'json', data: { 'poll_state': 'yes', 'csrfmiddlewaretoken': csrftoken, }, success: function(res){ if (res['onHold'] == 'yes'){ console.log(res) setTimeout(function(){ poll_state() }, 500) } else{ console.log(res) var task_id = res.proc_id var progressUrl = '{% url "celery_progress:task_status" "task_id" %}'; var progressUrl = progressUrl.replace("task_id", task_id) CeleryProgressBar.initProgressBar(progressUrl); // <--- This is the line triggering the error } } }) } settings.py INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.gis', 'leaflet', 'django_celery_beat', 'django_celery_results', 'crispy_forms', 'corsheaders', 'celery', 'celery_progress', 'mappa' ] CELERY_BROKER_URL = 'redis://redis:6379/0' CELERY_RESULT_BACKEND = 'redis://redis:6379/0' CELERY_CACHE_BACKEND = 'django-cache' CELERY_ACCEPT_CONTENT = ['application/json', 'json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' CELERY_TIMEZONE = 'Europe/Rome' -
How to get current in django urls.py using requests module
I need to get current url using requests module in django For eg : In urls.py file import requests How to get current url using this module -
pytest-django: django_db_keepdb Does Not Prevent Destruction of Test Database
I am testing a Django (v. 4.1) application using pytest-django (v. 4.5.2). I want to preserve the database that is created during testing so that I can examine it afterward. According to the pytest-django documentation: django_db_keepdb Returns whether or not to re-use an existing database and to keep it after the test run. Here is how I am using it: import datetime import pytest from annotations import import_data @pytest.mark.django_db def test_import_data(django_db_keepdb): start_date = datetime.datetime(2016, 1, 1) end_date = datetime.datetime(2016, 6, 1) import_data.import_data(start_date, end_date) The test runs but pytest destroys the test database after the test run. Creating test database for alias 'default' ('test_vita')... PASSED [100%]Destroying test database for alias 'default' ('test_vita')... Perhaps I am misinterpreting what django_db_keepdb is supposed to do? How can I prevent the test database from being destroyed? -
Not updating the profile in Django
Not updating the profile in Django Error : int() argument must be a string, a bytes-like object or a real number, not 'function' **model: ** class Profile(AbstractUser): codemeli = models.CharField(max_length=10, verbose_name='کد ملی', unique=True) fname_en = models.CharField(max_length=150, verbose_name='نام لاتین') lname_en = models.CharField(max_length=150, verbose_name='نام خانوادگی لاتین') father = models.CharField(max_length=150, verbose_name='نام پدر', null=True) father_en = models.CharField(max_length=150, verbose_name='نام پدر لاتین', null=True) date_birth = models.DateField(verbose_name='تاریخ تولد', null=True) place_birth = models.CharField(max_length=150, verbose_name='محل تولد', null=True) gender = models.CharField(max_length=10,choices=Gender, verbose_name='جنسیت', null=True) status_marriage = models.CharField(max_length=10,choices=Status_Marriage, verbose_name='وضعیت تاهل', null=True) mobile = models.CharField(max_length=11, verbose_name='موبایل', null=True) phone = models.CharField(max_length=11, verbose_name='تلفن ثابت', null=True) method_introduction = models.CharField(max_length=10,choices=Method_Introduction, verbose_name='طریقه آشنایی', null=True) tahsilat = models.CharField(max_length=10,choices=Tahsilat, verbose_name='تحصیلات', null=True) reshte = models.CharField(max_length=150, verbose_name='رشته تحصیلی', null=True) job = models.CharField(max_length=150, verbose_name='َشغل', null=True) job_father = models.CharField(max_length=150, verbose_name='َشغل پدر', null=True) job_mather = models.CharField(max_length=150, verbose_name='َشغل مادر', null=True) mobile_father = models.CharField(max_length=11, verbose_name='موبایل پدر',null=True) mobile_mather = models.CharField(max_length=11, verbose_name='موبایل مادر',null=True) bank = models.CharField(max_length=150, verbose_name='َبانک / شعبه',null=True) account_number = models.CharField(max_length=150, verbose_name='شماره حساب',null=True) card_number = models.CharField(max_length=150, verbose_name='شماره کارت',null=True) shaba_number = models.CharField(max_length=150, verbose_name='شماره شبا',null=True) departman = models.ForeignKey(Departman, on_delete=models.CASCADE, verbose_name='متقاضی', null=True) state = models.CharField(max_length=150, verbose_name='استان',null=True) city = models.CharField(max_length=150, verbose_name='َشهر',null=True) area = models.CharField(max_length=150, verbose_name='َمنطقه',null=True) address = models.CharField(max_length=150, verbose_name='آدرس',null=True) description = models.TextField(verbose_name='توضیحات', null=True) image = models.ImageField(default='avatar.jpg', upload_to="Member/profile/", verbose_name='تصویر') status = models.CharField(max_length=4, choices=Status, verbose_name='وضعیت نمایش', null=True) semat = models.CharField(max_length=50, choices=Semat, null=True, verbose_name='سمت', default='0') … -
How to make an ER model with tables and relationships with a sqlite3 database
Working with Django, need an ER model. It doesn't have to be the original database in the first place. Any way to create one without manually drawing all of the tables? A solution that exports and imports into MySQL to reverse engineer also works. Tried Schemacrawler, didn't understand enough to use it. Tried to export it, again, not enough understanding. -
browser requests not completing
I have a django app served with uwsgi and nginx. This app has been deployed for 8 years and now we are seeing that browser requests do not complete. This is what we see in the request timing tab: ss shows only 3 connections to the origin. In the uwsgi log it appears the request has completed: {address space usage: 10855825408 bytes/10352MB} {rss usage: 560128000 bytes/534MB} [pid: 3279260|app: 0|req: 1/25] 10.240.0.58 () {46 vars in 1033 bytes} [Wed Mar 15 13:05:09 2023] GET /report/TASKS/BatchDashboard/ => generated 457971 bytes in 5765 msecs (HTTP/1.1 200) 6 headers in 327 bytes (4 switches on core 0) There are no errors in the nginx or django logs. Any thoughts on why this is suddenly happening and/or how I can debug or fix this? -
Django Design Pattern with NoSQL DynamoDB
This is a general design question as to how to best implement DynamoDB (or NoSQL/Key-Value in general) with the Django ORM for a rather large project with many django apps in it. I am planning on using this in conjunction with a regular SQL DB as well for the more "mundane" and not speed dependant queries. I've found some good insights in this stackoverflow answer already but I am wondering how this works in general as I have not used NoSQL DBs before. I am planning on using the PyNamoDB interface as it seems the most recommended and tested. I primarily require DynamoDB (KV-pair) for 1 or 2 tables that can potentially have several millions of "rows" written per day and then increasingly queried the same (high read&write traffic). Something that will eventually be just too much with a traditional SQL table and where a "model" with a single table data structure isn't really appropriate. Does anyone have experience on this topic especially relating the following questions: If the "traditional" Django model setup (models.Model) does no longer apply I assume and anything like using models.Manager and the traditional Queryset is out the question? If so then this then perpetuates all … -
How to use django-notification to send an anonymous notification to a user
I've implemented a notification sending when the certain object is changed. notify.send(request.user, #UserA recipient=worker.profile.user, #UserB target=application, verb="Your object has been changed") Here is the example of such notification "UserA: Your object Obj has been changed". But for my case I need to send this notification anonymously (just not display the name of UserA in notification) e.g. just "Your object Obj has been changed", but I still need the info about sender. I couldn't find any examples of such use of django-notification system, but it is mentioned in the documentation that there is an anonymous usage of the fields. I've tried to set sender field to None. But it has to be not empty. I've also tried to set actor field. Name of request.user is still mentioned in notification. -
Django: add localhost deployment to CSRF_TRUSTED_ORIGINS
I am trying to debug my cloud deployed Django app. I want to make request to the app using my locally deployed frontend app. I have made the localhost and localhost:3000 to trusted origins. CSRF_COOKIE_SECURE = True CSRF_TRUSTED_ORIGINS = [ 'http://localhost', 'http://localhost:3000', 'https://example.com', ] In my Django app, I still get CSRF verification failed. Request aborted. How can I add my local frontend deployment to CSRF_TRUSTED_ORIGINS? Should it be my external IP Address? What is the other way to debug this way and exempting my localhost frontend to the CSRF verification? -
check if scheduled actions are due
I use huey to create scheduled tasks, that run for example every minute. I created an example to display my question: class Campaign(models.Model): active = models.BooleanField("active", default = True) name = models.CharField("campaign name", max_length = 32) class CampaignTime(models.Model): campaign = models.ForeignKey(Campaign, on_delete = models.CASCADE) time_start = models.TimeField("start time") time_end = models.TimeField("end time") running = models.BooleanField("campaign running right now", default = False) ad_to_show = models.ForeignKey(Ad, on_delete = models.CASCADE) I am not sure if I implemented this "smoothly": from django.utils.timezone import localtime as T class CampaignService: for campaign in Campaign.objects.all(): for ctime in campaign.campaigntime_set.values(): if T.time() > ctime["time_start"] and ctime["running"] == False: ... ## start campaign and set ctime["runnning]" = True elif T.time() > ctime["time_end"] and ctime["running"] == True: ... ## end campaign and set ctime["running"] = False else: continue This somehow looks crude to me. Any suggestions on how to implement this more nicely?