Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to exclude drf router path from drf_spectacular SERVERS setting
I would like to verify some best practices when using drf_spectacular with a django project. I have an API in a django project where all the endpoints use the api/ prefix, i.e. in urls.py, I'm using. path('api/', include('myapp_api.urls')), The myapp_api project'ss urls.py uses the default router, so something like router = routers.DefaultRouter() router.register(r'assets', views.AssetsViewSet) By default, this means that the swagger docs will present all the endpoints as something like... /api/assets/{}/ instead of /assets{}/ This of itself isn't a big deal because the swagger UI's test calls will work just fine because it will correctly call https://example.com/api/assets{}/. It just looks a bit messy in SwaggerUI. The main problem arises when I set the OpenAPI server object, which for drf_spectacular is the SERVERS setting, e.g. SPECTACULAR_SETTINGS = { 'SERVERS': [{'url': 'https://example.com/api'}], } At which point I have failure because the Swagger test calls will try and request to https://example.com/api/api/assets/{}/ and will still show the /api/ prefix on all the endpoints. I seem to have two options: I could go to my urls.py and use path('', include('myapp_api.urls')) instead of path('api/', include('myapp_api.urls')) but that's not desirable because the prefixing seems to make sense in this context. I could use a drf_spectacular preprocessing hook … -
error ModuleNotFoundError in django for python
Why am I getting this error? I know my code has bugs So help me My error : File "C:\Users\emanull\AppData\Local\Programs\Python\Python310\lib\importlib\__init__.py", line 126, in import_module return _bootstrap._gcd_import(name[level:], package, level) File "<frozen importlib._bootstrap>", line 1050, in _gcd_import File "<frozen importlib._bootstrap>", line 1027, in _find_and_load File "<frozen importlib._bootstrap>", line 1004, in _find_and_load_unlocked ModuleNotFoundError: No module named 'current_datetime' my code : link github -
Reduce by -1 & display as new instance every time
Trying to build a member ship system where an admin clicks on the button (Reduce) and the sessions field (Reduces -1 and shows the data & date reduced) every time a swimmer comes through. Thank You VIEWS.PY @api_view(['POST']) def swimmersReduce(request, pk): sw = get_object_or_404(Swimmers,id=pk) # gets just one record current_sessions = sw.sessions + 10 sw.sessions = current_sessions # updates just the one in memory field for sw (for the one record) sw.save() # you may want to do this to commit the new value serializer = SubSerializer(instance=sw, data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, safe=False, status=status.HTTP_201_CREATED) return JsonResponse(data=serializer.errors, safe=False, status=status.HTTP_400_BAD_REQUEST) MODELS.PY class Swimmers(models.Model): name = models.CharField(max_length=200, blank=False) lastname = models.CharField(max_length=200, blank=False) idno = models.CharField(max_length=200, blank=False, null=True) sessions = models.IntegerField(blank=False) totalsessions = models.IntegerField(blank=True, null=True) dateofpayment = models.CharField(max_length=200, blank=True) -
What is the use of class Meta in django?
I have been using django and used class Meta: a lot of times, actually what is the use of it? for example , In django models class Accounts(models.Model): ---some code here--- class Meta: ordering = [-1] In django forms class AccountForm(forms.ModelForm): ---some code here--- class Meta: fields = '__all__' -
Django transfer database to different Django project without messing up the logic
I built a django project with a few models. Now I created a second server with the same setup. This one is meant to be the deployment server. Databases are seperate from the dev-server. However can you tell me if I can simply copy the databases from the dev server to the deploy or will the django logic, since I also mean the user models and permissions etc. The tables wich I created myself are no problem to transfer to the new server. However I am wondering If django gets confuse when I also transfer something like the auth_user Model. Should this work since I also just copied the backend logic as well? -
How can i redirect to same page for certain routes in Django?
enter image description here i would like to restrict signup page after user is logged in so, if user is logged in then return back to same page -
GET data from database to Modal in Django
this file serivces.html has the code used to generate card elements with different id from thedb {% block content%} <div class="container-fluid p-lg-5 d-flex justify-content-lg-around flex-wrap "> {% for package in packages %} <div class="card" style="width: 18rem; "> <div> <img class="cardimg" src="{% static '/images/genomic lab final logo1 ( RGB ).png'%}" class="card-img-top" alt="..."> </div> <div class="card-body"> <h3 class="text-center">{{package.package_name}} <span class="checkup text-center">Checkup</span></h3> <button type="button" class="modalbtn btn btn-primary" data-bs-toggle="modal" data-bs-target="#cardModal"> more details </button> </div> </div> {% endfor%} </div> <<!-- Modal --> <div class="modal fade content-data" id="cardModal" data-url="{%url 'Services_data'%}" tabindex="-1" aria-labelledby="exampleModalLabel" aria-hidden="true"> <div class="modal-dialog"> <div class="modal-content"> <div class="modal-header"> <h5 class="modal-title" id="exampleModalLabel">{{details.pkg_name}}</h5> <button type="button" class="btn-close" data-bs-dismiss="modal" aria-label="Close"></button> </div> <div class="modal-body"> <H4>{{details.content}}</H4> </div> <div class="modal-footer"> <button type="button" class="btn btn-secondary" data-bs-dismiss="modal">Close</button> <button type="button" class="btn btn-primary">Save changes</button> </div> </div> </div> </div> {% endblock %} this is the view.py contain def services(request): packages = Packages.objects.all() context = {'packages':packages} return render(request, 'base/Services.html',context) class AjaxHandlerView(View): def get(self,request,*args, **kwargs): if request.is_ajax(): details = Details.object.all() details_serializers = serializers.serializer('json',details) return JsonResponse(details_serializers,safe=False) return JsonResponse({'message':'Errrorr'}) and this is the base.js contain the ajax code $(document).ready(function(){ $(".modalbtn").on('click',function(){ $.ajax({ url: "{% url 'Services_data' %}", type:'GET', datatype: 'json', success: function(){ $('#cardModal').modal("show"); }, error:function() {console.log('Errorrrr'); } }); }); }); Basically, this code generates cards with different id and when click on … -
Wagtail add thumbnail image to PageChooserPanel
How is it possible to customize the explorer/list view of the PageChooserPanel? I would love to add a thumbnail image here to make life easier for the editors. Their task is to pick out a few dozen artworks (pages) from a large archive. A preview image (and possibly a few additional columns) would greatly simplify this work. I am aware of the get_admin_display_title of a Page as mentioned here. How about a custom version of the PageChooserPanel? I found the AdminPageChooser widget in there, but did not understand how the table of the explorer view is rendered finally. Not sure if it is necessary to get into the weeds to this extend. Would love to see a simple hook like the ModelAdmin list view with its ThumbnailMixin. # wagtail/admin/panels.py from wagtail.admin.widgets import AdminPageChooser class PageChooserPanel(FieldPanel): # ... def get_form_options(self): opts = super().get_form_options() if self.page_type or self.can_choose_root: widgets = opts.setdefault("widgets", {}) widgets[self.field_name] = AdminPageChooser( target_models=self.page_type, can_choose_root=self.can_choose_root ) return opts -
Saving django data field into another field of same table
Adding + 10 to (session field) and trying to save the data into (totalsession field),So that totalsession display on a table in the frontend in a new raw everytime the button is clicked. THANK YOU VIEWS.PY @api_view(['POST']) def swimmersReduce(request, pk): sw = get_object_or_404(Swimmers,id=pk) # gets just one record current_sessions = sw.sessions + 10 sw.sessions = current_sessions # updates just the one in memory field for sw (for the one record) sw.save() # you may want to do this to commit the new value serializer = SubSerializer(instance=sw, data=request.data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data, safe=False, status=status.HTTP_201_CREATED) return JsonResponse(data=serializer.errors, safe=False, status=status.HTTP_400_BAD_REQUEST) MODELS.PY class Swimmers(models.Model): name = models.CharField(max_length=200, blank=False) lastname = models.CharField(max_length=200, blank=False) idno = models.CharField(max_length=200, blank=False, null=True) sessions = models.IntegerField(blank=False) totalsessions = models.IntegerField(blank=True, null=True) dateofpayment = models.CharField(max_length=200, blank=True) -
I am trying to make a webpage in django everything works well
How to write django code inside css style tag to link images from static directory -
after editing any task
I am using paginator in my list view. Every page listed 10 item. If I edit an item from page 5 then I want to redirect back to page 5. Right if I edit an team from page 5, it's redirecting me every time in page 1 -
How can i keep the Searched thing in search bar after searching something in Django?
Whenever i am searching for something in search bar. My search functionality is working properly but the thing i had searched gets disappear. How can i keep the text in search bar after searching? -
rest_framework.exceptions.ParseError: JSON parse error - 'utf-8' codec can't decode byte 0x89 in position 135: invalid start byte
While Uploading an image from Angular 8 to Django, rest_framework.exceptions.ParseError: JSON parse error - 'utf-8' codec can't decode byte 0x89 in position 135: invalid start byte getting this error,while try the API in POSTMAN it got success The code in views.py file is: def post(self, request): image = request.data['image'] request_data = { "image": image, } image_serializer = ImageSerializer(data=request_data) if image_serializer.is_valid(): image = image_serializer.save() response = self.response(is_success=True, status=status.HTTP_201_CREATED, data=self.get_data(image), token="", message="Success") return response -
Python Virtual Environment: changed path of enviroment - can't find packages anymore (How to show the enviroment where its packages are located)
I have a issue with my virutal enviroment and I couldn't find a clear and straightforward awnser for it. I had a fully working virtual enviroment with a lot of packages. My directory changed from "../Desktop/.." to "../Cloud_Name/Desktop/.." and lets assume i can't change that anymore. I'm now able to cd into my eviroment and activate it. If I now want to use any kind of command I get: Fatal error in launcher: Unable to create process using "C: ..." "C: ..." the system cannot find the specified file. I tried sofar to change the directory in "eviroment/Scripts/activate" and "eviroment/Scripts/activate.bat", but it doesn't work. I don't want to install a new enviroment. I'd be very thankfull if someone has a working solution to show my eviroment where its packages are. Thank you in advance for your time and have a great day! -
Django mass email - get single recipient address in every email template
I'm sending email in Django: ... recipient_list = ['first@recipient.com', 'second@recipient.com',] mail = EmailMessage('Subject', 'content body', [sender@email.com], recipient_list) mail.send() In the template I'm rendering I would like to extract single recipient like this. template.html ... This message was sent at {{ datetime_sent }} to address {{ recipient_address }}. I don't want to pass recipient_list in every email in case of mass email, but rather a single recipient address. Is this possible? -
Django: Running dumpdata command programmatically fails
I want to run django's dumpdata command programmatically, however from django.core.management import call_command call_command('dumpdata', 'asdf', indent=2, output=filePath) fails with Unable to serialize database: 'ascii' codec can't encode character '\xdf' in position 83: ordinal not in range(128). running python3 manage.py dumpdata --indent=2 --output=dump.json.gz asdf from the command line works fine though! why won't it work with call_command()? python version: 3.6.9 django version: 3.2.13 $LANG is set to en_US.UTF-8 $LC_ALL is set to en_US.UTF-8 $LC_CTYPE is set to UTF-8 -
How to Deploy Django App on Centos server having domain secured With SSL?
I have a Django App which I want to deploy on a Centos Linux server having a global/public IP which is assigned to a domain and is secured with SSL. The System configuration is as: centos-release-6-10.el6.centos.12.3.x86_64 Apache/2.2.15 (CentOS) When I run the server using: python manage.py runserver 0.0.0.0:8000, then it is only accessible from the browser by passing a local IP say http://192.xxx.xx.xxx:8000/django_app/home But I want to access it from the public/global IP, but it gives an error when I replace the local IP with Global/Public IP or domain assigned to the public IP as: 105.168.296.58 took too long to respond. Try: Checking the connection Checking the proxy and the firewall Running Windows Network Diagnostics ERR_CONNECTION_TIMED_OUT When I simply put this public IP in the browser as https://105.168.296.58 then it redirects the browser to the app/website say https://mywebsite.com/home which is running at port 80 on Apache, and shows the assigned domain instead of IP, so IP is working fine. in settings.py: all hosts are allowed as ALLOWED_HOSTS = ['*'] Methods tried are: by using django-extensions as: python manage.py runserver_plus --cert certname 0.0.0.0:8000 by using django-sslserver as: python manage.py runsslserver 0.0.0.0:8000 The app runs from both of these methods only locally … -
Write a title that summarizes the specific problem The title is the first thing potential a
Write a title that summarizes the specific problem The title is the first thing potential answerers will see, and if your title isn't interesting, they won't read the rest. So make it count: -
I have configured Django REST Framework API Key, I want to expose one API to call without API key in Authorization header, What configuration needed?
This is the code block I have added to my settings.py file. Is there any way to expose an API that can be called without an authorization header? I don't want to use the JWT token. There is no user interface in the application its an integrator project. Please suggest here... Thanks "DEFAULT_PERMISSION_CLASSES": [ "rest_framework_api_key.permissions.HasAPIKey", ] }``` -
AttributeError: 'MiddlewareTests' object has no attribute 'request'
class MiddlewareTests(TestCase): def SetUp(self): self.middleware = MiddlewareClassName() self.request = Mock() def test_logging(self): with self.assertLogs() as captured: MiddlewareClassName.__call__(self, self.request) self.assertEqual(len(captured.records), 1) When I try to run the test_logging, I come across the error "AttributeError: 'MiddlewareTests' object has no attribute 'request'". Why? -
Docusign retrieving and saving the retrieved signed document
I am trying to retrieve and save the DocuSign signed document to my django backend. I have been able to retrieve a path-like string following this code: # You would need to obtain an accessToken using your chosen auth flow api_client = ApiClient() api_client.host = base_path api_client.set_default_header('Authorization', 'Bearer ' + access_token) envelopes_api = EnvelopesApi(api_client) account_id # accountId for your DocuSign account envelope_id # envelopeId that you are working on # produce a PDF combining all signed documents as well as the CoC results2 = envelopes_api.get_document(account_id, 'combined', envelope_id) #TODO - use results file to write or send the file for your use But what results2 returns is something like this: '/tmp/04142042_040424_047446_this_document.pdf' How can I actually retrieve the pdf document from this and save it to my models? I have tried saving it as it is, tried to add the base_url before it and retrieve the file using get request, tried to read it, tried to get the content from it but to no avail. How can I get the actual file from this? -
how to merge two views functions with minor differences
I just wrote two view functions for two different models but they are very similar and only different in some names. what is the best way to merge these two view functions to prevent code repetition? these are the view functions: def manager_scientific(request, *args, **kwargs): context = {} if request.user.role == 'manager': template = loader.get_template('reg/scientific-manager-dashboard.html') users = User.objects.filter(role='applicant', isPreRegistered=True, scientificinfo__is_interviewed=True).order_by('-date_joined') approved = ScientificInfo.objects.filter(is_approved__exact='0').all() context['users'] = users context['all_users'] = len(users) context['approved'] = len(approved) context['survey_choices'] = SURVEY_CHOICES if request.GET.get('user', 'all') == 'all': users = users if request.GET.get('user', 'all') == 'new': users = users.filter(scientificinfo__is_approved__exact='0') field_list = request.GET.getlist('field') if field_list: if 'None' in field_list: users = users.filter(fields__title=None) | users.filter(fields__title__in=field_list) else: users = users.filter(fields__title__in=field_list) gender_list = request.GET.getlist('gender') if gender_list: users = users.filter(gender__in=gender_list) education_list = request.GET.getlist('education') if education_list: users = users.filter(educationalinfo__grade__in=education_list) work_list = request.GET.getlist('work') if work_list: users = users.filter(workinfo__position__in=work_list) province_list = request.GET.getlist('province') if province_list: if 'None' in province_list: users = users.filter(prevaddress__address_province__in=province_list) | users.filter( prevaddress__address_province=None) else: users = users.filter(prevaddress__address_province__in=province_list) query_string = request.GET.get('query_string') if query_string: name_query = None for term in query_string.split(): if name_query: name_query = name_query & (Q(first_name__contains=term) | Q(last_name__contains=term)) else: name_query = Q(first_name__contains=term) | Q(last_name__contains=term) users = users.filter(name_query | Q(educationalinfo__field__contains=query_string) | Q(educationalinfo__tendency__contains=query_string) | Q(educationalinfo__university_name__contains=query_string) | Q(workinfo__organization__contains=query_string) | Q(ngoinfo__ngo_name__contains=query_string) | Q(melli_code__contains=query_string)) users = users.distinct() context['grade_choices'] = [] … -
Django Admin CSS and JS loaded but didn't applied
show image As shown in the image above, I received CSS and JS, but it is not applied. I tried refresh and delete cookies and caches. I don't know how to fix this. machine info: Centos 7.9 python 3.6.8 Django 4.0.6 Nginx -
django forms how to insert auto-generated id from the same fields
I'm trying to insert an item with the following fields (studid,office,sem,sy) and I have another column in my db which will be generated automatically after submitting the form called cl_itemid. This column should based on what I put in office/sem/sy fields for example. I have this form Studid:2021-69420 Office:Dorm Sem:1 SY:2021-2022 |Submit| When I press submit. In my database it's. cl_itemid | studid | office_id | sem | sy | Dorm2021-2022-1 2021-69420 Dorm 1 2021-2022 How can I achieve this? views.py def create_view(request): context = {} form = CreateForm(request.POST or None) if form.is_valid(): form.save() context['form'] = form return render(request, "clearance/insert.html", context) forms.py class CreateForm(forms.ModelForm): class Meta: model = ClearanceItem fields = [ 'studid', 'office', 'sy', 'sem', ] insert.html <form method = "post" enctype="multipart/form-data"> {% csrf_token %} <table> <tr> <td>Studid:</td> </tr> <tr> <td>{{form.studid}}</td> </tr> <tr> <td>Office:</td> </tr> <tr> <td>{{form.office}}</td> </tr> <tr> <td>Sem:</td> </tr> <tr> <td>{{form.sem}}</td> </tr> <tr> <td>SY:</td> </tr> <tr> <td>{{form.sy}}</td> </tr> </table> <input type="submit" value="Submit"> </form> -
Pycharm : Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings
I was trying to get Django installed onto my Pycharm. In Terminal, I typed in python -m pip install Django When I pressed enter on the information, It told me: Python was not found; run without arguments to install from the Microsoft Store, or disable this shortcut from Settings > Manage App Execution Aliases. I already have Python installed and put it as the base interpreter for the file. Not sure why Pycharm wants me to install it from the Microsoft store??? Please help!