Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Attempt to write a readonly database Django/Apache2/OperationalError
I am working on a Django app and have deployed it to a Ubuntu Server via AWS. Everything that doesn't require a database insert works fine. But when I try to log in (everytime if someone logs in I am saving the 'last login') an OperationalError appears: Attempt to write a readonly. I already changed the owner of the database and tried also with chmod 666 and chmod 777 but it still doesn't work. Did someone had the same issue and has solved it? Kind regards -
Django commit database changes later on command
I am building an eCommerce website that uses some form of verification as soon as a user upload/edits a product, once the product is updated the database property of the Product model isApproved is set to False, and if it's set to false the product won't show on the site because I set only approved products to be viewed. so how can I make it that when a user edits a product I can see the changes before committing it to the database? so that the previous version of the product is still live? -
deploy django app to heroku -push failed! , App not compatible with buildpack
$ git push heroku master Enumerating objects: 220, done. Counting objects: 100% (220/220), done. Delta compression using up to 4 threads Compressing objects: 100% (217/217), done. Writing objects: 100% (220/220), 1.20 MiB | 270.00 KiB/s, done. Total 220 (delta 62), reused 0 (delta 0), pack-reused 0 remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> App not compatible with buildpack: https://buildpack- registry.s3.amazonaws.com/buildpacks/heroku/python.tgz remote: More info: https://devcenter.heroku.com/articles/buildpacks#detection-failure remote: remote: ! Push failed remote: Verifying deploy... remote: remote: ! Push rejected to shivay-ksk. remote: To https://git.heroku.com/shivay-ksk.git ! [remote rejected] master -> master (pre-receive hook declined) error: failed to push some refs to 'https://git.heroku.com/shivay-ksk.git' -
pipenv creating Pipfile & Pipfile.lock in one-up directory
I am trying to install Django using pipenv. The command used is pipenv install django~=3.1.0 The command is issued in django folder. The command creates files PipFile and Pipfile.lock in Desktop folder instead of Desktop/django folder. How to create PipFile and Pipfile.lock in django folder instead of Desktop folder? Operating system is Windows 10 and python in 3.7. -
Trying to deploy django app to AWS EC2 instance using Gunicorn and Nginx
I'm trying to deploy a django app on AWS EC2 and also using gunicorn and Nginx in the process, I followed this tutorial link. I'm not sure what is going wrong, this is the first time I've used AWS EC2, when I try to launch the IP address of the instance it comes back as: "can't open page because safari can't establish secure connection to the server" in my aws console the EC2 'instance state' shows it's running it has been setup in ubuntu 18.04 , I've also set up security groups in my EC2 instance with http, https, 443, 80, 8000, 5432 and 22 all allowed from any ip address except the 22 which only has my ip address as access. Also in my django app settings 'ALLOWED_HOSTS' , i've added the instance ip address and also '*'. this is my gunicorn.socket file: [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target and my gunicorn service file: [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=djangoadmin Group=www-data WorkingDirectory=/home/ubuntu/djangoapp1 / ExecStart=/home/djangoadmin/pyapps/venv/bin/gunicorn \ --access-logfile - \ --workers 3 \ --bind unix:/run/gunicorn.sock \ djangoapp1.wsgi:application [Install] WantedBy=multi-user.target ngnix conf file : server { listen 80; listen 443; server_name **.***.***.*; location = /favicon.ico { access_log off; log_not_found off; … -
How to properly configure the url for a django/ajax call
This is a vastly simplified version of my app. I am having problems with the url of the ajax call when the home page is reloaded after selecting a colour: the url becomes pages/use-selection/pages/print-time/ instead of pages/print-time/ Can someone please point out the solution? home.html {% block content %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.5.1/jquery.min.js"></script> <h1>{% block title %}Home{% endblock title %}</h1> You have selected: {{ colour }} <p><a href="{% url 'select' %}">Select colour</a></p> <script> document.addEventListener("DOMContentLoaded", (event) => { var colourButtons = document.getElementsByName('colour'); colourButtons.forEach((radioButton) => { radioButton.addEventListener('click', () => { useSelectedUrl(radioButton.value) }); }) $.ajax( { type: "GET", url: "pages/print-time/", cache: false, success: function (context) { } } ); }); function useSelectedUrl(colour) { var href = '/use-selection/colour_text'.replace('colour_text', colour); var return_link = document.getElementById('select'); return_link.href = href; } </script> {% endblock content %} select.html {% block content %} <h1>{% block title %}Select colour{% endblock title %}</h1> <p><input type="radio" name="colour" value="red" checked/>Red</p> <p><input type="radio" name="colour" value="blue" checked/>Blue</p> <p><a id="select" href="{% url 'use-selection' colour='blue' %}">Use selection<a></a></p> <script> document.addEventListener("DOMContentLoaded", (event) => { var colourButtons = document.getElementsByName('colour'); colourButtons.forEach((radioButton) => { radioButton.addEventListener('click', () => { useSelectedUrl(radioButton.value) }); }) }); function useSelectedUrl(colour) { var href = '/use-selection/colour_text'.replace('colour_text', colour); var return_link = document.getElementById('select'); return_link.href = href; } </script> {% endblock content %} urls.py # … -
How to create a function to send emails formatting html message with a variable list?
I am trying to create a function in django to send my HTML email templates with certain variables. Here's what I have so far: from django.core.mail import send_mail from django.template.loader import render_to_string from django.core.mail import get_connection from django.utils.html import strip_tags from otr import settings def send_email(subject, email_template, recipient, username, password, variable_list): html_message = render_to_string(email_template, {'context': 'values'}) for variable in variable_list: html_message.format(variable) plain_message = strip_tags(html_message) recipient = recipient with get_connection( host=settings.EMAIL_HOST, port=settings.EMAIL_PORT, username=username, password=password, use_tls=True ) as connection: send_mail(subject, plain_message, 'Me', [recipient], fail_silently=False, html_message=html_message, connection=connection) Then I want to call this function to be used in different django views like: subject = "My subject" email_template = "emails/followup_email.html" recipient = queryset.customer_email username = username_variable password = password_variable customer_name = "Bob" dear_user = "my_name" phone_number = "1111111111" sincerely_user = "my_name" variable_list = [customer_name, dear_user, phone_number, sincerely_user] send_email(subject, email_template, recipient, username, password, variable_list) I keep getting "Replacement index 1 out of range for positional args tuple", so I am guessing I can't do a for loop in this way to format the HTML email with a list of variables. Does anyone know how to accomplish this a different way? -
django appuser give duplicate key error while creating new superuser
im getting this error while creating new superuser Heres the error: django.db.utils.IntegrityError: duplicate key value violates unique constraint "user_auth_appuser_phone_key" DETAIL: Key (phone)=() already exists. I know it is checking for unique phone number while also considering empty phone value and hence giving this error. my question is how to resolve this Models.py: class AppUser(AbstractUser): user_type = models.PositiveSmallIntegerField(default=1) class Gender(models.IntegerChoices): Male = 1, 'MALE' Female = 2, 'FEMALE' Other = 3, 'OTHER' email = models.EmailField(null=True, blank=True) phone = models.CharField(max_length=15, unique=True) gender = models.PositiveSmallIntegerField(choices=Gender.choices, null=True, blank=True) dob = models.DateField(null=True, blank=True) doa = models.DateField(null=True, blank=True) @property def info(self): from user_auth.serializers import UserSerializer return UserSerializer(self).data @property def token(self): return RefreshToken.for_user(self) -
Django error on connecting to Postgres, unsupported startup parameter: options
On migrate step I get such error django.db.utils.OperationalError: ERROR: unsupported startup parameter: options settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.postgresql', 'OPTIONS': { 'options': '-c search_path=public' }, 'NAME': env.str('DB_NAME'), 'USER': env.str('DB_USER'), 'PASSWORD': env.str('DB_PASS'), 'HOST': env.str('DB_HOST'), 'PORT': env.str('DB_PORT'), 'DISABLE_SERVER_SIDE_CURSORS': True, } } (in options parameter I tried to set default schema to public) -
How to sum variable in a django model
In this example i have the following model in django: class Test(models.Model): name = models.models.ForeignKey('auth.user') amount = models.IntegerField() in this example i have 4 instances: test1 = Test("John",10) test2 = Test("John",20) test3 = Test("Eric, 30) test4 = Test("Eric, 40) what i want is to get a list of tuple, with the user and the total sum of amount. testlist = (("john", 30), ("Eric", 70)) i tried the aggregate method but then i get the total amount of all the instances -
is there an open source to manage workflow of a company with data and userss
Is there an open source platform based on Django to manage data, workflow and users. if there is please mention their name or github link. -
how to send values from nodeMCU to django website
I'm working on nodeMCU with soil moisture sensor and want to show on my django website. I'm very close to it but when i send data from nodeMCU to django server i see http 200 request from both side (from nodeMCU side and dajngo side). But main problem is i can't show real time values to my dajngo webpage. Anyone have knowledge about this, kinldy please share, maybe it will be very helpful for me. Project urls.py from django.contrib import admin from django.urls import path,include urlpatterns = [ path('admin/', admin.site.urls), path('', include('SIS_APP.urls')), #1.nodeMCU hit data on this url path('update', include('SIS_APP.urls')), ] App urls.py from django.contrib import admin from django.urls import path from . import views urlpatterns = [ path('admin/', admin.site.urls), path('', views.index, name='index'), #2.nodeMCU hit data on this url path('update', views.update, name='update'), ] views.py from django.shortcuts import render from django.http import HttpResponse from django.views.decorators.csrf import csrf_exempt # Create your views here. def index(request): return render (request, 'index.html') #this function call when nodeMCU hit this url @csrf_exempt def update(request): value = request.POST.get("httpResponseCode") #this value show "None" on webpage return HttpResponse (value) Nodemcu.ino #include <ESP8266WiFi.h> #include <ESP8266HTTPClient.h> #include <WiFiClient.h> const char* ssid = "****"; const char* password = "*****"; // Domain Name … -
I want to integrate the payment gateway of paytm in a small modal iframe in my project
I'm in a planning phase so i just wanted to see if all the thing that I was thinking can be achieved or not it's just theoretical question and just want your advice on it The thing that I want is that a person should click on a link and a small modal on right side should pop up as shown in the below image Once that is done now i want it to have the payment gateway appear only inside that modal and not in the full view I'm going to start building this project for learning so any help or guidance will be great If possible please add the references as well on how this can be achieved -
ModuleNotFoundError only occurs when starting app in Docker
I am currently experimenting with cookiecutters. I'm creating a template for Django, which is working. The next step is to add a docker container for it. For some reason i get following error when I run docker-compose up (or just start the django app manually from within the container): app_1 | Exception in thread django-main-thread: app_1 | Traceback (most recent call last): app_1 | File "/usr/local/lib/python3.8/threading.py", line 932, in _bootstrap_inner app_1 | self.run() app_1 | File "/usr/local/lib/python3.8/threading.py", line 870, in run app_1 | self._target(*self._args, **self._kwargs) app_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper app_1 | fn(*args, **kwargs) app_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/commands/runserver.py", line 110, in inner_run app_1 | autoreload.raise_last_exception() app_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 76, in raise_last_exception app_1 | raise _exception[1] app_1 | File "/usr/local/lib/python3.8/site-packages/django/core/management/__init__.py", line 357, in execute app_1 | autoreload.check_errors(django.setup)() app_1 | File "/usr/local/lib/python3.8/site-packages/django/utils/autoreload.py", line 53, in wrapper app_1 | fn(*args, **kwargs) app_1 | File "/usr/local/lib/python3.8/site-packages/django/__init__.py", line 24, in setup app_1 | apps.populate(settings.INSTALLED_APPS) app_1 | File "/usr/local/lib/python3.8/site-packages/django/apps/registry.py", line 91, in populate app_1 | app_config = AppConfig.create(entry) app_1 | File "/usr/local/lib/python3.8/site-packages/django/apps/config.py", line 90, in create app_1 | module = import_module(entry) app_1 | File "/usr/local/lib/python3.8/importlib/__init__.py", line 127, in import_module app_1 | return _bootstrap._gcd_import(name[level:], package, level) app_1 | File "<frozen importlib._bootstrap>", line … -
Django displays incorrect template
I'm working on an website where user (if logged in) can perform a calculation and see all of his calculations listed. My website has two groups: Clients and Administrators where Clients are not allowed to see any other members' calculations except their own while Administrators are. Authentication is based on Django's built in User class and for each group I created separate views and templates. Templates have similar behavior but different displaying messages. When Clients want to see their calculations, correct information is displayed but the template rendered is for Administrators rather than for Clients. views.py #Administrators' view function class CalculationListView(generic.ListView): model = Calculation paginate_by = 10 #Users' view function class CalculationsByUserListView(LoginRequiredMixin, generic.ListView): model = Calculation paginate_by = 10 def get_queryset(self): return Calculation.objects.filter(userid=self.request.user) urls.py urlpatterns = [ path('', views.index, name='index'), path('calculations/', views.CalculationListView.as_view(), name='calculations'), path('calculation/<int:pk>', views.CalculationDetailView.as_view(), name='calculation-detail'), ] urlpatterns += [ path('mycalculation/', views.CalculationsByUserListView.as_view(), name='mycalcs'), ] Template names Administrators: calculation_list.html Clients: calculations_user.html test.py def test_calculations_in_list(self): login = self.client.login(username='testuser1', password='1X<ISRUkw+tuK') response = self.client.get(reverse('mycalcs')) # Check our user is logged in self.assertEqual(str(response.context['user']), 'testuser1') # Check that we got a response "success" self.assertEqual(response.status_code, 200) # Check that initially we don't have any calculations in list self.assertTrue('calculation_list' in response.context) self.assertEqual(len(response.context['calculation_list']), 0) # Now assign some calculations … -
Invalid data. Expected a dictionary, but got str : django
I want to create new data on the course model. Some errors like "Invalid data. Expected a dictionary, but got str" occur while trying to get values in the following way, I do not know how to overcome it, give me a solution serializer class CourseSerializer(serializers.ModelSerializer): area = AreaSerializer() sect = SectionSerializers() class Meta: model = Course fields = ( 'name', 'description', 'area', 'sect') Here area is foreignkey field and sect is m2m field -
AUTH_LDAP_HASH_PASSORD DJNAGO
I have a problem with the connection with an LDAP user who has a hashed password. if I change the user's password with raw text the connection is successful but with hash no. this is the code of authentification : logger.info("Trying to authenticate the user %s against the LDAP" % username) user = super(LDAPBackendCustom, self).authenticate(request, username, password, **kwargs) also if I run ldapsearch -H ldap://10.110.0.150 -D "bgleeson@contoso.com" -w 2fourall if the password is in raw text this commande return the user but if it is in hash format the LDAP_SEARCH invalid bind credential -
recording user's post like time
I am building a simple BlogApp and I am trying to record user like post time. I have created a field named like_time But the problem is when user_1 like the post than the time is recorded But when user_2 like than it resets the user_1 time, But i am trying to store different like time of different of different users. models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length-300) likes = models.ManyToManyField(User, related_name='likes') body = models.CharField(max_length=300) like_time = models.DateTimeField(auto_now=True) views.py def blog_post_like(request, blogpost_id): post = get_object_or_404(BlogPost, pk=blogpost_id) if request.user not in post.likes.all(): post.likes.add(request.user) post.like_time = timezone.now() post.save() return JsonResponse({'disp':'success'}) The Problem :- It is resetting every for every user on same post, But I am trying to store different like time for different users, like :- user_1 - liked time - 40 seconds ago user_2 - liked_time - 30 seconds ago Any help would be much Appreciated .Thank You -
That choice is not one of the available choices django
I have a form to update user, the error is on the role field. I am filtering the role based on customer. I am getting the right values for role but anyways the error pops up. Select a valid choice. That choice is not one of the available choices views.py class UserUpdateView(LoginRequiredMixin, SuccessMessageMixin, UpdateView): form_class = UserUpdateForm template_name = 'users/modals/update_profile_modal.html' success_message = "User updated successfully." def get_form_kwargs(self): kw = super().get_form_kwargs() kw['request'] = self.request return kw def get_object(self, *args, **kwargs): user_id = self.request.session['user_detail'] return TbUser.objects.get(id=user_id) def form_invalid(self, form): messages.error(self.request, form.errors) print(form.errors) return redirect('user-detail', pk=self.object.pk) def get_success_url(self): return reverse('user-detail', kwargs={'pk': self.object.pk}) forms.py class UserUpdateForm(forms.ModelForm): email = forms.EmailField() def __init__(self, request, *args, **kwargs): super().__init__(*args, **kwargs) self.request = request if request.user.customer: self.fields['department'].queryset = TbDepartment.objects.filter( customer=request.user.customer) self.fields['role'].queryset = TbRole.objects.filter( customer=request.user.customer) self.fields['username'].required = True self.fields['real_name'].required = True self.fields['email'].required = True self.fields['cellphone'].required = True self.fields['department'].required = True self.fields['role'].required = True class Meta: model = TbUser fields = ['username', 'real_name', 'email', 'cellphone', 'department', 'role'] -
A platform to create a system for managing data and users with proper access to data and related actions
I want to create a website for a company to handle its workflow. The company has some data and its users should work on that. There are some different kind of user such as regular with limited access, manager with full access, expert with some access to data and ... Also they can do something with data and modify data. Also there is a workflow, ie regular user submits a form and manager see the form and add something else to data and pass it to expert and ... Is there a platform to create such a system like CMS platforms? -
DJANGO settings using namedtuple
I want to create a variable of type namedtuple in Django settings: SCHEMA_VERSION: namedtuple = config("SCHEMA_VERSION", cast=namedtuple(typename="SCHEMA_VERSION", field_names=["subject", "schema_id", "version"], defaults=[None, None, None]), default=None) But when I want to use it in code below: result = ujson.loads(result) result = settings.SCHEMA_VERSION(**result) I get the following error: AttributeError: 'Settings' object has no attribute 'SCHEMA_VERSION' Of course, I import Django setting like this: from django.conf import settings What I'm doing wrong? -
Django convert postgresql query with Array and subquery to ORM
The problem is I can't convert this query to Django ORM select weekday, (array( select termdelay from call_schedule_history c_in where c_in.is_active and c.weekday = c_in.weekday order by 1 )) from call_schedule_history c where is_active group by 1, 2 I tried: history_in = History.objects.filter(weekday=OuterRef('pk')) history_out = History.objects.values('weekday').annotate( newest_commenters=ArrayFormat(history_in.values('termdelay')), ) but sql query of history_out is: select "call_schedule_history"."weekday", array(select U0."termdelay" from "call_schedule_history" U0 where U0."weekday" = "call_schedule_history"."id") as "newest_commenters" from "call_schedule_history" So how can I replace "call_schedule_history"."id" to "call_schedule_history"."weekday" in Django ORM? -
django rest framwokr. How i can filter quryset in range?
I need filtering data from get request in range: Here is my code: model.py class MainModel(TimeStampedModel): model_name = models.CharField(_("model_name"), max_length=240) model_price = models.DecimalField(_("model_price"), max_digits=8) class ModelAdditionalData_1(TimeStampedModel): model_id = models.OneToOneField( Model, verbose_name=_('related model'), on_delete=models.CASCADE, related_name='model_water_flow_data1', related_query_name='model_water_flow_data1' ) model_param_1 = models.models.DecimalField(_("model_param_1"), max_digits=8) class ModelAdditionalData_2(TimeStampedModel): model_id = models.OneToOneField( Model, verbose_name=_('related model'), on_delete=models.CASCADE, related_name='model_water_flow_data2', related_query_name='model_water_flow_data2' ) model_param_2 = models.models.DecimalField(_("model_param_2"), max_digits=8) view.py : class ModelsViewSet(ReadOnlyModelViewSet, GenericViewSet): serializer_class = ModelsSerializer def get_queryset(self): model_param_1 = self.request.query_params.get('model_param_1') model_param_2 = self.request.query_params.get('model_param_2') filters = {} if model_param_1: filters['model_water_flow_data1__model_param_1'] = model_param_1 if model_param_2: filters['model_water_flow_data2__model_param_2'] = model_param_2 if filters: return MainModel.objects.filter(**filters) return MainModel.objects.all() How i can apply my filters for filtering data in range? For example, i wont filtering data by model_param_1 betwen 1 and 10. -
UnboundLocalError at /accounts/register/
hi i was trying to check if a user with a same number is in my database , i show a error that this number is exists from before but ... UnboundLocalError at /accounts/register/ forms.py html views.py -
Django - retrieve objects from latest date for each group - PersonPhoto
My DB contains passport images of different people. Something like: class Person(models.Model): pass class PersonPhoto(models.Model): date_captured = models.DateField() person = models.ForeignKey(Person, null=False) I want to extract for each person all of the images from the latest date he was photographed. So if person A has photos from August 5, 5, 9, 11, 11, and person B has images from August 7, 9, 13, 13, 19, 19 then I want to fetch both images from August 11 for person A, and both images from August 19 for person B. The way I'm currently doing that is something like: specific_dates_queryset = Q() for photo in PersonPhoto.objects.all().annotate(max_date=Max('date_captured')).values('person_id'): specific_dates_queryset |= Q(person_id=photo["person_id"], date_captured=photo["max_date"]) for photo in PersonPhoto.objects.filter(specific_dates_queryset).order_by("person_id"): print(f"image for person {photo.person_id}, of date {photo.date_captured}") The idea is to first find the latest date of a photo for each person, and then in a new query to fetch these images for these people from these dates. Is there a simpler solution that does everything within the DB and avoids redundant queries and data fetching?