Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Not being able to send emails on a django backend from a React frontend
On a form submission from my React frontend, my django backend sends emails to multiple user. I am not using any sort of backend queue for the job scheduling (for now), so the request should take little time to complete. Its important to note that I am using axios interceptors for refreshing tokens on a 401 response. Now, the thing is, everytime someone submits the form and there is more than 1 user to send an email to, I get a 401 response to my axios interceptor and it fails. But when there is only 1 user they send an email to, it works fine. I understand this might be hard to visualize without code context, but would really appreciate if someone has any idea as to why this might happen? -
Query of coordinate data in Folium (ClickForMarker)
everyone, I am currently creating a small project with python / django. I would like to develop a tool in which the user can mark a point on a map - and then send it off using the "Remember address" button. This data should then be stored in the database. I use Folium / Leaflet for this. With the function "ClickForMarker" I can already mark points on the map. Now to my question :) Currently, a new marker is placed with each click - however, I would like that if a user clicks several times, the marker is always updated. How can I read out the data (coordinates). Or do I have a "Send data" button below the map - can I process the post request with the data? I don't think I have to mention that I'm still a beginner - with Javascript, for example, I only know very little. I'm happy about any help :) -
Django generic views with form_class and model attributes
In a note about generic views in Django's docs, it says that even if form_class is set, the model attribute should be set too. But I've seen many examples (some on Django docs itself) that only the form_class was specified. Also, inside the ModelFormMixin class (generic views inherit from it) you can find this: if self.form_class: return self.form_class else: if self.model is not None: # If a model has been explicitly provided, use it model = self.model It's in the 'else' that it would look for the model. So for views that inherit from generic views like FormView or CreateView, is it necessary that I set the model attribute if I've set the form_class? If not, then what is that note talking about? -
Django admin LogEntry error with remote authentication
I'm using Central Authentication System (CAS) with my Django services. User is authenticated by remote server and not Django auth itself. I have also changed Authentication Backend as follows : class CASBackend(BaseBackend): def authenticate(self, request, username=None, password=None): payload = get_cas_payload(request) user, _ = User.objects.get_or_create(username=payload['username']) def get_user(self, user_id): try: return User.objects.get(pk=user_id) except User.DoesNotExist: return None When creating a new object in admin, I got the following error : django.db.utils.IntegrityError: null value in column "user_id" violates not-null constraint Which is related to LogEntry. Is there anything I have missed? -
How to Serialize ManyToManyfield in django rest framework
Sorry to ask a repetitive question which is already have been asked a lot of times. I have seen alot of answers on this topic. But I can't reproduce the solution of my problem. Basically I want to serialize a field name partner which is in quote model Quote(models.Model): #... partner = models.ManyToManyField( Partner, blank=True, related_name='quote_partners') and this is the Partner models in the accounts app class Partner(models.Model): id = models.UUIDField(primary_key=True, unique=True, default=uuid.uuid4, editable=False) name = models.CharField(max_length=100, blank=True, null=True) group = models.OneToOneField( Group, on_delete=models.DO_NOTHING, blank=True, null=True) def __str__(self): return self.name And this is how the serializer looks class QuoteListSerializer(serializers.Serializer): """ For the List views """ #... id = serializers.UUIDField(read_only=True) partner = serializers.CharField(read_only=True) I'm getting all other fields properly but not the partner field. This is the end results looks : { "id": "cbf64980-1637-4d0d-ad1f-4eb6421df5a1", "partner": "accounts.Partner.None", }, However I can see the partners field is filled for this specific entry in the admin page but not showing in the serialized data. In the Partner Model In the Quote [][2 Anybody knows why this is happening and how to fix this issue. -
DJANGO IF STATEMENT FOR CONTEXT USAGE IN TEMPLATE
What i am trying to achieve: i am getting data from an API, i want to display that data in my template only if the conditions are met. What i tried #1: i added a boolean in my model that is linked to the API called "accessconfirmed" and then in my views i added a if statement saying if access is confirmed then display this context and if not then display this other context. i dont get an error but my data from the API is no longer displaying, i get nothing. here is the code in the views.py VIEWS: def projectdetailscoins(request, pk): coin = Coin.objects.get(id=pk) notifications = Notification.objects.all() accessconfirmed = Coin.is_api_access api_coin_number_variable = coin.api_coin_number url = 'XXX' parameters = { 'slug': coin.api_slug, 'convert': 'USD', } headers = { 'Accepts': 'application/json', 'X-CMC_PRO_API_KEY': 'XXX' } session = Session() session.headers.update(headers) response = session.get(url, params=parameters) api_price = response.json() if accessconfirmed == True: context = {'coin':coin, 'notifications':notifications, 'gimmeprice':api_price['data'][api_coin_number_variable]['quote']['USD']['price'], 'gimme24h':api_price['data'][api_coin_number_variable]['quote']['USD']['percent_change_24h'], 'accessconfirmed':accessconfirmed, } else: context = {'coin':coin, 'notifications':notifications,} return render(request, 'blog/project_details_coin.html', context) What i tried #2: i also tried changing the if statement from if accessconfirmed == True: to if accessconfirmed: the data displays correctly on my template if i do that, but when i go … -
How to get provider of user in django which registered with django allauth
I am going to get provider of user in django I tried to loop through queryset user.socialaccount_set but got only username of user. Is there are any solution to get provider? -
Using Filter or Q in Aggregation
class Streamer(models.Model): name = models.CharField(max_length=50, null=True) is_working_with_us = models.BooleanField(default=False) class Account(models.Model): streamer = models.ForeignKey(Streamer, on_delete=models.CASCADE) salary= models.Decimalfield(decimal_places=2, max_digits=7) cost= models.Decimalfield(decimal_places=2, max_digits=7) Can I make two different aggregations that depend on attributes in a single query? like below. streamer_salary_stats = Streamer.objects.filter(is_working_with_us=True).aggregate( expensive_streamers_sum=Sum(Q(cost__gt=10000.0),'salary'), # with Q or cheap_streamers_sum=Sum(cost__lte=10000.0,'salary'), # without Q ) I know it can be done this way but want to achieve this in a single query. expensive_streamers_sum = Streamer.objects.filter( is_working_with_us=True, cost__gt=10000.0 ).aggregate(s=Sum('salary'))['s'] cheap_streamers_sum = Streamer.objects.filter( is_working_with_us=True, cost__lte=10000.0 ).aggregate(s=Sum('salary'))['s'] -
Error on Flask request api builtins:ValueError: dictionary update sequence element #0 has length 1; 2 is required
Error when make a request to an Flask Api, this error occurs just sometimes, and the structure of the body it's right Stack trace generated by New Relic **builtins:ValueError: dictionary update sequence element #0 has length 1; 2 is required** File "/venv/lib/python3.9/site-packages/flask/app.py", line 1936, in dispatch_request File "/venv/lib/python3.9/site-packages/newrelic/hooks/framework_flask.py", line 60, in _nr_wrapper_handler_ File "/venv/lib/python3.9/site-packages/maas_security/keycloak.py", line 203, in wrapper File "/venv/lib/python3.9/site-packages/webargs/core.py", line 452, in wrapper File "/venv/lib/python3.9/site-packages/flask_smorest/arguments.py", line 77, in wrapper File "/venv/lib/python3.9/site-packages/flask_smorest/response.py", line 90, in wrapper File "/venv/lib/python3.9/site-packages/marshmallow/schema.py", line 559, in dump File "/venv/lib/python3.9/site-packages/marshmallow/schema.py", line 523, in _serialize File "/venv/lib/python3.9/site-packages/marshmallow/fields.py", line 320, in serialize File "/venv/lib/python3.9/site-packages/marshmallow/fields.py", line 1508, in _serialize -
Django - UserEditView is missing a QuerySet?
trying to create an edit profile for users and i keep getting this error what should i add or change ? is my models right for UserEditView this is my views.py from django.urls import reverse_lazy from django.views import generic from django.contrib.auth.forms import UserCreationForm , UserChangeForm class UserEditView(generic.UpdateView): models = UserChangeForm form_class = UserChangeForm template_name = 'vendor/edit_profile.html' seccess_url = reverse_lazy('vendor_admin') def get_object(self): return self.request.user urls.py from django.urls import path from .import views from .views import UserEditView from django.contrib import admin from django.contrib.auth import views as auth_views urlpattern =[ path('signup/', views.become_vendor, name='become_vendor'), path('profile/', views.vendor_admin, name='vendor_admin'), path("logout/", auth_views.LogoutView.as_view(), name="logout"), path('login/', auth_views.LoginView.as_view(template_name='vendor/login.html'), name='login'), path('edit_profile/', UserEditView.as_view(template_name='vendor/edit_profile.html'), name='edit_profile'), ] edit_profile.html (where the error pops up) {% extends "base.html"%} {% load static %} {% block content %} <title>title</title> <div class="section pt-9 pb-9"> <div class="container"> <div class="row"> <div class="col-md-12"> <div class="section-title"> <div class="wrap-title"> <h3 class="title"> <span class="first-word"></span> </h3> <br> <form method="post" > {% csrf_token %} <table> {{ form.as_p }} </table> <button class='button'>Update</button> </form> </div> <hr> {% endblock content %} -
Django URLs not working properly in template
I am making social network website where user can post and like the post. On one of my templates, image of heart (which represents if post is liked or not) is not loading because of incorrect path: this is the incorrect one: other_profile/static/network/nolike.png. It should be: static/network/nolike.png. other_profile is the name and path of my template. Same happens in case of other API fetch calls on my website. URL should not begin with other_profile. And this happens only on other_profile HTML page. The code: urls.py from django.urls import path from . import views urlpatterns = [ path("", views.index, name="index"), path("profile", views.profile, name="profile"), path("login", views.login_view, name="login"), path("logout", views.logout_view, name="logout"), path("register", views.register, name="register"), path("Post/<str:post_id>", views.likes, name="likes"), path("follows/<str:user_id>", views.follows, name="follows"), path("following", views.following, name="following"), path("other_profile/<str:user_id>", views.other_profile, name="other_profile") ] views.py snippet import json from urllib.request import Request from django.contrib.auth import authenticate, login, logout from django.db import IntegrityError from django.http import HttpResponse, HttpResponseRedirect from django.shortcuts import redirect, render from django.urls import reverse from .forms import NewPostForm, likeForm, followForm from .models import User, Post, Likes, Follows from django.contrib.auth.decorators import login_required from django.http import JsonResponse from django.core.exceptions import ObjectDoesNotExist from datetime import datetime def other_profile(request, user_id): followform = followForm(request.POST or None) if request.method == "POST": try: Follows.objects.filter(following__in=[user_id]).get(following=request.user).delete() except … -
Django Rest Framework AuthToken being created without a key
I have a data migration indended to create a couple accounts in django, along with a token for authentication. class Migration(migrations.Migration): initial = True dependencies = [ migrations.swappable_dependency(settings.AUTH_USER_MODEL), ('api', '0001_initial'), ('authtoken', '0001_initial'), ] operations = [ migrations.RunPython(api.models.user.create_service_accounts, api.models.user.delete_service_accounts), ] And the create method: def create_service_accounts(apps, schema_editor): User = apps.get_model('api', 'User') Token = apps.get_model('authtoken', 'Token') db_alias = schema_editor.connection.alias new_user = User.objects.using(db_alias).create(username='sa', is_superuser=True, is_staff=True) token = Token.objects.using(db_alias).create(user=new_user) After this migration is run, a token is created. But the token does not have a key. Therefore it is useless. Why is it getting created without a key? If I manually create a token it works fine, but through this migration it provides a blank key. -
Base64 Docx to Base64 pdf
Im trying to convert a Base64 Docx to a Base64 pdf, for test purpose im receiving the base64 docx and im saving it in my Django static folder like this: Proyect --App ----static ------Docs --------test.docx So, Im trying with doxc2pdf library to make the convertion and the into base64 like this: class Converttest(View): def post(self, request, *args, **kwargs): template = loader.get_template('home.html') testdoc = static('Docs/test.docx') pdf = convert(testdoc) encoded = base64.b64encode(pdf) context = {} return HttpResponse(template.render(context, request)) But im getting this error: pywintypes.com_error: (-2147221005, 'Invalid class string', None, None) > g:\python_projects\reps\stratos\strategy\views.py(162)post() -> convert(testdoc) Any idea what am I doing wrong ? -
os.environ.setdefault('DJANGO_SETTINGS_MODULE') doesn't work
I'm trying to run a standalone script that uses the Django models for accessing the database. The script is very simple, see below: import sys from manager.models import Playlist from manager.utils import clean_up_playlist, add_record_to_playlist def main(playlist_id, username): playlist = Playlist.objects.get(playlists=playlist_id) # the script does other stuff if __name__ == "__main__": playlist_id = sys.argv[1] username = sys.argv[2] import os os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'SpotifyPlaylistManager.settings') import django django.setup() main(playlist_id, username) The script is in the top folder of the Django folder SpotifyPlaylistManager/ |-SpotifyPlaylistManager/ |-settings.py |-venv |-manage.py |-my_script.py For some reason, if I try to run it with the command below I got the error raise ImproperlyConfigured( django.core.exceptions.ImproperlyConfigured: Requested setting INSTALLED_APPS, but settings are not configured. You must either define the environment variable DJANGO_SETTINGS_MODULE or call settings.configure() before accessing settings. The actual command I need to launch source /home/nicola/PycharmProjects/SpotifyPlaylistManager/venv/bin/activate && python /home/nicola/PycharmProjects/SpotifyPlaylistManager/scheduler.py 6tIMeXF1Q9bB7KDywBhG2P nicoc && deactivate I can't find the issue -
Why does my functions based API POST respond with .accepted_renderer not set on Response
I have a function-based view: api_view(['POST']) def scoring_logicapp_kickoff(request, prediction_id): if request.method == 'POST': url = "https://FAKEURL.net" payload = json.dumps({ "prediction_id": prediction_id }) headers = { 'Content-Type': 'application/json' } requests.request("POST", url, headers=headers, data=payload) return Response(status=status.HTTP_202_ACCEPTED) return Response(status=status.HTTP_400_BAD_REQUEST) FAKEURL is actually a URL that sets off an Azure Data Factory logic app. I originally was getting a 403 error "Forbidden (CSRF cookie not set.)". I then wrapped the URL endpoint to quickly circumvent the issue: path('logicapp-trigger/<int:prediction_id>/', csrf_exempt(views.scoring_logicapp_kickoff)) Now I'm getting the error: "AssertionError: .accepted_renderer not set on Response" Any idea how to fix the original csrf error or the response error? I'm a bit stuck. -
NameError: name 'urlpatterns' is not defined using i18n_patterns
I have problems writing the urls for translation. According to this question I understand that it is because I have += so I need to put this = the bad thing is that I have to translate all my urls I can't leave any outside of i18n, what can I do to include all my urls there? from . import views from django.urls import path from django.conf.urls.i18n import i18n_patterns app_name='Clientes' urlpatterns+= i18n_patterns( path('',views.list_clientes,name='clientes_list'), path('add',views.create_clientes.as_view(),name='clientes_add'), path('edit/<int:pk>',views.edit_clientes.as_view(),name='clientes_edit'), path('<int:pk>/',views.detail_clientes.as_view(),name='clientes_detail'), path('delete/<int:pk>',views.eliminar_cliente.as_view(),name='clientes_delete'), ) -
urllib3.exceptions.ReadTimeoutError: HTTPConnectionPool(host='prod.******', port=9200)
please I have elasticsearch on prod server , i changed all the url on my django project to localhost , but still show me this error ! any solution please ! hellp es = Elasticsearch('http://localhost:9200/') -
How do I upload all the files in a django app to a git brand new repository?
I'm using Django in PyCharm for a simple project. I have a github account, git installed on my environment and github desktop, but I can't figure out how to upload all the files in my entire app project to a git repository all at once, to then view it on github. I haven't been using Git at all throughout the project and it has cost me when making irreversible mistakes. So what's the easiest way to use Git/github with Pycharm. i got the extension for it but I find the interface a bit confusing. -
Django, JWT, React redirect to different page base on different group after log in
I have 2 roles which are member and staff, and i want to redirect to the different pages depend on the users' roles using username and password e.g. after logging in as a member would redirect to member page and as a staff would redirect to onlystaff page. How I can do it. I'm using React Django JWT and Material UI. the code: axios.js const baseURL = 'http://127.0.0.1:8000/api/'; const axiosInstance = axios.create({ baseURL: baseURL, timeout: 5000, headers: { Authorization: localStorage.getItem('access_token') ? 'JWT ' + localStorage.getItem('access_token') : null, 'Content-Type': 'application/json', accept: 'application/json', }, }); axiosInstance.interceptors.response.use( (response) => { return response; }, async function (error) { const originalRequest = error.config; if (typeof error.response === 'undefined') { alert( 'A server/network error occurred. ' + 'Looks like CORS might be the problem. ' + 'Sorry about this - we will get it fixed shortly.' ); return Promise.reject(error); } if ( error.response.status === 401 && originalRequest.url === baseURL + 'token/refresh/' ) { window.location.href = '/login/'; return Promise.reject(error); } if ( error.response.data.code === 'token_not_valid' && error.response.status === 401 && error.response.statusText === 'Unauthorized' ) { const refreshToken = localStorage.getItem('refresh_token'); if (refreshToken) { const tokenParts = JSON.parse(atob(refreshToken.split('.')[1])); const now = Math.ceil(Date.now() / 1000); console.log(tokenParts.exp); if (tokenParts.exp > now) … -
Why is collectstatic only detecting admin static files?
I'm using S3 to store my static files, but I'm having an issue where only the admin static files are uploading to the bucket. I expected to see the css and other folders from inside static upload to the bucket, but instead, this is all I got: static/ - admin/ - flags/ What can I do to get my app's static folder to upload also? Looking at other answers to this question, it seems like the main difference is that my project uses django-sass-processor, but I'm not sure why that would mean my entire folder is not picked up. Project folder structure: backend/ - accounts/ - core/ -- settings.py -- ... - static/ - templates/ settings.py USE_S3 = os.getenv('USE_S3') == 'TRUE' if USE_S3: # aws settings AWS_ACCESS_KEY_ID = os.getenv('AWS_ACCESS_KEY_ID') AWS_SECRET_ACCESS_KEY = os.getenv('AWS_SECRET_ACCESS_KEY') AWS_STORAGE_BUCKET_NAME = os.getenv('AWS_STORAGE_BUCKET_NAME') AWS_DEFAULT_ACL = 'public-read' AWS_S3_CUSTOM_DOMAIN = f'{AWS_STORAGE_BUCKET_NAME}.s3.amazonaws.com' AWS_S3_OBJECT_PARAMETERS = {'CacheControl': 'max-age=86400'} # s3 static settings AWS_LOCATION = 'static' STATIC_URL = f'https://{AWS_S3_CUSTOM_DOMAIN}/{AWS_LOCATION}/' STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' else: STATIC_URL = '/staticfiles/' STATIC_ROOT = os.path.join(BASE_DIR, 'staticfiles') STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.AppDirectoriesFinder', 'sass_processor.finders.CssFinder', ] SASS_PROCESSOR_ROOT = os.path.join(BASE_DIR, 'static') STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'media') -
Split video into images with OpenCV on Django
I am trying to split a video into images. Each image should be store individually into an object "UserCapturedData". At the moment, here is the code i use: cap = cv2.VideoCapture(userData.file.path) while cap.isOpened(): # Extract the frame ret, frame = cap.read() if not ret: continue filename = datetime.now().strftime('%Y.%m.%d.%H.%M.%S') path = "media/"+filename+"-"+str(count+1)+'.jpg' cv2.imwrite(path, frame) # It works until here... tempImageFile = ContentFile(File(open(path,'r'))) # What should i pass here???? UserCapturedData.objects.create(profile=userData.profile, file=tempImageFile) (...) In my case, UserCapturedData.file is : file = models.FileField(_('File'), blank=True) Thanks for your help! -
Dynamic URL Django problems
Im making a journal-program for dental offices, using django. I want to make dynamic URLs for the clinics page and for individual patients aswell. I want the URLs to inherent the id's of both the clinic and patient. The models.py: class klinik(models.Model): klinikid = models.CharField(max_length=200, null=True) class patient(models.Model): id_nr = models.CharField(max_length=200, null=True) The views.py: def klinik(request, k_id): klinikker = klinikker.objects.get(klinik_id=k_id) patients= patient.objects.all() return render(request,'DentHelp/klinik.html', {'patients':patients}) def registering(request, fd): patientsid = patient.objects.get(id_nr=fd) return render(request,'DentHelp/registrering.html') The URLS.py path('klinik/<str:k_id>/', views.klinik), path('registrering/<str:fd>/', views.registering), Something must be right, because the patients page called registrering is loading nicely, however the klinik page says the object hasnt been declared. Do you see any mistakes? -
Omit base resolver edge resolution in an aggregation query
I'm returning aggregate data for a model, I have: Objects { byColor { red blue } } As my query, then in graphene I have: class ObjectsQuery(DjangoObjectType): class Meta: model = Objects def resolve_by_color(self, _): return self.iterable.aggregate(...) I'm having a performance issue because it looks like a query for all Objects is being executed, even though the results of that query aren't included in any edges. Is there a way to avoid this Objects.objects.all() query from running? -
Some task are not processing using Django-Q
I have a django Q cluster running with this configuration: Q_CLUSTER = { 'name': 'pretty_name', 'workers': 1, 'recycle': 500, 'timeout': 500, 'queue_limit': 5, 'cpu_affinity': 1, 'label': 'Django Q', 'save_limit': 0, 'ack_failures': True, 'max_attempts': 1, 'attempt_count': 1, 'redis': { 'host': CHANNEL_REDIS_HOST, 'port': CHANNEL_REDIS_PORT, 'db': 5, } } On this cluster I have a scheduled task supposed to run every 15 minutes. Sometimes it works fine and this is what I can see on my worker logs: [Q] INFO Enqueued 1 [Q] INFO Process-1:1 processing [oranges-georgia-snake-social] [Q] INFO Process-1 created a task from schedule [2] [ My Personal Custom Task Log] [Q] INFO Processed [oranges-georgia-snake-social] But other times the task does not start, this is what I get on my log: [Q] INFO Enqueued 1 [Q] INFO Process-1 created a task from schedule [2] And then nothing for the next 15 minutes. Any idea where this might come from ? -
how to make a post request and get the radio button values in django
I'm doing a website in django but this is the first time i use this framework so i'm not so used to it. I need to save some information on a DB, and i need to take these information from some radio buttons. I tryied so many ways to get the data but nothing worked. So i'd like to ask how to get these data in models.py from a template.html. This is the code in views.py: def question1(request): form = CHOICES(request.POST) if request.method == 'POST': form = CHOICES(request.POST) if form.is_valid(): selected = form.cleaned_data.get("NUMS") return render(request, 'q1.html', {'form': form}) This is the template question1.html: <form class="form-inline" method='POST' action="" enctype='multipart/form-data'>{% csrf_token %} {% csrf_token %} {{form.path}} </form> Then there is the form in forms.py: NUMS = [ ('one', 'one'), ('two', 'two'), ('three', 'three'), ('four', 'four'), ('five', 'fives'), ] class CHOICES(forms.Form): NUMS = forms.ChoiceField(choices=NUMS, widget=forms.RadioSelect) I checked and I think that the problem could be the request.method that is GET insted of POST. So how can I make a POST request? Thank you