Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
cannot import name 'S3' from 'froala_editor'
I am trying to generate a hash value for the folder on Amazon S3 with a package called "Froal_editor" in Django. I am following this tutorial. After everything is setup I installed Froala_Editor with command pip install django-froala-editor which successfully installed the package. I am facing the error cannot import name 'S3' from 'froala_editor when I am trying to import from froala_editor import S3 Any help in this regard would be highly appreciated. -
yaml field formatting display in Django admin pane
I want to display the field in yaml formatting in Django admin. Is there a way to achieve this? I tried exploring but didn't find much about yaml field in Django -
Django: To add a Link to custom page from Django admin form of a model
I want to add a link in admin/seo/seolist/1/change/ form which redirect to a custom html select_page.html and selects an input. -
Filter Dropdown based on Logged in User
I have models as below models.py user = models.OneToOneField(User, null=True, on_delete=models.CASCADE) firstname = models.CharField(max_length=100) lastname = models.CharField(max_length=100) email = models.EmailField() role_id = models.ForeignKey("Role",on_delete=models.SET_NULL,null=True,related_name="role_id", default=1) lead_id = models.ForeignKey("Employee",on_delete=models.SET_NULL,null=True,related_name="parent_id" ,default=1) department_id = models.ForeignKey("Department" ,on_delete=models.SET_NULL,null=True,default=1) team_id = models.ForeignKey("Team" ,on_delete=models.SET_NULL,null=True,default=1) class Timesheet (models.Model): date = models.DateField(auto_now=True) Task = models.TextField(null=True) employee = models.ForeignKey("Employee",on_delete=models.SET_NULL,null=True ) supervisor = models.ForeignKey("Employee",on_delete=models.SET_NULL,null=True,related_name="supreviosr") my filters.py class TimesheetFilter(django_filters.FilterSet): class Meta: model = Timesheet fields= ['employee'] when a lead logged in , i want lead's employee's to be shown on django's filter dropdown box (this where i am stuck) 2.based on selected employees filter a table(was able to achieve this) looked at this How do I filter values in a Django form using ModelForm? wondering if i can apply same approach for my requirement, any suggestions would be much appreciated Thank you. -
Is the server running on host "localhost" (127.0.0.1)
I am deploying a django app for the first time to Heroku. I used the following: heroku run python manage.py migrate and it returns : Traceback (most recent call last): File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 217, in ensure_connection self.connect() File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/base/base.py", line 195, in connect self.connection = self.get_new_connection(conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/django/db/backends/postgresql/base.py", line 178, in get_new_connection connection = Database.connect(**conn_params) File "/app/.heroku/python/lib/python3.6/site-packages/psycopg2/__init__.py", line 122, in connect conn = _connect(dsn, connection_factory=connection_factory, **kwasync) psycopg2.OperationalError: could not connect to server: Connection refused Is the server running on host "localhost" (127.0.0.1) and accepting TCP/IP connections on port 5432? In my settings.py i have : DATABASES = { 'default': dj_database_url.config( default=config('DATABASE_URL') ) } and at the bottom : try: from .local_settings import * except ImportError: pass in the local_settings.py I have : DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql_psycopg2', 'NAME': 'newapp_development', 'USER': 'postgres', 'PASSWORD': '#####', 'HOST': 'localhost', 'PORT': '5432', } } Do you know why is the error message please ? Also, note that local_settings is added to . gitignore. Thank you for your help. -
How to solve the error while building a VueJS project?
I am using VueJS for front-end and Django on back-end. For production I moved all my VueJS compiled bundel to Static/dist in django. And I blocked the content of index.html in VueJS to base.html in django. And changed the url.py such that when localhost:8000 is called it gives base.html which gives index.html of VueJS. When I am trying to build using npm run buid it is throwing errors as shown ERROR Build failed with errors. npm ERR! code ELIFECYCLE npm ERR! errno 1 npm ERR! e_cell_frontend@0.1.0 build: `vue-cli-service build` npm ERR! Exit status 1 npm ERR! npm ERR! Failed at the e_cell_frontend@0.1.0 build script. npm ERR! This is probably not a problem with npm. There is likely additional logging output above. npm ERR! A complete log of this run can be found in: npm ERR! /home/vagrant/.npm/_logs/2021-08-05T04_54_44_578Z-debug.log The log file is as shown: 0 info it worked if it ends with ok 1 verbose cli [ '/usr/bin/node', '/usr/bin/npm', 'run', 'build' ] 2 info using npm@6.14.4 3 info using node@v10.19.0 4 verbose run-script [ 'prebuild', 'build', 'postbuild' ] 5 info lifecycle e_cell_frontend@0.1.0~prebuild: e_cell_frontend@0.1.0 6 info lifecycle e_cell_frontend@0.1.0~build: e_cell_frontend@0.1.0 7 verbose lifecycle e_cell_frontend@0.1.0~build: unsafe-perm in lifecycle true 8 verbose lifecycle e_cell_frontend@0.1.0~build: PATH: /usr/share/npm/node_modules/npm-lifecycle/node-gyp-bin:/home/vagrant/VueJS/e_cell_frontend/node_modules/.bin:/home/vagrant/.vscode-server/bin/c3f126316369cd610563c75b1b1725e0679adfb3/bin:/home/vagrant/.local/bin:/home/vagrant/.vscode-server/bin/c3f126316369cd610563c75b1b1725e0679adfb3/bin:/usr/local/sbin:/usr/local/bin:/usr/sbin:/usr/bin:/sbin:/bin:/usr/games:/usr/local/games:/snap/bin … -
Django.db.models.deletion related_objects takes 3 positional arguments
I'm upgrading my project from Django 2.2 to 3.2 and wracking my brain at what seems to be a bug in their code. I have a test that does a simple DELETE request to a resource (incidentally a DjangoRestFramework resource), and a crash happens inside django.db.models.deletion. here is the relevant part of the stack trace: self = <django.db.models.deletion.Collector object at 0x7f7870265ac8> objs = [<Category: Test category 0>], source = None, nullable = False collect_related = True, source_attr = None, reverse_dependency = False keep_parents = False, fail_on_restricted = True def collect(self, objs, source=None, nullable=False, collect_related=True, source_attr=None, reverse_dependency=False, keep_parents=False, fail_on_restricted=True): """ Add 'objs' to the collection of objects to be deleted as well as all parent instances. 'objs' must be a homogeneous iterable collection of model instances (e.g. a QuerySet). If 'collect_related' is True, related objects will be handled by their respective on_delete handler. If the call is the result of a cascade, 'source' should be the model that caused it and 'nullable' should be set to True, if the relation can be null. If 'reverse_dependency' is True, 'source' will be deleted before the current model, rather than after. (Needed for cascading to parent models, the one case in which the cascade … -
Can foreign key take up value other then choice?
I am having trouble with the foreign key I created. I need some advice/help from the pros out here. I have an app using django. And inside there is a tab called 'Add Device'. This tab's job is generate a form to add new device using 2 models in the same form into the SQL DB which is created. The following are the codes I have coded: models.py class Device(models.Model): hostname = models.CharField(max_length=50) ipaddr = models.CharField(max_length=15) date_added = models.DateTimeField(default=timezone.now) def __str__(self) return self.hostname class DeviceDetail(models.Model): hostname = models.ForeignKey(Device, on_delete=models.CASCADE) mgt_interface = models.CharField(max_length=50) mgt_ip_addr = models.CharField(max_length=30) subnetmask = models.CharField(max_length=30) ssh_id = models.CharField(max_length=50) ssh_pwd = models.CharField(max_length=50) enable_secret = models.CharField(max_length=50) device_model = models.CharField(max_length=50) def __str__(self): return self.hostname views.py def device_add(request): if request.method == "POST": device_frm = DeviceForm(request.POST) ##Part A1 dd_form = DeviceDetailForm(request.POST) if device_frm.is_valid(): device_frm.save() deviceid = Device.objects.aggregate(Max('id'))['id__max'] device = Device.objects.all() ##Part A1 if dd_form.is_valid(): deviceD = dd_form.save(commit=False) deviceD.device = Device.objects.get(id=deviceid) deviceD.save() else: print(dd_form.errors) return render(request, 'interface/device_added.html',{'devices':device}) forms.py class DeviceForm(ModelForm): class Meta: model= Device fields= ['hostname', 'ipaddr'] class DeviceDetailForm(ModelForm): class Meta: model= DeviceDetail fields= ['hostname', 'ssh_id','ssh_pwd', 'mgt_interface', 'mgt_ip_addr', 'subnetmask','enable_secret','device_model'] The above codes is workable if my foreign key is device_model. But the problem is this foreign key, it links up the table together … -
Understanding post_save and m2m_changed signals in Django(2.2)
I have a notifications model in Django with a ManyToMany field related to Users. The idea I had was that I would assign all users to a notification on its' creation, then individual users who cleared that notification on the frontend would be removed from the M2M relationship on the backend. Once the notification had no more users within its' M2M field, the instance would delete itself. Initially, I tried assigning all users to a notification within its' post_save signal: @receiver(post_save, sender=Notification) def contract_post_save(sender, instance, created, **kwargs): from core.api.serializers import NotificationSerializer if created: users = User.objects.all() instance.users.add(*users) return Ofcourse the M2M relations I added didn't save which I found from StackOverflow was because "M2Ms are saved after instances are saved and thus there won't be any record at all of the m2m updates" and I would have to use the m2m_changed signal instead. So I added this signal to see what data would come through (I didn't make any changes to the post save signal above): @receiver(m2m_changed, sender=Notification.users.through) def test(sender, instance, action, reverse, model, pk_set, **kwargs): print(sender) print(instance) print(action) print(reverse) print(model) print(pk_set) The actions that trigger the m2m_changed signal are pre_remove and post_remove, and the pk_set contains all of my … -
How can I show only one author (who has logged in) instead of list of all the authors, while creating post?
I am new to django. I am creating a blog project where the user who has logged in can create post. The problem that i am facing is, i am getting a list of all logged-in authors while i want option of only author who has just logged in. see this pic of create post page- Please help me with this. Below are my Codes - #models.py from django.db import models from django.contrib.auth.models import User from django.shortcuts import render, get_object_or_404, redirect from django.http import HttpResponseRedirect, HttpResponse from django.urls import reverse from django.conf import settings from django.utils import timezone from ckeditor.fields import RichTextField # Create your models here. class Post(models.Model): author = models.ForeignKey('auth.User',on_delete=models.CASCADE,blank=False,null=True) title = models.CharField(max_length=200) header_image = models.ImageField(blank = True, null=True, upload_to="images/") text = RichTextField(blank=True, null=True) created_date = models.DateTimeField(blank = True, null= True) published_date = models.DateTimeField(default=timezone.now) likes = models.ManyToManyField(User, related_name='blog_posts') def get_absolute_url(self): return reverse("blog:post_detail", kwargs={'pk':self.pk}) def total_likes(self): return self.likes.count() def approve_comments(self): return self.comments.filter(approved_comment=True) # from total comments on post , only approved comments will be filtered and returned (shown on blog ), unapproved comments will be rejected. def publish(self): self.published_date = timezone.now() # self - connects method and its arguments to instance of a class. self.save() def __str__(self): return self.title … -
I cannot set a value to django-select2 ModelSelect2Widget using val() function
In my django app I have a CenterModel and a ProvinceModel, each center has a province_id field. I have define a form for Center using ModelSelect2Widget (django_select2) for province_id. I want to set the selected value to the province_id field in the template using javascript but the following code is not working: $("#id_province_id").val(response.province_id) $('#id_province_id').trigger('change'); but these lines are not working, they are NOT setting the value to the province_id field. Instead if the field has some previosly selected value the '.val()' funtion clears that value. I double checked and the response.province_id is storing a valid province id. Why I cannot set a value to the selct field? I am working with django-select2==7.7.1 class CenterModel(models.Model): name = models.CharField(verbose_name=_("Nombre"), max_length=50, unique=True,blank=False, null=False) province_id = models.ForeignKey("ProvinceModel", verbose_name=_("Provincia"), blank=True, null=True, on_delete=models.SET_NULL, related_name="centers") municipality_id = models.ForeignKey("MunicipalityModel", verbose_name=_("Municipio"), blank=True, null=True, on_delete=models.SET_NULL, related_name="centers") from django_select2.forms import ModelSelect2Widget class CenterForm(forms.ModelForm): class Meta: model = CenterModel exclude = ("id",) widgets = { 'name':forms.TextInput(attrs={'class': 'form-control'}), 'province_id' : ModelSelect2Widget(model=ProvinceModel, queryset=ProvinceModel.objects.filter(), search_fields=['des_prov__icontains'], attrs={'style': 'width: 100%;'}), 'municipality_id' : ModelSelect2Widget(model=MunicipalityModel, queryset=MunicipalityModel.objects.filter(), search_fields=['municipio__icontains'], dependent_fields={'province_id': 'cod_prov'}, attrs={'style': 'width: 100%;'}), } -
Integration between google maps and django
I 'm working on a django app based on location where I 've a model shop like this : class Shop(models.Model): name = models.CharField(max_length=200) address = models.CharField(max_length=100) city = models.CharField(max_length=50) location = gis_models.PointField(u"longitude/latitude", geography=True, blank=True, null=True) suppose that in my views i 've a function that filter the db based on a location (long , lat) and rener nearby shops , i will use google maps api here to render a map and show center based on the sent (long , lat) and markers for the nearby shops , now i want to enable the user to change the location on the map by drag and set a new center and listen to this in my view to run filter again and apply changes ? any help for this , thanks . -
message:New application object missing required attributes
the error I got in the wfastcgi-enable query is as follows C:\Users\Administrator>wfastcgi-enable ERROR ( message:New application object missing required attributes. Cannot add duplicate collection entry of type 'application' with combined key attributes 'fullPath, arguments' respectively set to 'c:\python39\python.exe, c:\python39\lib\site-packages\wfastcgi.py' . ) An error occurred running the command: ['C:\Windows\system32\inetsrv\appcmd.exe', 'set', 'config', '/section:system.webServer/fastCGI', "/+[fullPath='c:\python39\python.exe', arguments='c:\python39\lib\site-packages\wfastcgi.py', signalBeforeTerminateSeconds='30']"] -
How can I upload text and file in Django Rest Framework
I am trying to upload both text data and a file to django server using angular for the front-end, here is my models in django #models.py class UploadChapter(models.Model): chapter_number = models.CharField(max_length=50, choices=chapters) chapter_file = models.FileField(upload_to="files") student = models.ForeignKey(User,on_delete=models.CASCADE) supervisor = models.ForeignKey(Supervisor, on_delete=models.CASCADE) status = models.CharField(max_length=100, choices=status, default="Pending") def __str__(self): return f'{self.student} - {self.chapter_number}' for the serializer I wrote this code #serializers.py class UploadChapterSerializer(serializers.ModelSerializer): class Meta: model = UploadChapter fields = ['chapter_number', 'chapter_file', 'student', 'supervisor', 'status'] and for the views i wrote this code #views.py @csrf_exempt def ChapterApi(request, id=0): if request.method=='GET': chapters=UploadChapter.objects.all() chaptersSerializer=UploadChapterSerializer(chapters, many=True) return JsonResponse(chaptersSerializer.data, safe=False) elif request.method=='POST': chaptersData=JSONParser().parse(request) chaptersSerializer=UploadChapterSerializer(data=chaptersData) if chaptersSerializer.is_valid(): chaptersSerializer.save() return JsonResponse('Added Successfully', safe=False) return JsonResponse('Failed', safe=False) so am getting errors from the JSONParser and I really dont know how to do this, I need help please -
Docker Image > 1GB in size from python:3.8.3-alpine
I'm pretty new to docker and, although I've read lots of articles, tutorials and watched YouTube videos, I'm still finding that my image size is in excess of 1 GB when the alpine image for Python is only about 25 MB (if I'm reading this correctly!). I'm trying to work out how to make it smaller (if in fact it needs to be). [Note: I've been following tutorials to create what I have below. Most of it makes sense .. but some of it feels like voodoo] Here is my Dockerfile: FROM python:3.8.3-alpine ENV PYTHONDONTWRITEBYTECODE 1 ENV PYTHONUNBUFFERED 1 RUN mkdir -p /home/app RUN addgroup -S app && adduser -S app -G app ENV HOME=/home/app ENV APP_HOME=/home/app/web RUN mkdir $APP_HOME RUN mkdir $APP_HOME/staticfiles RUN mkdir $APP_HOME/mediafiles WORKDIR $APP_HOME RUN pip install --upgrade pip COPY requirements.txt . RUN apk update \ && apk add --virtual build-deps gcc python3-dev musl-dev \ && apk add postgresql-dev \ && apk add jpeg-dev zlib-dev libjpeg \ && apk add --update --no-cache postgresql-client RUN pip install -r requirements.txt RUN apk del build-deps COPY entrypoint.prod.sh $APP_HOME COPY . $APP_HOME RUN chown -R app:app $APP_HOME USER app ENTRYPOINT ["/home/app/web/entrypoint.prod.sh"] Using Pillow and psycopg2-binary has caused a world of … -
Django deployment with Zappa - root URL is wrong
I have successfully set up a Django app following a Zappa tutorial I found. However, the problem is that Zappa deploys my app to the location: https://some-aws-address/devel where "devel" is the name of my particular Zappa deployment. The problem with this is that, at this position, I have pages that have links on them beginning with a '/' that map to: https://some-aws-address/ and not (as I would want): https://some-aws-address/devel For example, in one of my template files I have a link on an image: <a href="/"><img src="{% static 'images/main/ryzosens-logo-white-background.png' %}"></a> where the href="/" always maps to https://some-aws-address/ I don't want to have to do some hack to get my root URLS to map to https://some-aws-address/devel, so the question is: What must I have in my Django settings (or elsewhere) so that my URL root '/' maps to the HTTP endpoint that Zappa creates? Many thanks in advance! -
How to query records from a nested M2M field in Django?
I'm trying to understand how to get a QuerySet for a nested ManyToMany relationship in Django. Imagine models that look something like this: class Collection: ...fields... class Group: collections = ManyToMany(Collection) class Account: groups = ManyToMany(Group) I can't quite figure out how to query all of the collections for a given account. E.g. something similar to: account.groups.all().values('collections') But the above query gives me a generic QuerySet of just the PKs of the collections, and I'd like a CollectionQuerySet containing the full models. -
Django DRF: How to get a file response from a post request
I want to post an image and receive a file containing the OCR result of that image but i m not sure how to do it, i tried to follow the DRF documentations but i m not sure i got it because this is new to me and my first time using django. lass UploadView(viewsets.ModelViewSet): queryset=Uploads.objects.all() serializer_class=UploadSerializer @api_view(['GET', 'POST']) def methodes(self,request,*args,**kwargs): if request.method=='POST': serializer=UploadSerializer(data=request.data) if serializer.is_valid(): serializer.save() queryset=File.objects.filter(id=str(File.objects.latest('created_at'))) file_data=queryset.values('file') serializers=Fileserializers(data=file_data) return Response(serializers.data) return HttpResponse({'message':'error'},status=400) -
Django: Cant Logout of homepage
For some reason I am unable to logout of the homepage("Auditor"), when I click on the Logout button I get the following: As you can see it redirects to Logout, but still stays in the home page. Here is the Views.py from django.shortcuts import render, redirect from django.http import HttpResponse from django.contrib.auth.forms import UserCreationForm from .forms import createUserForm, auditForm from django.contrib.auth import authenticate, login, logout from .models import datas from django.contrib.auth.decorators import login_required from django.contrib import messages @login_required(login_url='Login') def Auditor(request): model = datas.objects.filter(qs_login=request.user) form = auditForm() if request.method == "POST": form = auditForm(request.POST) if form.is_valid(): form.save() # <-- Add this to get the updated data instance context = {'items': model, 'form': form} return render(request, "main/auditform.html", context) @login_required(login_url='Login') def auditFormPage(request, pk): model = datas.objects.filter(qs_login=request.user) form = auditForm() try: data = datas.objects.get(Task_ID=pk) form = auditForm(instance=data) if request.method == 'POST': form = auditForm(request.POST, instance=data) if form.is_valid(): form.save() # <-- Add this to get the updated data instance except datas.DoesNotExist: pass context = { "items": model, "form": form } return render(request, "main/auditform.html", context) def registerPage(request): if request.user.is_authenticated: return redirect('Auditor') else: form = createUserForm() if request.method == "POST": form = createUserForm(request.POST) if form.is_valid(): form.save() user = form.cleaned_data.get('username') messages.success(request, 'Account Successfully Created for: ' + user) … -
Removing brackets and quotes from list in django template?
Context I'm using Django to extract data from an API - which is then presented in a template. The data extracted is a list of genres. The list contains quotes and brackets when used via context. Question How to remove brackets and quotes from list in snippet below? Refer to objects, "genres" and "prodc", in views.py file Refer to context.genres and context.prodc in HTML Snippet Views.py class HomePageView(TemplateView): # template_name = 'home.html' def get(self,request): if 'movie' in request.GET: api_key = xxxx id = request.GET['movie'] url = 'https://api.themoviedb.org/3/search/movie?api_key={}&language=en-US&query={}&include_adult=false' # payload = {'q': , 'appid': 'xxxxxx'} response = requests.get(url.format(api_key,id)) # successful request if response.status_code == 200: # Parse json output for key value pairs tmdb = response.json() # backdrop image -- tmdb for each movie backdrop_path = tmdb['results'][0]['backdrop_path'] url_backdrop = 'https://image.tmdb.org/t/p/original'+backdrop_path # poster image -- tmdb for each movie poster_path = tmdb['results'][0]['poster_path'] url_poster = 'https://image.tmdb.org/t/p/original'+poster_path # 2nd get request for info on individual movie id_1 = tmdb['results'][0]['id'] api_key_1 = xxxx url = 'https://api.themoviedb.org/3/movie/{}?api_key={}&language=en-US' tmdb_1 = requests.get(url.format(id_1,api_key_1)).json() # genres list genres = [] for i in range(len(tmdb_1['genres'])): genres.append(tmdb_1['genres'][i]['name']) eeeee = str(genres)[1:-1] # prod comps list prodc = [] for i in range(len(tmdb_1['production_companies'])): prodc.append(tmdb_1['production_companies'][i]['name']) context = { 'title': tmdb['results'][0]['original_title'], 'overview': tmdb['results'][0]['overview'], 'release_date': tmdb['results'][0]['release_date'], 'vote_average': … -
Django PasswordChangeForm is giving me a alert to select a user to apply changes to. Why?
For some reason it it giving me a pop up alert when I submit this form and asking me which user I should apply this change to and I don't want it to. I just want it to submit and update the form. I'm relatively new to django views.py ''' def passwordChange(request, pk): if request.method == 'POST': form = PasswordChangeForm(request.user, request.POST) if form.is_valid(): user = form.save() update_session_auth_hash(request, user) messages.success(request, 'Your password was successfully updated!') return redirect('home') else: messages.error(request, 'Please correct the error below.') else: form = PasswordChangeForm(request.user) context = { 'form' : form, } return render(request, 'resturant/password_change.html', context) ''' urls.py ''' urlpatterns = [ path('', views.home, name='home'), path('menu/', views.menu, name='menu'), path('order/', views.order, name='order'), path('menu/<str:pk>/details', views.menu_details, name="menu_details"), path('login/', views.loginPage, name='login'), path('register/', views.registerPage, name='register'), path('logout/', views.logoutPage, name="logout"), path('<str:pk>/profile', views.userProfile, name="user_profile"), path('menu_adjustment', views.adminMenuItem, name="admin_menu_item"), path('<str:pk>/delete', views.delete_item, name="delete_item"), path('<str:pk>/password_change', views.passwordChange, name='password_change'), ] ''' template - password_change.html ''' {% extends 'resturant/main.html' %} {% load static %} {% load widget_tweaks %} {% block content %} <br> <div class="row"> <div class="col-5" style="margin: auto;"> <div class="card"> <div class="card-title"> <h2 class='text-center mt-2'>Password Change</h2> </div> <div class="card-body"> <form class="" action="" method="post"> {% csrf_token %} <div class="form-group"> <label for="id_old_password1" class='h5'>Old Password</label> {% render_field form.old_password class="form-control" %} </div> <div class="form-group"> <label for="id_new_password1" … -
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>