Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
ImproperlyConfigured at /api/customereport/
i am getting this error, which was not there previously , having trouble to rectify help needed in this class MeterSerializer(serializers.HyperlinkedModelSerializer): url = serializers.HyperlinkedIdentityField(view_name="meter_reading:meters-list") customer_reports = CustomerReportSerializer(source='customerreport_set', many=True,read_only=True) class Meta: model = Meter fields = ['number','customer_reports','customer','url'] class CustomerReportSerializer(serializers.ModelSerializer): meter_no = serializers.SerializerMethodField(method_name='meter_num') customer_name = serializers.SerializerMethodField(method_name='cust_name') customer_number = serializers.SerializerMethodField(method_name='cust_number') class Meta: model = CustomerReport fields = ('meter_no','meter','customer_name','date','customer_unit','unit_rate','bill_amount','consumer_number','customer_number','pending_units',) routers.py router.register('customer', CustomerViewSet) router.register('meters',MeterViewSet,basename='meters') router.register('issues',IssueViewSet) router.register('customereport',CustomerReportViewSet,basename='customerreport') # router.register('users',UserViewset) urlpatterns = router.urls urls.py urlpatterns = [ path('', include(router.urls)), path('api-auth/', include('rest_framework.urls', namespace='rest_framework')), path('meter_access/', MeterAccess.as_view(),name='meter_access'), ] -
How can I send back an array from Django to React after fetching POST request?
So my web app is a combination of Django, React and BigQuery. What I want to do is to make a POST request from React to Django, and Django will fetch the table data from BQ before sending the table data back as an array to the React frontend. How can I achieve this? What I have so far: app.js const handleConfirm = () => { fetch("http://localhost:8000/get-data-instance/", { method: "POST", headers: { "Content-Type": "application/json" }, body: JSON.stringify(tableName), }); }; views.py def get_data_instance(request): client = bigquery.Client() if request.method == 'POST': table_requested = json.loads(request.body) query_string = f""" SELECT * FROM `project-id.dataset-id.{table_requested}` """ result = ( client.query(query_string) .result() ) records = [dict(row) for row in result] data_instance = json.dumps(str(records)) return render(request, 'frontend/index.html') I basically want to send back the data_instance created above. If I try to print data_instance, i get the correct output >> "[{'key': 1, 'Date': '2021-11-10', 'Hour': 1, 'Measurement': 2.0}]" So, now I'm just stuck on how can I pass this data back to React? Note: I'm not using DRF for this project. -
javascript exception Django [closed]
So I was following along a MapBox Tutorial on Django, and I was trying to initialize the for loop for the address of each house that I developed in my model, but I get an error for adding a for loop. It seems that you cannot instantiate the for loop in javascript, but the guy in the video was able to do it at 32 minutes. Any suggestions? I am on VScode. https://www.youtube.com/watch?v=65flD9ScEQM enter image description here -
Deploying Django App to AWS elasticbeanstalk, No './Library/Application Support/Insomnia/SS'
I tried to create an env with eb command. But after the eb create myenv-envruns this error follows. ERROR: FileNotFoundError - [Errno 2] No such file or directory: './Library/Application Support/Insomnia/SS' I am not very sure what causing this? Maybe is it somehow about the M1 mac? -
Many to Many field values not showing up in queryset in Django
These are my models: class Tasks(models.Model): name = models.CharField(max_length=50) def __str__(self): return self.name class Users(models.Model): GENDER = [ ('male', 'Male'), ('female', 'Female'), ('others', 'Others'), ] name = models.CharField(max_length=20) age = models.IntegerField() gender = models.CharField(max_length=6,choices=GENDER,default='male') tasks = models.ManyToManyField(Tasks) problems = models.TextField(blank=True) def __str__(self): return self.name In views when I do users = Users.objects.values() I am getting all the fields except tasks. I am not able to access the tasks list. <QuerySet [{'id': 1, 'name': 'Tom', 'age': 23, 'gender': 'Male', 'problems': ''}, {'id': 2, 'name': 'Thomas', 'age': 45, 'gender': 'Male', 'problems': ''}, {'id': 3, 'name': 'Lara', 'age': 34, 'gender': 'Female', 'problems': ''}]> Also while iterating in users for u in users: print(u['tasks']) gives key error, and u.tasks.all() is also not working -
Relate one model field to another model field twice Django
I am making an inventory system, and one thing I would like to be able to track is transfers. I have two models class Location(models.Model): class FacilityChoices(models.TextChoices): warehouse = 'Warehouse' location = 'Location' name = models.CharField(max_length=255, null=False, blank=False) street_ad = models.CharField(max_length=128, verbose_name='Street address') city_ad = models.CharField(max_length=128, verbose_name='City Address') state_prov = models.CharField(max_length=30, verbose_name='State/Province') country = models.CharField(max_length=50, verbose_name='Country') zip_code = models.CharField(max_length=20, verbose_name='Zip/Postal code') facility_type = models.CharField(max_length=30, choices=FacilityChoices.choices, default=FacilityChoices.warehouse) ... class Transfer(models.Model): item = models.ForeignKey(Stock, on_delete=models.CASCADE) quantity = models.IntegerField() location_send = models.ForeignKey(Location, on_delete=models.CASCADE) location_receive = models.ForeignKey(Location, on_delete=models.CASCADE) but I receive an error (fields.E304) when I do this. What would be the best way to accomplish this? -
Django Error While Hosting It Using Apache Web Server
I'm using the below version of the packages, and the aim is to configure the apache to host the django application. I'm using python in a virtual environment. OS Version: Centos 7.9 **Apache Version** [root@localhost ~]# httpd -version Server version: Apache/2.4.6 (CentOS) Server built: Oct 19 2021 13:53:40 Python Version: 3.7.12 **Python Packages and Version:** (myprojectenv) [rafiq@localhost ~]$ pip3.7 list Package Version ----------------- -------- asgiref 3.4.1 Django 3.2.9 pip 21.3.1 pytz 2021.3 setuptools 58.3.0 sqlparse 0.4.2 typing-extensions 3.10.0.2 wheel 0.37.0 I have installed the sqlite3 from the source, below are the details of the sqlite3 version and the path of the sqlite3. I can able to import sqlite3 in python3.7.12 (myprojectenv) [rafiq@localhost ~]$ sqlite3 --version 3.36.0 2021-06-18 18:36:39 5c9a6c06871cb9fe42814af9c039eb6da5427a6ec28f187af7ebfb62eafa66e5 (myprojectenv) [rafiq@localhost ~]$ whereis sqlite3 sqlite3: /usr/bin/sqlite3 /usr/local/bin/sqlite3 /usr/include/sqlite3.h /usr/share/man/man1/sqlite3.1.gz I'm new to python and apache. I followed the digital ocean website to configure the django apache, the url is listed below. https://www.digitalocean.com/community/tutorials/how-to-serve-django-applications-with-apache-and-mod_wsgi-on-centos-7 I have two folders inside /home/rafiq. myproject - django project myprojectenv - python virtualenv The settings of my apache configuration listed below. [rafiq@localhost ~]$ cat /etc/httpd/conf.d/django.conf Alias /static /home/rafiq/myproject/static <Directory /home/rafiq/myproject/static> Require all granted </Directory> <Directory /home/rafiq/myproject/myproject> <Files wsgi.py> Require all granted </Files> </Directory> WSGIDaemonProcess myproject python-path=/home/rafiq/myprojectenv:/home/rafiq/myprojectenv/lib/python3.7/site-packages WSGIProcessGroup … -
pwa and serviceworker showing on page
I've converted my django app into a pwa using django_pwa. I used a custom serviceworker.js since the autogenerated one kept throwing 404s because I didn't have the files it was looking for. However, as soon as I tried to go to another page, I get the serviceworker showing up. Why is this? I put the serviceworker.js in my static that is in my base directior, and in my settings.py, I added PWA_SERVICE_WORKER_PATH. Can anyone help me? -
Configure the raspberry pi so that the 2D scanner works with rasberry pi
I have already hosted my django project onto the xampp apache server, right now i need to configure my raspberry pi so that my 2D barcode scanner will work. My raspberry pi at the end of the day will be just sitting at 1 corner with the 2D barcode scanner connected to the raspberry pi and my raspberry pi will not be accessing my hosted website and it also won't be connected to the monitor or any other screen. Both my pc and the raspberry pi will be connected to the same internet with the same static ip address that I already configure on the apache server. How do I confiure my raspberry pi to work with the 2D barcode scanner so that when the user use the scanner, the barcode information will be sent to the Xampp apache and will automatically appear at the user's windows pc? I am stuck here for a very long time, any help will be appreciated! -
What is wrong with my Django Redis Sentinel settings
I have a code where I use Celery and Redis. For Redis we have Sentinel with 3 nodes where 1 is master and 2 are slaves. So please help me write settings in Django settings for this code. I have it now this way: CELERY_BROKER_URL = "sentinel://'my_ip':26379/0;sentinel://'my_ip2':26379/0;sentinel://'my_ip3':26379/0" CELERY_BROKER_TRANSPORT_OPTIONS = {"visibility_timeout": 3600, "master_name": "master" "PASSWORD": 'password',} And somethig is wrong here, because I got error "beat: Connection error: No master found for 'master'. Trying again in 0 seconds..." If I delete this master_name part, I got beat: Connection error: No master found for None. Trying again in 0 seconds... What am I doing wrong? -
Google oAuth2 getting 500 error after redirected to url
I followed all the neccessary steps for login using google. But after login in through a google account, it will redirect to my local URL but get a 500 error. in google cloud platform redirect URL is -- http:localhost:8000/oauth/complete/google-oauth2/ How to fix these? -
How to upload a databse file from local, and access its tables and records from backend(Django)?
I am creating an application where a user uploads a database file from his/her local machine, and I need to show all the tables, rows, and data records from that database file in the frontend. How can I achieve this? Frontend - React Backend - Django -
Django admin action with intermediate page processes only first 100 of selection
I have an admin action where I select artists and then choose an email which I want to sent them. If I filter the artists and then choose select all, I get around 1000 artist. If I sent the email, its only send to the first 100. This is my action: def send_email(self, request, queryset): form = None if 'apply' in request.POST: form = ChooseEmailForm(request.POST) if form.is_valid(): email = form.cleaned_data['email'] htmlMessage = email.htmlMessage for artist in queryset: send_single_email(email, artist) self.message_user(request, _('Successfully emailed \'%s\' to the selected artists.') % (email)) return HttpResponseRedirect(request.get_full_path()) if not form: form = ChooseEmailForm(initial={'_selected_action': request.POST.getlist(ACTION_CHECKBOX_NAME)}) return render(request, 'admin/send_email.html', {'artists': queryset, 'email_form': form}) This is my form: class ChooseEmailForm(forms.Form): _selected_action = forms.CharField(widget=forms.MultipleHiddenInput) email = forms.ModelChoiceField(queryset=Email.objects.all(), label='') and this is my html: {% extends "admin/base_site.html" %} {% block content %} <p>Select the email to send:</p> <form action="" method="post"> {% csrf_token %} {{ email_form }} <p>De chosen email will be send to the following artists:</p> <ul>{{ artists|unordered_list }}</ul> <input type="hidden" name="action" value="send_email" /> <input type="submit" name="apply" value="Send email" /> </form> {% endblock %} On the intermediate form it says: 'De chosen email will be send to the following artists:' and lists all 1000 artists. But when I apply, it's only … -
Fail to send email, but no error and exception
I am working on sending an activation email after the user registers an account. Everything works fine in the console. However, when I change to smtp Email backend, the program will stuck at send_mail() and then the program will refresh itself and send back "the username is taken". Finally, no email has been sent. I don't think the email setting is wrong since the program can send the reset password link to any email address. Can someone please help me!!!!!!!!!!! Feel free to leave any comments!!!!!! Here are the pieces of code Thankssss from django.contrib.auth.models import User, auth from django.contrib import messages from django.http import HttpResponse from django.shortcuts import render, redirect from django.views import View from django.core.mail import send_mail, BadHeaderError from django.template.loader import render_to_string from django.utils.http import urlsafe_base64_encode, urlsafe_base64_decode from django.contrib.sites.shortcuts import get_current_site from django.utils.encoding import force_bytes, force_text, DjangoUnicodeDecodeError from .utils import token_generator import requests def send_letter(request, user): uidb64= urlsafe_base64_encode(force_bytes(user.pk)) domain= get_current_site(request).domain subject = "Activate your account" email_template_name = "activation_email.txt" c = { "email":user.email, 'domain': domain, 'site_name': 'Website', "uid": urlsafe_base64_encode(force_bytes(user.pk)), "user": user, 'token': token_generator.make_token(user), 'protocol': 'http',} email2 = render_to_string(email_template_name, c) try: ####The program will stuck here !!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!!! send_mail(subject, email2, 'admin@example.com' , [user.email], fail_silently=False) except Exception as ex: print(ex) class RegistrationView(View): … -
How to return custom messages for each functions in a DRF Viewset?
I'm having a viewset class JobPostView(viewsets.ModelViewSet): permission_classes = [IsAuthenticated] serializer_class = JobPostSerializer queryset = JobPost How will I return custom messages for each function? for eg. if using the get function, I have to return "listed successfully" with data, for the post "posted successfully" with data, likewise for put, patch and delete. -
535, b'Incorrect authentication data when sending email in django project
I am getting this erro while sending email to users The error looks like this:- (535, b'Incorrect authentication data') My settings :- EMAIL_BACKEND = 'django.core.mail.backends.smtp.EmailBackend' EMAIL_HOST = 'smtp.gmail.com' EMAIL_USE_TLS = True EMAIL_HOST_USER = 'myEmail@gmail.com' EMAIL_HOST_PASSWORD = '' EMAIL_PORT = 587 It was working yesterday. Suddenly its not working i dont know what to do? Here is my view where i am trying to send an email to user def send_email_to_user(request, *args, **kwargs): users = User.objects.exclude(username=request.user) if request.method == "POST": sender = request.user receiver = request.POST.get('receiver') subject = request.POST.get('subject') content = request.POST.get('content') send = SendEmailToUser( sender = sender, receiver = receiver, subject=subject, content = content, ) send.save() send_mail( subject, content, # 'itna.sakib@gmail.com', 'noreply.marketage@gmail.com', [receiver], fail_silently=False, ) return HttpResponse("Success") args = { "users": users } return render(request, "adminmailview/send_mail_to_user.html", args) -
Stripe -403 authentication credentials not provided
I am working on an application where I am using Stripe to process my payments. I have tested each and everything in test mode but when I switch to live mode I am facing errors on my web hooks and the error rate is 100% the possible explanation that Stripe returns is: { "detail": "Authentication credentials were not provided." } The status code is: 403. -
How to use authentication in Django application
In my Django application I have a PetOwner model with the following fields: first_name, last_name, email, phone_number, address. I want to create an authentication system now for my users which for now is a PetOwner. I was thinking I should extend from django.contrib.auth.models or more specifically, from django.contrib.auth.models import User I was planning on having a OneToOneField in my PetOwner model to reference the User. Something like the following... user = models.OneToOneField(User, on_delete=models.CASCADE) I'm not sure if this makes sense to do though. Also, I do not want my PetOwner to have access to admin privileges. I'm use to other frameworks like Flask or NodeJS where I would have to hash the password and have a hashed_password saved in a user document or row depending if I'm using sql or nosql. I want to basically make sure that when I am referring to a user I am referring to a PetOwner. -
Dont know how to solve
Back-end Challenge In the Python file, write a program to access the contents of the bucket coderbytechallengesandbox. In there there might be multiple files, but your program should find the file with the prefix_cb_, and then output the contents of that file. You should use the boto3 module to solve this challenge. You do not need any access keys to access the bucket because it is public. This post might help you with how to access the bucket. Example Output contents of some file -
Creating a survey with Django
I am trying to implement a survey in Django and have run into a couple of issues. The survey has two questions and the answer choices are supposed to be represented with radio buttons (the user can only select one choice for their answer). The issues I ran into: I am not able to show only the answer choices that belong to a specific question. For some reason I am getting all answer choices below each question. I have tried editing my models to link specific choices to a question, but still the same issue. 2)After the user clicks "Submit" they are not being directed back to the survey index page nor are their answers saved in the database. Here is what I have so far for my models: User = settings.AUTH_USER_MODEL class Questionnaire(models.Model): questionnaire_name = models.CharField(max_length=255) questionnaire_text = models.CharField(max_length=200) def get_absolute_url(self): return reverse('questionnaire-detail', args=[str(self.id)]) def __str__(self): return self.questionnaire_name class Question_Prompt(models.Model): prompt = models.CharField(max_length=200) questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE, related_name='prompts') def __str__(self): return self.prompt class AnswerOption(models.Model): q_prompt = models.ForeignKey(Question_Prompt, on_delete=models.CASCADE, related_name='answers') questionnaire = models.ForeignKey(Questionnaire, on_delete=models.CASCADE, related_name='responses', default='') answer_text = models.CharField(max_length=200) def __str__(self): return self.answer_text class UserAnswer(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) questionnaire_taken = models.ForeignKey(Questionnaire, on_delete = models.CASCADE) questionnaire_date = models.DateTimeField(auto_now_add=True) … -
Django view URL after deployment with Gunicorn
I have a Django backend and a React frontend that have been working perfectly before deployment. I ran: nohup python manage.py runserver my_server_ip:8000 & In this case, the view can be called by React with: my_server_ip:8000/app1/view1 After that, I deployed Django with Gunicorn and React with Nginx, Nginx config: server { listen 80; root /path_to_react_build_folder; server_name my_server_ip; index index.html; location = /favicon.ico { access_log off; log_not_found off;} location / { proxy_set_header Host $http_host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Forwarded-Proto $scheme; } } Gunicorn.socket [Unit] Description=gunicorn socket [Socket] ListenStream=/run/gunicorn.sock [Install] WantedBy=sockets.target Gunicorn.service [Unit] Description=gunicorn daemon Requires=gunicorn.socket After=network.target [Service] User=my_username Group=www-data WorkingDirectory=/home/my_username/django_project_root ExecStart=/home/my_username/python_virtualenv/bin/gunicorn --access-logfile - --workers 3 --bind unix:/run/gunicorn.sock django_project_root.wsgi:application [Install] WantedBy=multi-user.target Connection was okay as I typed my_server_ip in browser (i.e. default to index.html set in Nginx config). All static things like background color and banner displayed normally but I couldn't get the result from API call. Browser console showed: GET http://my_server_ip:8000/app1/view1 net::ERR_EMPTY_RESPONSE How can I let React access Django's view in this case? -
how can i use sql console on web?
I want to make web page to practice SQL Query. User can type SQL sentence and check the result. I think that needs SQL console that operating on Web, How can I build SQL console on Web? Is there any good tools? +) I'm developing with DRF and Vue.js. -
Ajax calls not calling on a PWA
I just covert a django project to a pwa using django_pwa. Before hand, the project worked perfectly. Part of the project, I am making GET and POST requet using ajax. Now that it is a pwa, it seems like ajax is not making these calls. Any reason why? I know pwa are still a bit new, and I can't seemed to find anything related to both of these on google or yourtube. -
How to easily extract request.POST data after Django form submission?
My request.POST data looks like this after my Django form submission: <QueryDict: {'form-0-country': ['19389'], 'form-0-city': ['Montreal'], 'form-0-eid': ['450'], 'form-0-company': ['Nestle'], 'form-0-dept': ['HR'], 'form-1-country': ['19390'], 'form-1-city': ['Toronto'], 'form-1-eid': ['432'], 'form-1-company': ['Nestle'], 'form-1-dept': ['Finance']}> These are values of two forms contained in two different rows on the webpage. The values from these two rows are printed sequentially in the request.POST. Is there a way to get this data printed in the backend in a simpler way so that I don't have to loop through all this data to extract the specific fields contained in it? For eg. something like this: <QueryDict: {'form-0-country': ['19389','19390'], 'form-0-city': ['Montreal','Toronto'], 'form-0-eid': ['450'], 'form-0-company': ['Nestle','Nestle'], 'form-0-dept': ['HR','Finance']> so that I can easily loop through the value (lists) in the dict above. instead of: <QueryDict: {'form-0-country': ['19389'], 'form-0-city': ['Montreal'], 'form-0-eid': ['450'], 'form-0-company': ['Nestle'], 'form-0-dept': ['HR'], 'form-1-country': ['19390'], 'form-1-city': ['Toronto'], 'form-1-eid': ['432'], 'form-1-company': ['Nestle'], 'form-1-dept': ['Finance']}> -
django permission based on AD group membership
I'm trying to grant access to specific URLs and menu links in base.html file based on AD groups an authenticated users belong to. The AD instance is fairly large but it also includes deeply-nested AD groups, so, quering the AD server for every HTTP request is an expensive one. A solution I'm think of at the moment is to write a custom middleware that queries the AD server the first time a user access the application, I query the AD server one time, get all the access levels they should have and store this information in a session, then, when they make another request, I check the session values first if I already set permissions for that specific user, this should avoid querying the AD server everytime. Given this criteria, is there any native django authorization classes/technique that is able to handle this sort of access privilege?