Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django login - "Cannot force an update in save() with no primary key"
I have implemented the standard Django login in the following manner: from django.contrib.auth import authenticate, login, logout def login_request(request): username = password = "" if request.POST: username = request.POST["username"].lower() password = request.POST["password"] user = authenticate(username=username, password=password) if user is not None: if user.is_active: login(request, user) return redirect("../..") return render(request, "login.html", context={"error": "TRUE"}) return render(request, "login.html", context={"error": "FALSE"}) For most users, this has worked fine. However, for some users it has been throwing the following error: ValueError at /login/ Cannot force an update in save() with no primary key. This error is sourced back to the user.save(update_fields=['last_login']) in django/contrib/auth/models.py. I have been unable to determine why this error is occurring, and why it happens to some users and not others. I've looked closely, and been unable to find anything that differentiates between users who have had this problem and those who haven't. -
I can't seem to find a way to write into heroku's postgres from my django app
I wrote an app with Django and it has been working fine when running locally. I know deployed it with Heroku and the app run as well. However, I when I python manage.py createsuperuser it says that I successfully created the superuser but nothing is written into Heroku Postgress DB...so I can login into neither /admin nor my app. I have been trying debugging like crazy but I can't find the issue. This is my settings.py from pathlib import Path import os # Build paths inside the project like this: BASE_DIR / 'subdir'. BASE_DIR = Path(__file__).resolve().parent.parent # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/3.2/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = ... # SECURITY WARNING: don't run with debug turned on in production! DEBUG=True #DEBUG_PROPAGATE_EXCEPTIONS = True ALLOWED_HOSTS = ['localhost', '127.0.0.1', 'produceit.herokuapp.com'] # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'action.apps.ActionConfig', 'django_extensions', 'bootstrap_modal_forms', 'widget_tweaks', ] MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] ROOT_URLCONF = 'mywebsite.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 = 'mywebsite.wsgi.application' # Database # … -
How filter by date and convert datetime
I am sending some dates from the front made in vue. I am receiving these dates in my viewSet in django, I want to filter data from these received dates. I have two questions: How do I convert dates into Python Datetime? How do I filter the dates equal or greater or equal or less. => <= In other words: bring records whose date is equal to or greater than another date. date format in the front: 2021-08-03 10:12:14 date format in the back: # print(type(fechas['desde'])) fecha <class 'str'> # print(fechas['desde']) fecha 2021-08-03 10:12:14 VIEWSET: class TecnicosViewSet( mixins.CreateModelMixin, mixins.UpdateModelMixin, mixins.RetrieveModelMixin, mixins.ListModelMixin, mixins.DestroyModelMixin, viewsets.GenericViewSet): queryset = Tecnico.objects.all() serializer_class = Tecnicoserializer def list(self, request): dataQ = request.GET newQ = json.dumps(dict(dataQ)) newQ1= json.loads(newQ) tecnicos = '' fechas= json.loads(newQ1['fechas'][0]) for item in newQ1['tecnicos']: itemN = json.loads(item) tecnicos = itemN['tecnicos'] print('fechas', fechas['desde'], fechas['hasta']) # fecha = datetime.strptime(fechas['desde'], '%Y-%m-%d %H:%M') print('fecha', type(fechas['desde'])) print('fecha', fechas['desde']) for id in tecnicos: ordenes = Servicio_realizados_orden_trabajo.objects.filter(date_range = [fechas['desde'], fechas['hasta']]).filter(state = 1).filter(tecnico = id) ordenS = ServicioRealizadosserializer(ordenes, many=True) return Response({'OK'}) As I fixed before: I want to convert that date into understandable python format and then use that transformed date to filter data by that date. The for loop seen in the … -
how to loop through DIV id in ajax in Django
i have Django Appp and i use Ajax request i want to loop through DIV class inside Ajax <span value="{{i.id}}" name="{{i.id}}" id="quant{{i.id}}" class="input-counter__text input-counter--text-primary-style quant-{{forloop.counter}}">{{i.quantity}}</span> <a class="cart-add" value="{{i.id}}" href="{% url 'home:cart_quantity_add' id=i.id %}"><span class="input-counter__plus fas fa-plus"></span></a> </div> so every time i click on the link the quantity should appear inside the span Here is my Ajax <script type="text/javascript"> $(".cart-add").on("click",function (e) { e.preventDefault(); const ProductId = $(this).val(); // get the selected subject ID from the HTML dropdown list $.ajax({ // initialize an AJAX request type: "POST", url: $('.cart-add').attr("href"), data: { 'add-product': ProductId, // add the country id to the POST parameters 'csrfmiddlewaretoken':$('input[name=csrfmiddlewaretoken]').val(), }, success: function (data) { // `data` is from `get_topics_ajax` view function let html_data2=""; data.forEach(function (data) { html_data2 += ` ${data.quantity} ` }); $(".quant-{{forloop.counter}}").html(html_data2); } }); }); </script> -
Why is my django application not serving .css files?
I have an issue with serving a specific css file in my django app and I can't seem to find the solution to it, hopefully someone can help. I have a website PersonalWebsite and in there I have three apps, the important one being the dashboard. I decided to separate the static files of each app and then also the static files of the base website so my folder structure is like this: PersonalWebsite | |static |PersonalWebsite | |css | style.css |fonts | font.ttf |dashboard | |static |dashboard |css | style.css When I open up the website I can see all files from the static/PersonalWebsite are being served, however the ones from static/dashboard are not. Could anyone provide some insight as to what is wrong? I have run the collectstatic command several times and that one detects the file and I see it being copied into the root folder. These are my static settings. I added boot because in that one I have bootstrap downloaded. STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'root') STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static/'), os.path.join(BASE_DIR, 'boot/'), ] -
Django Simple Template Tag Questions
I'm a student who is learning how to play Django. You are about to output a p-tag using template tags in the vault. The template tag I want to use is "When option.product_code and product.product_code are the same in the Option table, print out if there are two options.option_code". How should I fill out the if statement? I'd like to add Hello by referring to the above. Please give me some advice. -
Django: How to make FIle name the same as Post Form Title
So on my app I want a user to upload an image and the title of the form will become the file name. so ex: user uploads image xyz.jpg, title = newfile after that the image will now be newfile.jpg this is my code below im really new to django so hopefully somebody can pull me in the right direction #forms class PostForm(forms.modelForm): class Meta: model = Post fields = ['title', 'cover'] #urls from django.urls import path from .views import HomePageView, CreatePostView urlpatterns = [ path('', HomePageView.as_view(), name='home'), path('post/', CreatePostView.as_view(), name='add_post') ] #views from django.shortcuts import render from django.views.generic import ListView, CreateView from django.urls import reverse_lazy from .forms import PostForm from .models import Post class HomePageView(ListView): model = Post template_name = 'home.html' class CreatePostView(CreateView): # new model = Post form_class = PostForm template_name = 'post.html' success_url = reverse_lazy('home') -
Unable to run custom decorator after post_save signal
I have a post_save signal which is run after any updates happens to a Profile, like so: # removing the `dispatch_uid` parameter doesn't change anything @receiver(post_save, sender=Profile, dispatch_uid="c_profile_invite") def send_invitation_email(sender, instance, **kwargs): # ... do things I would like to run a custom decorator on the signal, after the post_save has been run, like so: def my_test_decorator(func): print("outside the wrapper") def wrapper(request, board_id, board_name): print("INSIDE THE DECORATOR AFTER POST_SAVE") try: return func(request, board_id, board_name) except Exception: return Http404("Board not found") return wrapper @my_test_decorator @receiver(post_save, sender=Profile, dispatch_uid="c_profile_invite") def send_invitation_email(sender, instance, **kwargs): # ... do things However, my method my_test_decorator doesn't run at all. However, if I switch places on the decorators then it will run but it will run before the @receiver decorator, not after. What am I missing? Found this 5 year old question, but it was left unanswered so I'm trying again. TYIA -
How to create Models without an app in django?
Is there a way I can create a Models.py file without creating an app and make the models work with migrations that django provides? -
How to fiend one nearest date in HTML Calendar django
i want to implement an event calendar. i am faced with the problem of displaying the closest event to today's date. to find the nearest date, i use __gte in queryset, after queryset finds all the nearest dates, I want to highlight the first one with a different color here is my solution could you tell me what i'm doing wrong? This is my Model class Events(models.Model): title = models.CharField(max_length=100) slug = models.SlugField() start_time = models.DateTimeField() end_time = models.DateTimeField() def __str__(self): return self.title @property def get_html_url(self): url = reverse('cal:events', args=(self.slug,)) return f'<a href="{url}">' And my HTMLCalendar from datetime import datetime, timedelta from calendar import HTMLCalendar from .models import Events class Calendar(HTMLCalendar): def __init__(self, year=None, month=datetime.now().month): self.year = year self.month = month super(Calendar, self).__init__() # formats a day as a td # filter events by day def formatday(self, day, events): events_per_day = events.filter(start_time__day=day) d = '' if Events.objects.filter(start_time__day=day, start_time__month=self.month).exists(): for event in events_per_day: d += f'{event.get_html_url}' if day != 0: ev = Events.objects.filter(start_time__gt=datetime.now()).first() if ev: return f"<td>{d}<span style='color:red;' class='date'>{day}</span></a></td>" else: return f"<td>{d}<span style='color:aliceblue;' class='date'>{day}</span></a></td>" return '<td></td>' else: if day != 0: return f"<td><b><span class='date'>{day}</span> </b></td>" return '<td></td>' # formats a week as a tr def formatweek(self, theweek, events): week = '' … -
python turn these print values into dictionary with keys being first column and the buttom being dictionary values
I am working with django and got back a response that looks like this Name,surname AVA,AAJ DAA2,ASA EAA23,VVD GAA43,DDA AAA42,AAS MAA21,JJ produced by this code @api_view(["POST"]) def testfunc(request): if request.method == 'POST': x = request.body.decode('utf-8') print(x) return JsonResponse(x,safe=False) i want to place this into a dictionary with the first row being the key and the remaining rows being the values, so they can be further processed. -
Django - How to reach relational field
I have Patient model which has many to many relation with ICF model. ICF model has many to one field to Unite model. In Unite model I have Unite names. I want to reach Unite names that are assigned to Patient with relations. I try to reach Unite names for each Patient. If it is more than one I cannot list them for that person. Here are my codes. This is my patient model. class Patient (models.Model): id = models.AutoField(primary_key=True) name = models.CharField(max_length=255) lastname = models.CharField(max_length=255, default="doe") data = models.JSONField() Intensivecare_form = models.ManyToManyField(Intensivecare_Form) isDeleted = models.BooleanField(default=False) This is my ICF model. class Intensivecare_Form (models.Model): id = models.AutoField(primary_key=True) hospitals_id = models.ForeignKey(Hospital, on_delete=models.CASCADE) formname = models.CharField(max_length=128) data = models.JSONField() unites_id = models.ForeignKey(Unite, on_delete=models.CASCADE) At last, This is my Unite model class Unite (models.Model): id = models.AutoField(primary_key=True) unitename = models.CharField(max_length=128) In my views.py file I have a function as below def listPatients(request): Patients = Patient.objects.all() output = [] for patient in Patients: unitename = [] icfinfo = serializers.serialize('json', patient.Intensivecare_form.all()) jsonicfinfo = json.loads(icfinfo) unitename.append(jsonicfinfo) output.append({'id': patient.id, 'fname': patient.name, 'lname': patient.lastname, 'data': patient.data, 'unitename': unitename, }) return JsonResponse(output, safe=False) -
Create superuser programmatically inside dockerized Django app
I have the following code in my Django apps.py file: from django.apps import AppConfig import logging from django.contrib.auth import get_user_model from django.utils.translation import gettext_lazy as gettext class SemanticSearchConfig(AppConfig): name = "semantic_search_demo" label: str = "policy" verbose_name: str = gettext("Policies") @classmethod def ready(cls): user_model = get_user_model() log = logging.getLogger(cls.label) try: if not user_model.objects.filter(username="admin").first(): log.info("Creating default superuser with user and password: admin") user_model.objects.create_superuser('admin', 'admin@admin.admin', 'admin') except Exception: log.warning( "Found an error trying to create the superuser, if you aren't " "running the user model migration yet, ignore this message" ) The code is executed beautifully when I run in the debugger. However, when I deploy this inside a docker I get the exception. How do I avoid this? How do I automate the migration? I have no other dat models/migrations. -
Django annotate value based on another model field
I have these two models, Cases and Specialties, just like this: class Case(models.Model): ... judge = models.CharField() .... class Specialty(models.Model): name = models.CharField() sys_num = models.IntegerField() I know this sounds like a really weird structure but try to bare with me: The field judge in the Case model refer to a Specialty instance sys_num value (judge is a charfield but it will always carries an integer) (each Specialty instance has a unique sys_num). So I can get the Specialty name related to a specific Case instance using something like this: my_pk = #some number here... my_case_judge = Case.objects.get(pk=my_pk).judge my_specialty_name = Specialty.objects.get(sys_num=my_case_judge) I know this sounds really weird but I can't change the underlying schemma of the tables, just work around it with sql and Django's orm. My problem is: I want to annotate the Specialty names in a queryset of Cases that have already called values(). I only managed to get it working using Case and When but it's not dynamic. If I add more Specialty instances I'll have to manually alter the code. cases.annotate( specialty=Case( When(judge=0, then=Value('name 0 goes here')), When(judge=1, then=Value('name 1 goes here')), When(judge=2, then=Value('name 2 goes here')), When(judge=3, then=Value('name 3 goes here')), ... Can this be … -
How to submit with radio button selected item?
I am new to django. I tried to submit the radio button selected value. by click submit button. <div class="row mx-auto"> {% for item in object_list %} <div class="containermac mt-sm-5 my-1"> <div class="question ml-sm-5 pl-sm-5 pt-2"> <div class="py-2 h5"><b>Q. {{item.title}}</b></div> <div class="ml-md-3 ml-sm-3 pl-md-5 pt-sm-0 pt-3" id="options"> <label class="options">{{item.option1}} <input type="radio" name="radio"> <span class="checkmark"></span> </label> <label class="options">{{item.option1}} <input type="radio" name="radio"> <span class="checkmark"></span> </label> <label class="options">{{item.option2}} <input type="radio" name="radio"> <span class="checkmark"></span> </label> <label class="options">{{item.option3}} <input type="radio" name="radio"> <span class="checkmark"></span> </label> </div> </div> <div class="d-flex align-items-center pt-3"> <div class="ml-auto mr-sm-5"> <button class="btn btn-success">Submit</button> </div> </div> </div> {% endfor %} </div> -
Mutate and query multiple apps having same database schema in GraphQL Django app
I am new to django and graphQL. Am working with 2 databases which have exact same schema. Problem is - My query and mutations are executing only on one database. Am trying to code an backend where: My news article (Id,FullDescription) resides in TestDb. So, I need to mutate and query TestDb. I process them (lower case conversion + remove punctuations) and store them in OutDb. Similarly, I need to mutate and query OutDb. I have correctly configured ops with 2 database using dbrouters. My driver App is NewsArticle and I implemented 2 Django Apps for handling 2 db TestReadDb and TestWriteDb ## `TestReadDb/models.py`## ------------ from djongo import models # Create your models here. class TestDb(models.Model): _id = models.CharField(max_length=300, primary_key=True) FullDescription = models.TextField(blank=False) class Meta: db_table = 'input_triples_collection' indexes = [models.Index(fields=['_id', 'FullDescription']),] And ## `TestWriteDb/models.py`## ------------ from djongo import models # Create your models here. class OutDb(models.Model): _id = models.CharField(max_length=300, primary_key=True) FullDescription = models.TextField(blank=False) class Meta: db_table = 'output_triples_collection' indexes = [models.Index(fields=['_id', 'FullDescription']),] As can be seen, schema for both databases is exactly same. I defined individual GrahpQL types, queries, mutations for both apps. For e.g. queries look like: ## `TestReadDb/queries.py`## ------------ import graphene from test_read_db.types import FullDescriptionTestDbType from test_read_db.models … -
Django tests failing after unique_together error catch
Writing my tests for a certain part of my Django application I am trying to test if a unique_together error message pops up on my API. This is the test I am running: re = self.c.patch('/api/me/dashboards/' + str(default_id) + '/', {'widgets': [{ 'name': 'Testwidget 2', 'type': 1, 'coord_x': 1, 'coord_y': 1 }]}, content_type='application/json') self.assertEqual(500, re.status_code) self.assertEqual( re.content, b'{"message":"UNIQUE constraint failed: dashboard_widget.coord_x, dashboard_widget.coord_y, dashboard_widget.dashboard_id","status":500,"error":true,"detail":""}') It works fine, but after that no matter whicht test I am running it states django.db.transaction.TransactionManagementError: An error occurred in the current transaction. You can't execute queries until the end of the 'atomic' block. If I remove all tests after this, there is no error message or similar. The API endpoint works otherwise, it is just the test that messes up. Also I did this with a similar test, which should raise a Validationerror and this test behaves the same: Everything is fine but the subsequent test is failing with the error. -
How to get a user's activity history in Django?
I need to show a page of all the actions a user has done in my system (so their manager's can see what they've been doing, basically). I have used Django-Reversion on previous projects but all I can really find in the docs/googling etc is for getting the history of changes to a particular object. I.e. not the changes that a particular user has done to several objects (of a variety of models). Does anybody know of a way to maybe say, .filter(user=request.user) on all versions (regardless of model) in the DB? Or even better, just a related name so maybe request.user.versions. The only methods I see are get_for_object() and get_for_model(). I suppose what I'd like is something like get_for_user() Also, might django-simple-history be better for this? -
How do I access my django app on other devices in my environment using some custom domain?
I have a django app which I hosted locally on my system, now since other devices are connected and on the same local network as my django app, they too are able to access the website by typing the ipaddress:port of my django app host device. But I wanted those devices also to access my django app using some domain name, but it's not working. Here is what I tried. Edited the hosts file on windows and added 127.0.0.1 anythingyoulike.com 127.0.0.1 www.anythingyoulike.com 127.0.0.1. blog.anythingyoulike.com added our custom domain to the allowed host on our settings.py ALLOWED_HOSTS = ['www.anythingyoulike.com', 'blog.anythingyoulike.com', 'anythingyoulike.com'] But other devices on my hotspot network are unable to access using these domain names, and only my devices where I hosted my django website is able to access it. Note : There are Android mobile devices too where I want to access using domain name on my local environment -
Django re-calculate column on model anytime a new model is created or an existing is saved
I have a model that has an aggregate field on it. I'd like to recalculate the agg field whenever the model is updated, or calculate it initially if the model is being created. model (Just as an example): class FooBar(models.Model): id = models.BigAutoField(primary_key=True) name = models.TextField(blank=True, null=True) last_active_date = models.DateTimeField(blank=True, null=True) agg_field = models.DateTimeField(blank=True, null=True) Where the agg_field should be a method such as (This could be anything, just wrote this as an example): FooBar.objects.filter('last_active_date__gt': datetime.now() - timedelta(days=1)).annotate(Count('pk'))) So essentially every time the model is updated or created, it should recalculate this column -
Devspace deploy error: pullSecrets[0].registry: cannot be empty
I'm studying how to deploy a django application with kubernetes, I found this tutorial, which explains about the Devspace tool, so that following the tutorial just like it returns me a message that I can't solve. the message is this: returns only this [fatal] pullSecrets[0].registry: cannot be empty Can someone help me ? -
HTML5 Video tag not showing on Iphone Safari. like the video isn't loading
I am using Django. This is my code. The video is in mp4 format. <video autoplay loop muted playsinline class="mt-5" style="width:100%;margin:0 auto;"> <source src="{{ project.secondary_video_mobile.url }}" type="video/mp4"> </video> Is it something with apple devices? or any workaround for this issue? Note: i tried adding controls and preload="metadata" and didn't work. -
Getting Employee ID from Azure AD
I am able to retrieve the Job Title, Department. I want to be able to retrieve the Employee ID. As shown in the second image, I need to know the parameters to get the Employee ID. This is my HTML. <p>{{user.employee id}} </p> -
ThreadPoolExecutor results not aggregating properly
I'm trying to download multiple files at once in a Django (3.1.x) application, compiling the results to operate on later. I have this simple routine that downloads a file: import requests import tempfile def download_file(url): response = requests.get(url, stream=True, timeout=10) if(response.status_code == 200): ntf = tempfile.NamedTemporaryFile(delete=False) for chunk in response.iter_content(32768): ntf.write(chunk) ntf.flush() ntf.close() return ntf else: response.raise_for_status() Here's the core of the code that calls this method: from concurrent.futures import ThreadPoolExecutor, as_completed urls = [ "https://www.example.com/1.jpg", "https://www.example.com/2.jpg", # ... others ... ] external_map = {} with ThreadPoolExecutor() as executor: downloads = {executor.submit(download_file, url): url for url in urls} for download in as_completed(downloads): url = downloads[download] try: data = download.result() external_map.setdefault(url, data) except Exception as e: print(f"Failed to download {url}: {e}") print(external_map) When I run this code locally, the final print statement shows an empty dict for the external_map variable. Shouldn't there be two entries in it? My expectation after running the threads is that the resulting dict would look like: external_map = { 'https://example.com/1.jpg': NamedTemporaryFile<abc>, 'https://example.com/2.jpg': NamedTemporaryFile<def>, } What am I doing wrong? Could the toy Django webserver (python manage.py runserver) be messing with the results somehow? -
How can I check User Input value again Django Models and Forms
I don't know how to actually write the logic but I want to check user inputs especially price form field against Product model (price property). I have model the django form as below: class SalesForm(forms.ModelForm): class Meta: model = Sales fields = ['product', 'customer', 'quantity', 'price'] Here is the Product Model class Product(models.Model): name = models.CharField(max_length=100, null=True) category = models.CharField(max_length=100, choices=CATEGORY, null=True) cost = models.PositiveIntegerField(null=True) price = models.PositiveIntegerField(null=True) quantity = models.PositiveIntegerField(null=True) Here is what I am trying to do logically in views.py def user_add_sales(request): sales = Sales.objects.all().order_by('-salesdate')[:5] if request.method == 'POST': sales_form = SalesForm(request.POST) if sales_form.is_valid: sales_price = sales_form.cleaned_data('price') try: user_input = Product.objects.get(price = sales_price) sales_form.save() messages.success(request, 'Sales Added Successfully') return redirect('dashboard-user-sales') except user_input.DoesNotExist: sales_form = SalesForm() else: sales_form = SalesForm() context = { 'sales' : sales, 'sales_form' : sales_form, } return render(request, 'dashboard/user_sales.html', context) When Try running the code, says 'SalesForm' object has no attribute 'cleaned_data'. Someone should please help.