Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Redirect django admin panel to appropriate path in the docker
I have a docker-compose.yaml script. I want proxy to pass the Nginx in this to another host-level nginx whose config as follows server { listen 80; server_name donorgrid.tbhaxor.com _; error_log /var/log/nginx/donorgrid.error.log; access_log /var/log/nginx/donorgrid.access.log; location /management { proxy_pass http://localhost:8080/; } } I want my base URL to be https://donorgrid.tbhaxor.com/management/ and all users inherit this. For example, admin panel should be available on https://donorgrid.tbhaxor.com/management/admin With this configuration, I am getting issues in redirection as Django sends redirect response with Location header /admin/ which in this case doesn't exist. Here are my curl request and responses # curl -I donorgrid.tbhaxor.com/management HTTP/1.1 302 Found Location: /admin/ # curl -I donorgrid.tbhaxor.com/management/ HTTP/1.1 404 Not Found # curl -I donorgrid.tbhaxor.com/management/admin HTTP/1.1 404 Not Found Note: I have stripped out unwanted headers for this question -
Can't figure how to solve this when creating a virtual environment for Django
How can I figure this out when working with Django :can't open file '/home/student/back_ends/venv': [Errno 2] No such file or directory -
Switching django app to apache, Permission denied: mod_wsgi
I've developed a django app which works properly with python3-venv through django 'server:8000' on Ubuntu 21.04. I tried to switch to apache so users can navigate directly to 'server', but it throws an error 'Forbidden: You don't have permission to access this resource.' I followed this tutorial: https://youtu.be/Sa_kQheCnds and here are some details about the errors in apache2 log: Permission denied: mod_wsgi (pid=16237): Unable to stat Python home /home/khalid/app/venv. Python interpreter may not be able to be initialized correctly. Verify the supplied path and access permissions for whole of the path. Python path configuration: PYTHONHOME = '/home/khalid/app/venv' PYTHONPATH = (not set) program name = 'python3' isolated = 0 environment = 1 user site = 1 import site = 1 sys._base_executable = '/usr/bin/python3' sys.base_prefix = '/home/khalid/app/venv' sys.base_exec_prefix = '/home/khalid/app/venv' sys.platlibdir = 'lib' sys.executable = '/usr/bin/python3' sys.prefix = '/home/khalid/app/venv' sys.exec_prefix = '/home/khalid/app/venv' sys.path = [ '/home/khalid/app/venv/lib/python39.zip', '/home/khalid/app/venv/lib/python3.9', '/home/khalid/app/venv/lib/python3.9/lib-dynload', ] Fatal Python error: init_fs_encoding: failed to get the Python codec of the filesystem encoding Python runtime state: core initialized ModuleNotFoundError: No module named 'encodings' Permissions: drwxrwxr-x 6 khalid www-data 4096 Jul 28 06:47 app drwxrwxr-x 6 khalid www-data 4096 Jul 28 06:47 venv django_app.conf: <VirtualHost *:80> ServerAdmin webmaster@localhost DocumentRoot /var/www/html ErrorLog ${APACHE_LOG_DIR}/error.log CustomLog … -
Django - 'dict' object has no attribute 'headers'
I am getting this error on django iwth my dict and OrderderedDict doesnt matter which one I use. If someone can maybe see what I am doing wrong. Thanks in advance data = {'PAYGATE_ID' : '10011072130', 'REFERENCE' : 'pgtest_123456789',} #just for reference i am puttung 2 items in dict CHECKSUM = calculate_md5(data) url = 'https://secure.paygate.co.za/payweb3/initiate.trans' data['CHECKSUM'] = CHECKSUM data['url'] = url hash_valid, response_data = post_payment(data) if not hash_valid: return HttpResponseForbidden('FAILED') response_data.pop('PAYGATE_ID') response_data.pop('REFERENCE') return response_data def post_payment(data): url = data.pop('url') response = requests.post(url,data=data) dict_ = {} new = response.text.split('&') print(new) for item in new: list_ = item.split('=') key = list_[0] value = list_[1] dict_[key] = value is_equal, dict_['CHECKSUM'] = validate_checksum(dict_) return is_equal, dict_ def validate_checksum(data): hash_ = data.pop('CHECKSUM') new_hash = calculate_md5(data) return hash_ == new_hash, new_hash -
ALLOWED_HOSTS not found. Declare it as envvar or define a default value
Am developing a Django application then try to deploy it on the Heroku platform. Everything is going on well until it reached the time to git push Heroku master where am getting this error File "/app/.heroku/python/lib/python3.9/site-packages/decouple.py", line 70, in get remote: raise UndefinedValueError('{} not found. Declare it as envvar or define a default value.'.format(option)) remote: decouple.UndefinedValueError: ALLOWED_HOSTS not found. Declare it as envvar or define a default value. This is my settings.py import os import django_heroku from decouple import config from decouple import Csv BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) # Quick-start development settings - unsuitable for production # See https://docs.djangoproject.com/en/2.1/howto/deployment/checklist/ # SECURITY WARNING: keep the secret key used in production secret! SECRET_KEY = 'SECRET_KEY' # SECURITY WARNING: don't run with debug turned on in production! DEBUG = True ALLOWED_HOSTS = config('ALLOWED_HOSTS', cast=Csv()) # Application definition INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django_daraja', 'chama', 'bulma', 'djmoney', 'django_simple_bulma', ] -
How to make plumbum.local run on your windows system
In my django application, I'm creating the db by taking the parameters from env variables but it throws following error. createdb = plumbum.local["createdb"] File "C:\Users\xyz\lib\site-packages\plumbum\machines\local.py", line 249, in __getitem__ return LocalCommand(self.which(cmd)) File "C:\Users\C:\Users\xyz\lib\site-packages\plumbum\machines\local.py", line 211, in which raise CommandNotFound(progname, list(cls.env.path)) plumbum.commands.processes.CommandNotFound: ('createdb') my code to create postgres db: import plumbum def create_db(): from myapp import settings createdb = plumbum.local["createdb"] for db_name, db_info in settings.DATABASES.items(): createdb["-h", db_info.get("HOST"), "-p", db_info.get("PORT"), db_info.get("NAME")].run( retcode=[0, 1] ) How to make it work on windows ? -
Adding label to Django AppConfig gives error with migrations
I am new with Django. I am using DRF. I was trying to integrate social authentication using dj-rest-framework and django-allauth, but I currently have an app called account, so it gives a naming conflict with allauth.account. I managed to fix this by following this solution. It is a known problem with allauth.account and changing one of the apps label will fix the confilct. Here comes the second problem. After I configured the URL, it gave an error ProgrammingError "Table '<project-name>.socialaccount_socialapp' doesn't exist" So, I thought that maybe making migrations will fix the issue. When I try making migrations, it gave some different errors based on the changes that I made, but none of the solutions seems to work. When I changed the label name of the AllAuth Account as described on the solution mentioned above and then trying to make the migrations python manage.py makemigrations gives this error: CommandError: Conflicting migrations detected; multiple leaf nodes in the migration graph: (0001_initial, 0002_email_max_length in allauth_account). To fix them run 'python manage.py makemigrations --merge' and then running: python manage.py makemigrations --merge gives ValueError: Could not find common ancestor of ['0001_initial', '0002_email_max_length'] If I try changing my account app label instead of the allauth … -
PayPal API specifying currency SGD
I'm developing a payment system with PayPal API. Everything works except that the transaction is in USD and not SGD (like how I want it to be). PayPal Button from react-paypal-button-v2 <PayPalButton currency='SGD' amount={parcel.basePrice} onSuccess={successPaymentHandler} /> Script to add PayPal button const addPayPalScript = () => { const script = document.createElement("script"); script.type = "text/javascript"; script.src = "https://www.paypal.com/sdk/js?client-id=CLIENT_ID&currency=SGD"; script.async = true; script.onload = () => { setSdkReady(true); }; document.body.appendChild(script); }; I followed the documentation here. https://developer.paypal.com/docs/checkout/reference/customize-sdk/ -
Getting Flask Error GET html 404 constantly
All of my .html files are present in templates folder. Im getting a 404 error on one particular file called tour.html I have defined its route as @app.route('/tour1.html') def tour1(): return render_template('tour1.html') Full Error is "GET tour1.html HTTP/1.1" 404 - Additionally, the linking works fine when i run on VS Code's Live Server, so no issue in html files. Pls help out ! -
The view firstweb.views.productdisplay didn't return an HttpResponse object. It returned None instead
def productdisplay(request): try: session=request.session["w"] if session is not None: productdetails=product.objects.all() return render(request,"firstweb/product.html",{"pd":productdetails}) except: messages.info(request,"Please login first") return render(request,'firstweb/login.html') once in past i have the same error, that was because i just call the render not returned it.This error still occured first but even when i returned it, it's still showing -
Conditional number of inline formsets according to value from master form
This is my models.py: class Event(models.Model): EV_TYPE = ( ('performance', 'performance'), ('recording release', 'recording release'), ('other', 'other'), ) title = models.CharField(max_length=200) type = models.CharField(max_length=20, choices=EV_TYPE, default="performance") class dateEvent(models.Model): event = models.ForeignKey(Event, on_delete=models.CASCADE) start_date_time = models.DateTimeField(auto_now=False, auto_now_add=False) views.py: def event_edit_view(request, id): event = get_object_or_404(Event, id=id) form_event = EventForm(request.POST or None, instance=event) DateEventFormSet = inlineformset_factory(Event, dateEvent, extra=5, can_delete=True, fields=('event', 'start_date_time',), form_date_event = DateEventFormSet(request.POST or None, instance=Event.objects.get(id=id), queryset=dateEvent.objects.filter(event__id=id)) context = { 'event': event, 'id': event.id, 'form_event': form_event, 'form_date_event': form_date_event, } if request.method == "POST": if form_event.is_valid(): form_event.save() form_date_event.save() return redirect('my-events') else: raise forms.ValidationError(form_date_event.errors) else: raise forms.ValidationError([form_event.errors, form_date_event.errors]) return render(request, "events/event-edit.html", context) I'd like to have my events form to require and accept one or more dateevent inline formsets if the event type = 'performance', accept none if type = 'other', and require one and only one dateevent inline formset if event type = 'recording release'. This is a first attempt. Could this be a good solution? if form_date_event.is_valid(): flag=False evt_type = form_event.cleaned_data.get('type') if evt_type =="recording release" and form_date_event.lenght != 1: flag = True break elif evt_type =="performance" and form_date_event.lenght < 1: flag = True break if flag: messages.error(request,'There must be one date event') return render(request, "events/event-edit.html", context) else: form_event.save() form_date_event.save() return redirect('my-events') -
Python Django Celery Integration with Azure Service Bus
Have you used Azure Service bus Queues as a message broker of Celery for a Django Project? What are the advantages and disadvantages of it? There is not much documentation for this integration. Does celery support Azure Service Bus? -
Get most liked post in last 10 days in django
I am building a BlogApp and I am trying to get most liked blogpost in last 10 days. Then after 10 days, new most liked posts will be shown. BUT when i try to access then is not showing. models.py class BlogPost(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) title = models.CharField(max_length=30) date_added = models.DateTimeField() likes = models.ManyToManyField(User, related_name='blogpost_dislike', blank=True) views.py def blogposts(request): time = timezone.now() - timedelta(days=10) liked = BlogPost.objects.annotate( num_likes=Count('likes')).filter( num_likes__gt=10).filter(date_added__gte=time) BUT the above code will show posts which have more than 10 likes . BUT i am trying to show most liked(without minimum) in 10 days. What have i tried :- I also tried this in template tag :- @register.simple_tag def get_most_commented_posts(count=10): return BlogPost.objects.annotate( total_likes=Count('likes') ).order_by('-total_likes')[:count] This code is also checking minimum 10 likes in posts. Then i tried this liked = BlogPost.objects.annotate(total_likes=Count('likes')).filter(date_added__lte=time) BUT this is not even filtering, it is showing all the posts. AND I am trying to get most liked posts in last 10 days. Any help would be Appreciated. Thank You in Advance. -
How can I delete specific row instead of always the first row (Modal in Django)
I'm building a CRM app and try to delete a specific client when the confirmation button is clicked in the pop-up modal, but it always deletes the first client. I know that it happened due to the ambiguous class name, and the problem may be solved by adding a unique id for each client? I have been searching around for this type of problem but still not sure how to solve it. Since I generated every client by a for loop and I might need to dynamically create a unique id for each client and call the specific id in javascript and modify the corresponding CSS? I feel that this way might be over-complicated. Are there any other methods to achieve my goal? Thanks. My code is following: Templates <!-- client table --> {% for user in clients %} <tr class="mt-3"> <td class="pt-3">{{ user.level }}</td> <td class="pt-3"><a href="{% url 'clients' user.id %}">{{ user.first_name }}</a></td> <td class="pt-3">{{ user.last_name }}</td> <td class="pt-3">{{ user.country }}</td> <td class="pt-3">{{ user.contact }}</td> <td class="pt-3">{{ user.contact_number }}</td> <!-- <td><a href="#" class="btn btn-outline-primary btn-sm">Client Info</a> --> <td><a href="{% url 'update' user.id %}" class="btn btn-outline-warning">Update</a> <a class="btn btn-outline-danger" onclick="clientmodal()" >Delete</a></td> </tr> <!-- client modals --> <div class="modal-bg"> <div class="delete-modal"> … -
Append server name in a API response -- Django rest framework
I have been trying to create a API with Django restframework. There is a Image field in the API which is giving a relative path. I would like to have absolute path or name of the server to append before the Image field. But its throwing an error TypeError: string indices must be integers I believe the json that I created from the ordered dict is a string and is not giving expected output. Problem: I need to access the json keys and append server name in it. I tried the following for it. views.py def get_individualmember_details(request): if request.method == 'GET': serializer = MasterIndividualMembersSerializer(MasterIndividualMembers.objects.all(), many=True) result = json.dumps(serializer.data) print(result) for row in result: if row["member_photos"]["image"]: row["member_photos"]["image"] = request.META['HTTP_HOST'] + "/" + row["member_photos"]["image"] result = json.dumps(result) return JsonResponse(json.loads(result), safe=False) expected output: [ { "model": "userdata.masterexecutivemember", "pk": 1, "fields": { "firstname": "John", "lastname": "Doe", "profile_image": "http://127.0.0.1:8000/user/1.jpeg", //Needs to append servername here "description1": "Test abc", } }, ... ... ] Please suggest how to append the server name or a string before any json key. Thanks in advance! -
Why response is always {"detail":"Unsupported media type \"text/plain\" in request."} in swift?
I have created a sample app in Django which deletes a question from App. And provides a correct output when consumed using POSTMAN. class Questions(APIView): def delete(self,request): received_id = request.POST["id"] print(received_id) place = Question.objects.get(pk=received_id) place.delete() questions = Question.objects.all() seriliazer = QuestionSerializer(questions,many = True) return Response({'Orgs': seriliazer.data}) However, when I am trying to achieve it from iOS app, it's returning {"detail":"Unsupported media type "text/plain" in request."} func deleteQuestion( id: Int){ guard let url = URL(string: "http://127.0.0.1:8000/V1/API/questions/") else { return } var request = URLRequest(url: url) let postString = "id=15" request.httpBody = postString.data(using: String.Encoding.utf8); request.httpMethod = "DELETE" URLSession.shared.dataTask(with: request) { data, response, error in let str = String(decoding: data!, as: UTF8.self) print(str) if error == nil { self.fetcOrganizatinData() } }.resume() } Could not really understand where exactly the problem is ? -
POST in form is not getting called in django project
After the FamilyForm is Filled and redirect the PersonForm is not get post. they are two forms to fill. adding action to the form also didn't trigger it. there might be something small that has been missed in it. please help as soon as possible for any other information tag and let me know View.py def index(request): familyForm = FamilyForm() if request.method == 'POST': familyForm = FamilyForm(request.POST) if familyForm.is_valid(): familydetails = familyForm.save() return redirect(addPerson,familydetails.familyId) #return render(request, 'html/personForm.html',{"family":familydetails,'personForm':personForm}) return render(request, 'html/index.html', {"familyForm": familyForm}) def addPerson(request,FamilyID): family = FamilyDetails.objects.get(familyId=FamilyID) personForm = PersonForm() print(request.method) if request.method == 'POST': personForm = PersonForm(request.POST) print(personForm.errors) if personForm.is_valid(): personDetails = personForm.save(commit=False) print(personDetails) return HttpResponse("<h1>Form FIlled</h1>") return render(request,'html/personForm.html', {"personForm":personForm, 'family':family }) personForm.html {% extends 'html/familyCard.html' %} <div class="formRepeat"> <form method="post" action="{% url 'add_person' family.familyId %}" id="personForm" class="needs-validation" novalidate data-qualification-url="{% url 'ajax_load_qualification' %}"> {% csrf_token %} urls.py urlpatterns = [ path('', views.index, name="index"), path('addperson/<int:FamilyID>/', views.addPerson, name="add_person"), path('ajax/load-qualification/',views.load_qualification,name='ajax_load_qualification'), ] -
context data not getting displayed in inherited template
Base HTML {% load static %} {% include "navigation/navigation.html" with cat=categories only %} <!-- base template --> {% block content %} some html {% endblock%} Template B {% extends "base/index.html" %} {% block content %} <!-- product right --> Some html <!-- //product right --> <!-- //product right --> {% endblock %} My issue is when I am rendering template b its not showing the context I have passed to the navigation bar, even though when accessing the base template alone context is getting displayed fine, don't know where is the issue, -
ModuleNotFoundError: No module named 'blogpro.wsgi' in Procfile, Deploying Django using Heroku, code H10 : App crashed
I am trying to deploy django project on Heroku, it is not deploying iam getting error as follows: ModuleNotFoundError: No module named 'blogpro.wsgi see full detail error in log. Full deatil log error - click here 2021-07-30T06:58:08.676208+00:00 app[web.1]: ModuleNotFoundError: No module named 'blogpro.wsgi' 2021-07-30T06:58:08.676489+00:00 app[web.1]: [2021-07-30 06:58:08 +0000] [8] [INFO] Worker exiting (pid: 8) my Procfile content is : web: gunicorn blogpro.wsgi and see my Procfile location folder in image below : Procfile location image - click here iam not able to understand what problem is ? is it because of my procfile in wrong location (if your answer is procfile should be in root directory please specify the root directory because i don't know what root directory is)? and whether the problem is in content of Procfile ? please see all images attached to see problem clearly. -
scheduling emails using sendgrid in a django app
I have created a django app which has a model Appointment. This Appointment model has a fields like this start_time = models.DateTimeField() student = models.Charf.... parent = models.Charf... tutor = models.Charf... .... Now, I want to send email notification to student, parent and the tutor. 10 minutes before the start_time. The start_time can be any future date , time. So basically i'm trying to schedule an email as soon as an appointment is created in the database. I'm willing to use sendgrid for this but please let me know if there is any other library that can do this job. -
how to set variable in DjangoTemplates inside in a loop and use outside
I want to set a variable in a loop and use other out a loop but django template not allow me, If i do this in a view then i have to run the loop 2 times, 1 time in a view and other time in a template.. This is not a good idea I try "set" , "firstof" and 'template tag' also example code with template tag @register.simple_tag def setvar(val=None): return val {% for x in "15"|loopRunTime %} {% if x == 12 %} {% setvar x as action %} {% endif %} {% endfor %} {{ action }} 2 example is firstof {% for x in "15"|loopRunTime %} {% if x == 12 %} {% firstof x as i %} {% endif %} {% endfor %} {{ i }} -
How can I trigger a Bootstrap modal programmatically when a Django template condition is met?
Let's say one of the views returns a context with the key 'db_busy' with a String if someone is using the database. Django part: def check_status(request): context = { 'current_tab': '1' } if request.method == 'POST': if get_lock_data(): lock_data = get_lock_data() for x in lock_data: if x['user_name'] != request.user.username: context['db_busy'] = 'Warning! The database is in use by: '+x['user_name'] return render(request, 'index.html', context) So what I want in index.html is, first of all, to check if that key (db_busy) exists in the context, if it exists that means that another user is modifying the database and therefore I want to show an informative modal. What I've tried so far: Javascript part within index.html (truncated index.html): <script> $(document).ready(function(){ $('[data-toggle="tooltip"]').tooltip(); }); {% if db_busy %} alert("{{db_busy}}"); $('#dbBusyModal').modal('show'); {% endif %} </script> The alert is working properly and showing up as expected when some user is editing the db. But for some reason, the modal is not showing. modal code (truncated index.html): <!-- Modal --> <div class="modal" id="dbBusyModal" tabindex="-1" role="dialog"> <div class="modal-dialog modal-dialog-centered modal-sm" style="width:350px;" role="document"> <div class="modal-content"> <div class="modal-header"> <h4 class="modal-title">Warning!</h4> <button type="button" class="close" data-dismiss="modal" aria-label="Close"> <span aria-hidden="true">&times;</span> </button> </div> <div class="modal-body"> <p>Warning! The database in use by: test</p> </div> <div class="modal-footer"> … -
How To show The YouTube Video Data in templates from Playlist's many to many field in Django, such as video name and video url
How can I display the video details using the many to many field in Django, what should be the syntax of the templates and views to fetch the all the videos of a playlist. --Models.py-- from django.db import models # Create your models here. class Youtube_Video(models.Model): video_url = models.TextField(default="", blank=True, null=True) video_name = models.CharField(max_length=200 ,default="", blank=True, null=True) def __str__(self): return self.video_name class Playlist(models.Model): image_Url = models.TextField() playlist_Name = models.CharField(max_length=200) playlist_Desc = models.TextField() slug = models.CharField(max_length=200) video = models.ManyToManyField(Youtube_Video, blank=True) def __str__(self): return self.playlist_Name --Views.py-- def videoItem(request, slug): playlist = Playlist.objects.filter(slug=slug).first() context = { 'playlist': playlist, } return render(request, "Home/videoItem.html", context) --Templates {% extends 'base.html' %} {% block title %}Video{% endblock title %} {% block body %} <section id="videoItem"> </section> <section> <h1>{{playlist.video.video_name}}</h1> </section> {% endblock body %} -
model form is not saving in django it is telling user can not be nul
i crated a model name address and connected with user by foreign key so a user can have multiple address but it is not saving i want form to take that user id to save but i don't how to do that here is my models.py class Address(models.Model): phoneNumberRegex = RegexValidator(regex = r"^\d{10,10}$") pincodeRegex = RegexValidator(regex = r"^\d{6,6}$") user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='address') reciever_name = models.CharField(max_length=200, blank=False) phone_no = models.CharField(validators = [phoneNumberRegex], max_length = 10, blank=False) alt_phone_no = models.CharField(validators = [phoneNumberRegex], max_length = 10, blank=True) state = models.CharField(max_length=50, choices=state_choice, blank=False) pincode = models.CharField(validators = [pincodeRegex], max_length = 6, blank=False) eighteen = models.CharField(blank=False, choices=eighteen_choice, default='Yes', max_length=4 ) city = models.CharField(max_length=100, blank=False) address = models.CharField(max_length=500, blank=False) locality = models.CharField(max_length=300, blank=True) joined_date = models.DateTimeField(default=timezone.now,editable=False) update_at = models.DateTimeField(auto_now=True) def __str__(self): return self.user.username my views.py @login_required def add_address(request, username): if request.method == 'POST': form = Addressform(request.POST) if form.is_valid(): form.save() return redirect('accounts:home') else: form = Addressform() return render(request, 'add_address.html', {'form': form}) my form.py class Addressform(forms.ModelForm): class Meta: model = Address fields = '__all__' exclude = ['user', 'joined_date', 'updated_at'] labels = { 'reciever_name':'Reciever Name', 'phone_no':'Phone No', 'alt_phone_no':'Alternate Phone No', 'state':'State/Union Territory', 'pincode':'Area Pincode', 'eighteen':'Is reciever is 18+', 'city':'City', 'address':'Address', 'locality':'Locality', } widgets = { 'eighteen': forms.RadioSelect() } … -
How to write Django filter query with GROUP BY
I am trying to fetch group by data in Django. How I Can write Django query like this SQL query:- SELECT id FROM table_name WHERE name=%s GROUP BY name" I am trying with Model.objects.filter().values('id').annotate(count=Count('name')).order_by('name') but not get unique name`s id in QuerySet