Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Where do I have to put my Django middlewares for the cache?
I tried to add caching to my Django project, so I added the cache middleware as stated (for what I've understood) in the official docs and obtained this: MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.middleware.cache.UpdateCacheMiddleware', 'debug_toolbar.middleware.DebugToolbarMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', 'django.middleware.cache.FetchFromCacheMiddleware', ] But this is breaking my authentication system: in other pages I fetch different querysets for different auth levels, but if I add those middlewares the same page is shown to all the users. How can I implement caching in my project and still be able to provide pages different querysets for different users? -
Django:Update values from my user model from my website and save changes to the database.But this creates a new copy
i have created this view but it is creating another instance instead of updating the existing one. ''' def edit(request , user_id): uk = user.objects.get(id=user_id) if request.method == 'POST': euser = user.objects.get(id=user_id) form = userForm(request.POST or None, instance=euser) form.save() return HttpResponseRedirect(reverse('characters:index')) else: form = userForm() return render(request, 'characters/edit.html' , {'form':form,'uk':uk}) ''' -
Map database field only once in django rest framework
I am using django rest framework for making rest api's. Below are my views: from django.contrib.auth.models import User, Group from rest_framework import viewsets from .serializers import UserSerializer, GroupSerializer # Create your views here. class UserViewSet(viewsets.ModelViewSet): queryset = User.objects.all().order_by('-date_joined') serializer_class = UserSerializer class GroupViewSet(viewsets.ModelViewSet): queryset = Group.objects.all() serializer_class = GroupSerializer Below are my serializers from django.contrib.auth.models import User, Group from rest_framework import serializers class UserSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = User fields = ['username', 'url', 'email', 'groups'] class GroupSerializer(serializers.HyperlinkedModelSerializer): class Meta: model = Group fields = ['name', 'url'] In this case i am using models from admin app of django. I want to map fields to database for example Assume i have a field username in the database and i am want return name in the response of my api. For this i have found this solution: name = serializers.CharField(source='username') by adding this above instruction and changing username in fields from 'username' to name in serializer it works, however in case of a complex database where one entity can have relation with multiple entities for e.g a user can be a part of a group, a user can post, a user can comment, a user can like e.t.c. If i go with … -
TypeError: detail() missing 1 required positional argument: 'request'
I am new in Django. Initially I had this function based view - @api_view(['GET', 'PUT', 'DELETE']) def detail(self,request, pk): """ Retrieve, update or delete a product instance. """ try: product = latesttrial.objects.get(pk=pk) newproduct = latesttrial.objects.all() except latesttrial.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': serializer = latestSerializer(product,context={'request': request}) return Response(serializer.data) elif request.method == 'PUT': serializer = latestSerializer(product, data=request.data,context={'request': request}) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Then it give this error - TypeError: detail() missing 1 required positional argument: 'pk' For this I did these changes according to this answer - missing 1 required positional argument: 'pk' Then I had this function based view @api_view(['GET', 'PUT', 'DELETE']) def detail(request, *args, **kwargs): """ Retrieve, update or delete a product instance. """ try: pk = self.kwargs.get('pk') product = latesttrial.objects.get(pk=pk) newproduct = latesttrial.objects.all() except latesttrial.DoesNotExist: return Response(status=status.HTTP_404_NOT_FOUND) if request.method == 'GET': pk = self.kwargs.get('pk') serializer = latestSerializer(product,context={'request': request}) return Response(serializer.data) elif request.method == 'PUT': pk = self.kwargs.get('pk') serializer = latestSerializer(product, data=request.data,context={'request': request}) if serializer.is_valid(): serializer.save() return Response(serializer.data) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) Then I had this error - TypeError: detail() missing 1 required positional argument: 'request' This is my view - from django.conf.urls import url, include from rest_framework.urlpatterns import format_suffix_patterns from .views import partial, Detailspartial, … -
How create and test factory for telebot?
I want to create factory for bot with pyTelegramBotAPI: from django.conf import settings from typing import Dict def bot_factory(config: Dict): token = config['ACCESS_TOKEN'] webhook = f'https://{config["HOST"] + reverse("telegram:webhook", kwargs={"token": config["ACCESS_TOKEN"]})}' proxy = { 'https': r'https://{}:{}@{}:{}'.format( config["PROXY"]["LOGIN"], config["PROXY"]["PASSWORD"], config["PROXY"]["HOST"], config["PROXY"]["PORT"] ) } import telebot telebot.apihelper.proxy = proxy bot = telebot.TeleBot(token) return bot bot = bot_factory(settings.TELEGRAM) I have some questions: Is this the best way to import telebot inside the function? How to test that bot has correct proxy (exactly that I passed in config)? -
how to use multselect field in django admin for filtering
I am using multiselectfield in my model to define one field and also register that model to admin.py when I am using that field in list_filter admin page not able to filter my data. How can I use multiselectfield as well as use it for filters or is there any better way to handle it? -
[PYTHON 3][DJANGO 2] SAML 2.0
In my django 2 and python 3 app I need to introduce support to Single Sign On a SAML 2.0 provider. Searching for package I've found pySalm2 and django-saml2-auth Unfortunally it seems like it doesn't work on Python 3. On official pySalm2 there is a note: For all this to work, you need to have Python installed. The development has been done using 2.7. There is now a 3.X version. So. Is there a way to make it works on Python 3? -
How to solve:type error.context must be a dict rather than Context,
How to solve:type error.context must be a dict rather than Context,i run server.and i see the above error ob the page web in chrom. -
if date_hierarchy + '__month' in request.GET not working
i'm making this code def get_next_in_date_hierarchy(request, date_hierarchy): if date_hierarchy + '__day' in request.GET: return 'hour' if date_hierarchy + '__month' in request.GET: return 'day' if date_hierarchy + '__year' in request.GET: return 'week' return 'month' to return the filter specific in admin but not working because '__day' not exists in request my models: contact = models.ForeignKey(Contact, verbose_name=_('User'),null=True, blank=True, on_delete=models.SET_NULL) installation_date = models.DateTimeField(verbose_name=_('Date Installation'),auto_now=True) session_id = models.CharField(verbose_name=_("Session"), max_length=100, default=None, null=True, blank=None) what can i do to '__day' exist in the request -
Django-filter : filtering using function with a request attribute
I'm building a website with Django and I have a little problem with filtering. I have a model User which has an attribute location and I want the user to be able to search for other users near its own location. I have a function distance(location1, location2) computing the distance between two locations. I need user A to search for all users B for which distance(locationA, locationB) is below a value choosen by A. I need to get locationA from the request and this, combined with the use of a function inside the filter, makes things a little bit complicated for a beginer like me. Here is what I have tried so far : import django_filters class LocationFilter(django_filters.FilterSet): distance = django_filters.NumberFilter( field_name='location', method='distance_filter', label='...', widget=forms.NumberInput(attrs={'class': 'form-control'}), ) class Meta: model = User fields = [SOME ATTRIBUTES] def distance_filter(self, queryset, name, value): return queryset.filter(location.distance(request__user__location)__lte = value) Currently, I get a SyntaxError: invalid syntax. I think I'm misusing the Filter.method of django-filter but the lack of documentation on the internet (other than basic examples) makes it difficult to understand what I'm doing wrong. I would greatly appreciate some help. Thanks in advance ! -
TypeError: Object of type RecievingObjectImages is not JSON serializable
Hi am trying to implement select_related query for processing data from two tables RecievingObjectImages and ObjectUpdationImages but am consistently getting stuck at Debug output (Pdb) TypeError: Object of type RecievingObjectImages is not JSON serializable > /Users/prady/github/GIS/papli-production-PH/GisServer/reciever/views.py(77)get() -> return HttpResponse(json.dumps({'mapped_images': mapped_images}), Models File class RecievingObjectImages(models.Model): """Original and Masked Object Images""" name = models.CharField(max_length = 100, unique = True, primary_key=True) area = models.IntegerField() ........ RCreated_date = models.DateTimeField(auto_now_add=True) ROwner = models.CharField(max_length = 100) # agency_name = models.CharField(max_length=100) rawImage = models.ImageField(upload_to=imageNameForRawImage,) maskedImage = models.ImageField(upload_to=imageNameForObjectImage,) objects = GeoManager() def __str__(self): return self.name class Meta: verbose_name_plural = 'Object Mapping' class ObjectUpdationImages(models.Model): """ Update Object Image wrt name""" name = models.ForeignKey(RecievingObjectImages, on_delete=models.PROTECT, unique=True) ........ is_filled = models.BooleanField(default=True) checked = models.BooleanField(default=False) def __str__(self): return str(self.name) Views File class Mapping_photos_select_related(APIView): """Mapping all images together""" # breakpoint() def get(self, requests): mapped_images_qs = ObjectUpdationImages.objects.select_related('name').all() mapped_images = [] for image in mapped_images_qs: mapped_images.append({ 'name' : image.name, 'updated_image' : image.updated_image, ............. 'rawImage' : image.name.rawImage, 'maskedImage' : image.name.maskedImage, }) # return mapped_images return HttpResponse(json.dumps({'mapped_images': mapped_images}), content_type='application/json; charset=utf8') -
online storage with Ionic without firebase or offline storage
hello everyone I first tried to use sqlite built in module in ionic-native but I just realised it is only for offline storage.Now if I want to connect my ionic app to a django server using rest framework is it possible that a user in the ionic app inserts data in django database?if so,how to do it seriously? -
Weblate production server setup with nginx,uwsgi causing no such file or directory for css and js files
I was asked to setup a weblate server, but I have no expierence with Django, uWSGI and Virtualenv. So I started with this guide: https://docs.weblate.org/en/latest/admin/install/venv-debian.html I am stucked with this error in the Nginx log: 2020/01/28 13:24:34 [error] 702#702: *16 open() "/var/weblate-env/lib/python3.7/site-packages/weblate/static/CACHE/js/output.00a0a12ff336.js" failed (2: No such file or directory), client: __IP__, server: __SERVER__, request: "GET /static/CACHE/js/output.00a0a12ff336.js HTTP/1.1", host: "__SERVER__", referrer: "__DOMAIN__" 2020/01/28 13:26:18 [error] 702#702: *21 open() "/var/weblate-env/lib/python3.7/site-packages/weblate/static/CACHE/css/output.13b293769894.css" failed (2: No such file or directory), client: __IP__, server: __SERVER__, request: "GET /static/CACHE/css/output.13b293769894.css HTTP/1.1", host: "__SERVER__", referrer: "__DOMAIN__" As you can see I started to installed with (wanted to have this on the /var partition): virtualenv --python=python3 /var/weblate-env pip install Weblate Here is the current configuration: Nginx root@weblate:~# cat /etc/nginx/sites-enabled/weblate server { listen 80; server_name __SERVER__; root /var/weblate-env/lib/python3.7/site-packages/weblate; location ~ ^/favicon.ico$ { # DATA_DIR/static/favicon.ico alias /var/weblate-env/lib/python3.7/site-packages/weblate/static/favicon.ico; expires 30d; } location ~ ^/robots.txt$ { # DATA_DIR/static/robots.txt alias /var/weblate-env/lib/python3.7/site-packages/weblate/static/robots.txt; expires 30d; } location /static/ { # DATA_DIR/static/ alias /var/weblate-env/lib/python3.7/site-packages/weblate/static/; expires 30d; } location /media/ { # DATA_DIR/media/ alias /var/weblate-env/lib/python3.7/site-packages/weblate/media/; expires 30d; } location / { include uwsgi_params; # Needed for long running operations in admin interface uwsgi_read_timeout 3600; # Adjust based to uwsgi configuration: #uwsgi_pass unix:///run/uwsgi/app/weblate/socket; uwsgi_pass 127.0.0.1:8080; } } uWSGI root@weblate:~# cat … -
How to set up properly AJAX in Django
I am newbie in using AJAX within a Django project. There is something wrong in my code. I have tried to follow these posts: Returning Rendered Html via Ajax Django render template in template using AJAX Django render template on AJAX success But there is a concept that I don't understand. I created an asynchronous task and I would like to follow the process by updating a template: I created two urls: path('checkTread/<int:id>/', views.checkThreadTask, name='checkThreadTask'), path('endTread/<int:id>/', views.endThreadTask, name='endThreadTask'), and two views: def checkThreadTask(request, id): task = ThreadTask.objects.get(pk=id) if request.is_ajax(): html = render_to_string('fund/task/processing_task.html', {'text': task.text}) return HttpResponse(html) def endThreadTask(request, id): task = ThreadTask.objects.get(pk=id) return JsonResponse({'is_done': task.is_done}) The purpose of checkThreadTask is to update my template and endThreadTask to send a boolean value when the process is finished in order to stop the ajax request: In my template: <!-- Asynchronous tasks --> <script type='text/javascript'> $(document).ready(function(){ $('#fund_dropdown').on('change',function(){ console.log( $(this).val() ); var i = 0; console.log(i) var threadInterval = setInterval(function(){ checkTask("/checkThread/" + data.id) endTask("/endThread/" + data.id, function(check){ if(check.is_done){ window.clearInterval(threadInterval) } if(++i === 1200){ window.clearInterval(threadInterval) } }) },1000) }) }) function checkTask(url){ $.ajax({ type: "POST", url: url, data: {'csrfmiddlewaretoken': '{{csrf_token}}'}, success: function(data) { console.log("check!") $('#task_text').html(data); } }) } function endTask(url, cb){ $.ajax({ type: "GET", cache: … -
Django Mealtime server listener
I am pretty good at django. I have postgresql with some table and this table populated by a C++ apps. Now i want to build django app to visualize realtime basis whenever any changes occur in the database, it should update realtime in my django frontend. I am not getting what technology to pic, I have heard of django-channel but not quite sure if i can do it with it. This post is the purpose to get technology recommendation suggestion. Can anyone help in this case? -
Using Response code or message with get_queryset method in djago restframework or custome response
Currently I am using django rest framework. In the case of filtering I used an extra ValidationErrorere class to return some extra response. Here is my ProductList class to filter data. class ProductList(ListAPIView): serializer_class = ProductSerializer def get_queryset(self): queryset = Product.objects.all() status = self.request.query_params.get('status', None) type = self.request.query_params.get('type', None) if status is not None: queryset = queryset.filter(status=status) if type is not None: queryset = queryset.filter(type=type) if not queryset: raise ValidationError return queryset class ValidationError(APIException): status_code = status.HTTP_404_NOT_FOUND default_detail = ({ 'response_code': '404', 'response': status.HTTP_404_NOT_FOUND , 'message': 'No data is available', }) Here i used a custom ValidationError class to return some extra value. When there is no data that means qeuryset returns no data then it shows these output. { "response_code": "404", "response": "404", "message": "No data is available" } Now It returns this result. When queryset is not Empty. emphasized text [ { "id": 6, "SKU": 11, "name": "Item_11", "type": "paper", }, ] But I want to show the result with the response code. like this..... [ { "response_code": "200", "response": "200", "message": "Ok" } { "id": 6, "SKU": 11, "name": "Item_11", "type": "paper", }, ] -
Django Converting HttpResponse to PDF for multiple Instances And Zipping them not working
I'm trying to get multiple instances from a query set, then for each instance, create a PDF from a HttpResponse object using the xhtml2pdf package, then eventually zip all of the generated PDFS for download. This is what I have so far: def bulk_cover_letter(request, ward_id, school_cat_id): report_files = {} school_type = SchoolType.objects.get(id=school_cat_id) ward = Ward.objects.get(id=ward_id) schools_in_school_type = Applicant.objects.filter( school_type=school_type, ward_id=ward_id, award_status='awarded').order_by().values_list( 'school_name', flat=True).distinct() for school in schools_in_school_type: cheque_number = Applicant.objects.filter(school_type=school_type, ward_id=ward_id, award_status='awarded', school_name=school).values_list('cheque_number__cheque_number', flat=True).distinct() beneficiaries = Applicant.objects.filter(school_type=school_type, ward_id=ward_id, award_status='awarded', school_name=school) total_amount_to_beneficiaries = Applicant.objects.filter(school_type=school_type, ward_id=ward_id, award_status='awarded', school_name=school).aggregate(total=Sum('school_type__amount_allocated')) context = { 'school_name' : school, 'beneficiaries' : beneficiaries, 'total_amount_to_beneficiaries' : total_amount_to_beneficiaries, 'title' : school + ' Disbursement Details', 'cheque_number': cheque_number[0] } response = HttpResponse('<title>Cover Letter</title>', content_type='application/pdf') filename = "%s.pdf" %(cheque_number[0]) content = "inline; filename=%s" %(filename) response['Content-Disposition'] = content template = get_template('cover_letter.html') html = template.render(context) mem_fp = io.BytesIO() pdf = pisa.CreatePDF( html, dest=mem_fp, link_callback=link_callback) resp = HttpResponse(mem_fp.getvalue(), content_type='application/pdf') resp['Content-Disposition'] = "attachment; filename=%s" %(filename) report_files[filename] = resp mem_zip = io.BytesIO() with zipfile.ZipFile(mem_zip, mode="w") as zf: for filename, content in report_files.items(): zf.writestr(filename, content) response = HttpResponse(mem_zip, content_type='application/zip') response['Content-Disposition'] = 'attachment; filename="{}"'.format(f'{ward}_cover_letters.zip') return response Everything works fine until the zipping part. I'm getting the error: object of type 'HttpResponse' has no len() How do I go about … -
IntegerField subtraction in Django
In this template ,I try to subtract two Integer Fields . {% load mathfilters %} <html> <p> {{ post.wallet|sub:post.cost }}</p> <p> {{ post.wallet }}</p> </html> However, I'm getting a VariableDoesNotExist at error . Also it displays Failed lookup for key [%s] in %r. With my modest level of understanding , I'm not able to catch the error. Can anyone help me? -
invalid syntax (<string>, line 1) with json.loads
i made a filter to a model called ArchivedUsers, so first a retrieve all the rows and it has a text field called data, i had a syntax error invalid syntax (<string>, line 1) in this line data = json.loads(json.dumps(eval(archivedUser.data))) i don't know what does it mean. -
django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)") in PHPMyAdminSQL
django.db.utils.OperationalError: (1045, "Access denied for user 'root'@'localhost' (using password: YES)") in PHPMyAdminSQL any help, would be appreciated. DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'HOST': 'localhost', 'NAME': 'deebaco_shop', 'USER': 'root', 'PASSWORD': 'root', 'PORT': '3306', } } -
How to validate an inline formset within a create view
I have an inline formset and 2 different forms within a create view of one of the forms. All my fields in the model are blank=False and the inline formset has a minimum validation of 1. If I try to send the form without any fields from the create view form, it displays the classic message "Please fill out this field" without rerendering the page. I want to achieve the same thing when the formset is not filled correctly. Also the same for the second form (this form is only displayed when the formset is filled based on the choice). I am able to get the error messages re rendering the form but I'd like to do it before sending it to the server. Is it possible changing something in the model or I need to do it via js on the front? Many thanks. Views: class SolicitacionReferenciaCreate(CreateView): template_name = 'microcredito/solicitacion_form.html' model = ContactoInfo fields = ['nombre', 'destinoPrestamo', 'apellido'] success_url = reverse_lazy('accounts/login') def get_context_data(self, **kwargs): data = super(SolicitacionReferenciaCreate, self).get_context_data(**kwargs) referencias_form_1 = ReferenciaForm() data['referencias_form_1'] = referencias_form_1 if self.request.POST: data['plataformas'] = IngresosFormSet(self.request.POST) else: data['plataformas'] = IngresosFormSet() return data def form_valid(self, form): context = self.get_context_data() plataformas = context['plataformas'] with transaction.atomic(): #ContactoInfo form if … -
Access SerializerMethodField in non ModelViewSet - {TypeError}getattr(): attribute name must be string
I am trying to access my serializer fields on a non-ModelViewSet (APIView) views.py class MyView(APIView): def get(self, request): serializer = SurveysDemographicsSerializer('some_object') return Response(serializer.data) serialzers.py class MySerializer(drf_serializers.Serializer): x = SerializerMethodField(object) def get_x(self): return 42 But keep getting the error: {TypeError}getattr(): attribute name must be string Expecting to return 42 in this case, Is there a way to solve this? I managed to bypass it by calling the function itself on views: serializer.get_x() But this seems awkward, If it was a ModelViewSet and a ModelSerilizer I could use fields=['x'] but this is not the case.. Thanks for the help! -
Django dynamic form choices not seen in POST
There is a form without model class TestForm(forms.Form): sk = MultipleChoiceField(widget=forms.CheckboxSelectMultiple) def __init__(self, *args, **kwargs): super(TestForm, self).__init__(*args, **kwargs) that has dynamically generated choices based on external API request. views.py form.fields["sk"].initial = sk_tuples My goal is to change selections and send form back. When sending POST the form behaves like being empty and throws "Select a valid choice. 2 is not one of the available choices." error. I'm migrating from Flask and it was working without Javascript. What is the simplest way to change forms dynamically in Django? -
mocking requst object python
I am trying to mock request object. I take request.query_params methods into the view. Then in the unit test for argument i use 'request' an that gives me an error: AttributeError: Mock object has no attribute 'query_params': Then i try this: class RequestFixture: query_params = {'start': "2019-01-01", 'end': "2019-12-30"} and it works. But i want to MOCK this request with the same method which holds some data. I understand that i have to mock not onley request but and builtin method 'query_parmas' too and put same value on but i don't know how? Here is some snippets from my code: view.py class GroupsOverview(APIView): def get(self, request, *args, **kwargs): days = request.query_params data = _collect_needed_data(object_1_id, object_2_id, days) ... and from my unittes.py: @mock.patch('owners.views.get_object_or_404') def test_get_method_invalid_object(self, mock_get_object_or_404): class RequestFixture: query_params = {'start': "2019-01-01", 'end': "2019-12-30"} # (but if i pass 'request' as an argument in get functions it will breaks) mock_get_object_or_404.side_effect = Http404('No Object matches the given query.') with self.assertRaises(Http404) as ex: GroupsOverview().get(RequestFixture, hash=self.hash_value) self.assertEqual(ex.exception.args, ('No Object matches the given query.',)) -
insert dataframes into an existing template without deleting style
i hope you having a nice day/night. im trying to insert a dataframe from pandas to a load_workbook(template) wich has color and img. the problem is that have been searching for a solution during days and i finaly found one. -create a copy of the template and insert the dataframe in it with win32com. pythoncom.CoInitialize() # Open excel to access to template excel = win32.GetObject(None, 'Excel.Application') # def workbook wb = excel.Workbooks.Open(extract_filename) # each sheet first_sheet_info=wb.Worksheets("NOTES") second_sheet_C1=wb.Worksheets("C1. Scheduled Maintenance Tasks") third_sheet_C2= wb.Worksheets("C2. Findings&Corrective Actions") # inserting datas into each sheet first_sheet_info.Range(first_sheet_info.Cells(2,1),# Cell to start the "paste" first_sheet_info.Cells(1+len(df3.index)-1, 1+len(df3.columns)-1) ).Value = df3.values second_sheet_C1.Range(second_sheet_C1.Cells(4,1),# Cell to start the "paste" second_sheet_C1.Cells(4+len(df1.index)-1, 1+len(df1.columns)-1) ).Value = df1.values third_sheet_C2.Range(third_sheet_C2.Cells(4,1),# Cell to start the "paste" third_sheet_C2.Cells(4+len(df2.index)-1, 1+len(df2.columns)-1) ).Value = df2.values # excel close and save wb.Close(SaveChanges=1) excel.Quit() This one works but only for a few files because there special char that i can't modify in the database and the terminal returns me an error because of it. so i tried with another module, openpyxl, to open the template and insert the data with the writer. it work but it delete the style of the template. so i c'ant use it . dfs = {'NOTES':df3, 'C1. Scheduled Maintenance …