Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django : How to upload CSV file in unit test case using APIClient from rest_framework
def test_upload_csv_success(self): """Test uploading a csv file""" with open("innovators.csv", "w") as file: writer = csv.writer(file) writer.writerow(["SN", "Name", "Contribution"]) writer.writerow([1, "Linus Torvalds", "Linux Kernel"]) writer.writerow([2, "Tim Berners-Lee", "World Wide Web"]) writer.writerow([3, "Guido van Rossum", "Python Programming"]) with open("innovators.csv", "r") as file: res = self.client.post( CSV_URL, {"file": file}, content_type="multipart/form-data" ) file.close() self.assertEqual(res.status_code, status.HTTP_201_CREATED) #self.assertIn('file', res.data) #self.assertTrue(os.path.exists(self.csv_model.file.path)) Below is the error, I/m getting System check identified no issues (0 silenced). .F. FAIL: test_upload_csv_success (core.tests.test_csv_api.CsvUploadTests) Test uploading a csv file Traceback (most recent call last): File "/Users/rounaktadvi/django_rest_api_projects/csv-store-api/core/tests/test_csv_api.py", line 56, in test_upload_csv_success self.assertEqual(res.status_code, status.HTTP_201_CREATED) AssertionError: 400 != 201 -
Multiprocessing with Django - fork causes random deadlocks
i've tried to start django multiprocess pool with fork context, but without any-apparent-reason, sometimes, the main application (that control the pool) freezes, without doing anything else. This is how i start my pool: model_instances = [instance1, instance2, instance3, instancen] with multiprocessing.get_context('fork').Pool(multiprocessing.cpu_count()) as pool: pool.map(_run_par_task, model_instances) After looking at this page, i've seen that it describes my issue, and i suspect that sometimes, the fork method causes some deadlocks. So, i've tried to use the spawn method to manage my pool, as following: model_instances = [instance1, instance2, instance3, instancen] with multiprocessing.get_context('spawn').Pool(multiprocessing.cpu_count()) as pool: pool.map(_run_par_task, model_instances) ...but i'm getting this error message: django.core.exceptions.AppRegistryNotReady: Apps aren't loaded yet. That clearly indicates that django apps are not loaded in the child process. Basically, i need to work in the child process with Django models, so, how i can load the django app in the child spawned processes? -
How to check user is a member of model object or not in Django?
I wrote this models in model.py class Group(models.Model): MEMBERS_NUMBER = [ (2, 'Two people'), (5, '3 to 5'), (10, '5 to 10'), ] group_name = models.CharField(max_length=50) slug = models.SlugField(max_length=50, unique=True) members = models.IntegerField(choices=MEMBERS_NUMBER) people = models.ManyToManyField('Profile', through='Membership', blank = True) summary = models.TextField( 'Summary and indeas', max_length=500, help_text='Say what you want to do with your study or jub partner.' ) date_created = models.DateTimeField(default=timezone.now) and class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) birth_date = models.DateField(blank=True, null=True) profile_picture = models.ImageField(default = 'default.jpeg', upload_to = 'profile_pics', null=True, blank = True) date_joined = models.DateTimeField(default=timezone.now, null=True, blank = True) and class Membership(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) members = models.ForeignKey(Profile, on_delete=models.CASCADE) then i created generic class-based view for every object of Group model but i want to limit access to only profiles in that Group object, this is my class-based view: class GroupDetail(UserPassesTestMixin, generic.DetailView): model = models.Group context_object_name = 'group' template_name = 'projects/group_detail.html' def test_func(self): return self.request.user.profile.group_set.filter(group_name='My-Django-Group') def get_queryset(self): return models.Group.objects.all() The test_func(self) checks if user is member of 'My-Django-Group' then show the group details to user but i want to get the object name that we are in it, i tested this: def test_func(self): return self.request.user.profile.group_set.filter(group_name=self.group.group_name) but it didn't work -
Save HTML tables locally in the Angular/Django
I'm new in full stack development and its a lot of try and error. Now I'm struggling with html tables. For explanation: I am building a simple web app that can show tables from Azure SQL Database. I am able to input the tables through backend connection (Django) to the Frontend(Angular) for representation. but, every time I reload the app, all data from the table are gone and it starts calling the tables again. it would be great to save this tables permanently because the tables are so large and it takes a long time to fetch them again. what's the best way to achieve this? -
How to get input values from a row in a django template
I have a table and want to see the elements, and some inputs in the fields which i want to edit. I have too two buttons, one to edit the row and another to delete the row. My problem is to get the id and values of only this row becouse I´m only avaliable to get the last row, no matters which button I press. Overview html: {% for zona in zonas %} <tr> <td> <input type="text" value="zona" id="{{zona.zona}}" name="zona" class="editable form-control"> </td> <td> <input type="text" value="red" id="{{zona.red}}" name="red" class="editable form-control"> </td> <td> {{ zona.soft_low }} </td> <td> {{ zona.soft_medium }} </td> <td> {{ zona.soft_high }}</td> <td style="display: grid"> <button type="submit" name='update' class="btn btn-success"><i class="fas fa-upload"></i></button> <button type="submit" name='delete' class="btn btn-danger"><i class="fas fa-trash"></i></button> <input type="hidden" name="zonaides" value="{{zona.zonaid}}"> </td> </tr> {% endfor %} -
How to host a django website in hostgator?
I want to host a my django website on hostgator but i don't know how to host a website in hostgator please help me can you please provide a link for hosting a django website on hostgator -
How to restart running task and pending task in celery once worker is forcefully shutdown?
My problem is i am running task in celery which take 10 to 15 minutes to complete but what problem come is How to i restart task which currently running in worker and also one which is currently not running but waiting for task to run while i forcefully stopped worker or in case my server got crash or stopped. What happens right now is if i start celery again it's not starting the last running task or remaining task. -
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,