Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Trying in make insert query using cursor in django and can not get rid off this error TypeError: not all arguments converted during string formatting
I am trying to make aan insert query using cursor in Django, but this error shows I searched for more than one solution but nothing helped the error is: sql = sql % tuple('?' * len(params)) TypeError: not all arguments converted during string formatting I tried to use '%s' instead of '?' but it didn't work def insert_DTARFDE2003SYD0827(sourcePE,sourceInterFace,targetPE,targetInterFace): params = (sourcePE, sourceInterFace,targetPE,targetInterFace) if sourcePE!=None and sourceInterFace!=None and targetPE!=None and targetInterFace!=None: sql=" insert into DTA.RFDE2003SYD0827 values ( '?','?',NULL,NULL,NULL,'?','?' " with connections['DataAdmin'].cursor() as cursor: cursor.execute(sql,params) The error is: sql = sql % tuple('?' * len(params)) TypeError: not all arguments converted during string formatting -
I cannot make my NRF24L01 communication(raspberry pi to many arduinos) work consistently
I am using a Master-Slave protocol and the NRF24L01 module for my Raspberry Pi to Arduino communication. In my case the Raspberry Pi is the master and it requests via a specific pipe(hex address) a radio response from one of Arduinos in the network. I am also using Django and Celery for my project, so I wrote a celery @task that gathers the response information from the Arduino. My problem is that most of the time when I change the pipe in order to talk to another Arduino, the radio signal is not felt by the Arduino so the request from the RPi just times out. My bet is that I do not "clean" the connection properly in the @task after I'm done with the receiving of the information. I have tried many different things but none were of success. Any help is appreciated. I thought maybe it had something to do with the GPIO.cleanup() function at the and of my task, but that didn't fix my problem. I have tested over and over again to see if I could make up some kind of pattern in the loss of connection but I was unsuccessful. I have also seen that … -
How do i update boolean field on Django model?
I have implemented a view that is supposed to update two boolean fields on a Django model i.e is_published and submitted. However , currently, the view is only able to update the first boolean field(is_published) and leaves out the second one(submitted). What am i doing wrong and how can I implement a solution that updates both fields at the same time? Here is my code Model class Course(models.Model): is_published = models.BooleanField(default=False) submitted = models.BooleanField(default=False) View class UpdateVideoAPIPublishView(generics.UpdateAPIView): """ Update course """ permission_classes = (IsAuthenticated,) renderer_classes = (CourseJSONRenderer,) serializer_class = CourseSerializer def update(self, request, *args, **kwargs): course = get_object_or_404( Course, slug=self.kwargs['slug']) if not course.is_published: course.is_published = True course.submitted = False course.save() return Response( {"message": "Course updated succesfully"}, status=status.HTTP_201_CREATED) raise serializers.ValidationError( 'Course already published' ) -
How to read google calendar events of user after getting access token?
I want to get google calendar events of my users in django and I wrote the following code. This code works and saves access token of user but I don't know what I should to do to get google calendar events of user after it. I had some problem before this and asked it in this question and tried to solve it and now I am here. can some one help me? in url: url(r'^new_event/$', views.new_event, name="new_event"), url(r'^oauth2_callback', OAuth2CallBack.as_view(), name='oauth2_callback'), url(r'^access_to_google_calendar$', views.access_to_google_calendar, name="access_to_google_calendar"), in view: def access_to_google_calendar(request): # Following line is for getting google calendar events of user to show him flow = OAuth2WebServerFlow(settings.CLIENT_ID_CALENDAR, settings.CLIENT_SECRET_CALENDAR, scope='https://www.googleapis.com/auth/calendar', redirect_uri=settings.REDIRECT_URI_CALENDAR) generated_url = flow.step1_get_authorize_url() return HttpResponseRedirect(generated_url) class OAuth2CallBack(View): def get(self, request, *args, **kwargs): code = request.GET.get('code', False) if not code: return JsonResponse({'status': 'error, no access key received from Google or User declined permission!'}) flow = OAuth2WebServerFlow(settings.CLIENT_ID_CALENDAR, settings.CLIENT_SECRET_CALENDAR, scope='https://www.googleapis.com/auth/calendar', redirect_uri=settings.REDIRECT_URI_CALENDAR) credentials = flow.step2_exchange(code) http = httplib2.Http() http = credentials.authorize(http) credentials_js = json.loads(credentials.to_json()) access_token = credentials_js['access_token'] # Store the access token in case we need it again! username = request.user.username with open('token.csv', 'w') as file: fieldnames = ['user', 'token'] writer = csv.DictWriter(file, fieldnames=fieldnames) writer.writeheader() writer.writerow({'user': username, 'token': access_token}) request.session['access_token'] = access_token return redirect('new_event') def post(self, request, … -
How can I count the number of download of a static file on my django website?
I am beginner with django, and I would to create on my website, a library which allows to dowload executables files, wich I created myself. And I would like to count how many times each file has been downloaded. So I thought to a middleware, knowing that I am able to make a middleware which counts and displays the number of times a page has been viewed : def stats_middleware (get_response): def middleware (request): try : p = Stat.objects.get(url = request.path) p.views_number = F('views_number')+1 p.save except Stat.DoesNotExist : p = Stat.objects.create(url= request.path) response = get_response(request) response.content += bytes( "cette page a été vue {} fois.".format(p.views_number), "utf8" ) return response return middleware And I thought that, if I managed to open the download in a new page, I could count the number of times it appears and thus the number of downloads of the file. But I did not manage to open the download in another tab. if you have any idea what to do, do not hesitate to let me know, thanks in advance, and sorry for my english which is not very good. -
Django 2.2+ call rest api, filtering on list of ids
How can I use the in operator for filtering on a list of ids for the results of a ViewSet in the django rest framework? A solution to the same question was found a few years ago, however the accepted solution no longer works: Call django rest API with list of model ids The viewset could for example be defined as: class MarkerViewSet(viewsets.ModelViewSet): queryset = Marker.objects.all() serializer_class = MarkerSerializer -
Replace placeholders in text with input fields with django templates
I'd like to render a page with django templates that is able dynamically place input fields based on the provided text templates. An example i found but with vue found here Given a text like My name is {name}, I am {age} years old. I live in {location} I'd like to replace {name}, {age}, {location} with input fields. -
what are the chances for this random unique Id generator to collide?
i want to know what are the chances for this unique id generator to collide https://github.com/vejuhust/blog-code/blob/master/python-short-id-generator/short_id_v5.py i wanted to generate a unique url for my Django project. is it going to be safe to use. i am a beginner in python and Django. -
the site took too long to respond
I deployed my django app on iis using wfastcgi but the app doesn't load on any browser. In mozilla the app keeps trying to connect on and on meanwhile in chrome I get the app took too long to respond. I deployed my app from the anaconda environment and I cannot see any error. Any tips to fix this issue? -
Django: AttributeError: 'Q' object has no attribute 'count'
I try to get the count of all attendees. I created the following for loop and query set. However, I always get the error AttributeError: 'Q' object has no attribute 'count'. Do you have an idea how to fix that? # Get count of attendees per ticket and then combine these tickets = Ticket.objects.filter(event=3) count = 0 for ticket in tickets: new_count = ticket.attendees.filter=Q( canceled=False, order__status__in=( OrderStatus.PAID, OrderStatus.PENDING, OrderStatus.PARTIALLY_REFUNDED, OrderStatus.FREE, ), ).count() count += new_count print(count) -
How to add pdf file to django response
I have a model that contains a link to the file stored in AWS S3. class Documents(models.Model): """ uploaded documents""" author = models.ForeignKey(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) filedata = models.FileField(storage=PrivateMediaStorage()) filename = models.CharField(_('documents name'), max_length=64) created = models.DateTimeField(auto_now_add=True) filetype = models.ForeignKey(Doctype, on_delete=models.CASCADE, blank=True) url_link = models.URLField(default=None, blank=True, null=True) url_link is the field using pre-signed URLs from boto3 for to get access to privat S3 repo. I'm trying to make a function that receives the model's id, loads it by reference and passes it to response for further processing in the SPA. Based on the answers found on the stackoverflow, I wrote the following function def view_pdf(request, pk): pdf = get_object_or_404(Documents, pk=pk) response = requests.get(pdf.url_link) with open(response, 'rb') as pdf: response = HttpResponse(pdf.read(), mimetype='application/pdf') response['Content-Disposition'] = 'inline;filename=some_file.pdf' return response pdf.closed BUt got an error TypeError at /api/v1/files/pdf/90 expected str, bytes or os.PathLike object, not Response error traceback Internal Server Error: /api/v1/files/pdf/90 Traceback (most recent call last): File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/core/handlers/exception.py", line 41, in inner response = get_response(request) File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/core/handlers/base.py", line 187, in _get_response response = self.process_exception_by_middleware(e, request) File "/home/y700/Env/healthline/lib/python3.7/site-packages/django/core/handlers/base.py", line 185, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "/home/y700/projects/healthline/lifeline-backend/apps/files/views.py", line 68, in view_pdf with open(response, 'rb') as pdf: TypeError: expected str, bytes or os.PathLike object, … -
'AnonymousUser' object has no attribute 'profile'
Can someone help me? I've been going around and around with questions here on SO but can't get the answer. I'm getting 'AnonymousUser' object has no attribute 'profile' My views.py are: @login_required def profile(request): if user.is_authenticated: if request.method == 'POST': u_form = UserUpdateForm(request.POST, instance=request.user) p_form = ProfileUpdateForm(request.POST, request.FILES, instance=request.user.profile) if u_form.is_valid() and p_form.is_valid(): u_form.save() p_form.save() messages.success(request, f'Your account has been updated!') return redirect('profile') else: u_form = UserUpdateForm(instance=request.user) p_form = ProfileUpdateForm(instance=request.user.profile) context = { 'u_form': u_form, 'p_form': p_form } else: return redirect('/login/') return render(request, 'aml/profile.html', context) -
How to separate logic correctly into separate applications?
I implement simple django website, where I tried to separate different parts from website in different APPs, but I'm facing some problems: I have two django apps, right now (core - where are heaader, footer, index) and (objects - where I have objects which I want to list at index page): core/templates/header.html (header elements, login, logout etc) core/templates/index.html (html tags, blocks, etc..): <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> {% block 'head-title' %} {% endblock %} {% load static %} <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.3.1/css/bootstrap.min.css" integrity="sha384-ggOyR0iXCbMQv3Xipma34MD+dH/1fQ784/j6cY/iJTQUOhcWr7x9JvoRxT2MZw1T" crossorigin="anonymous"> <script src="https://code.jquery.com/jquery-3.4.1.min.js" integrity="sha256-CSXorXvZcTkaix6Yvo6HppcZGetbYMGWSFlBw8HfCJo=" crossorigin="anonymous"> </script> <script src="{% static 'core/js/custom.js' %}"></script> </head> <body> {% include 'header.html' %} {% block 'body' %} {% endblock %} </body> </html> core/templates/home.html (homepage - here I want to list all Objects and implement filters for them): {% extends 'index.html' %} {% block 'body' %} {% endblock %} core/views.py: from django.shortcuts import render, redirect def show_home_page(request): return render(request, "home.html") Ok everything is perfect, but now I don't know how to add listing of elements: What I tried is to call Object model in show_home_page() function with Object.objects.all() and pass this list to home.html and for filters to call same function with parameters, for example def show_home_page(request, price_up, distance): But then I mess … -
Djanog/drf - delete method
I want to delete likes from my Likes table. for which I am making an axios call from the front end with axios({ method: "delete", url:http://127.0.0.1:8000/api/delete/, params: { companyid: xyz } }) It is supposed to delete a like that has company_id = xyz in it. The Url looks like this path('delete/', DeleteLikesView.as_view()), (/api/ is included in the project's urls.py. So taken care of...) and the DeleteLikesView - class DeleteLikesView(DestroyAPIView): queryset = Likes.objects.all() serializer_class = LikesSerializer def perform_destroy(self, request): print(self.kwargs['companyid']) companyid = self.kwargs['companyid'] instance = Likes.objects.get( company_id=companyid, user_id=request.user.id) instance.delete() I am either being stuck with errors 403 (csrf_token error. Although I tried using csrf_exempt, no luck) or 405 method not allowed(for which I refered this. the solution in this question puts me back with 403 error) Any help is appreciated. Thank! -
not able to traverse AJAX response
I am trying to send some data to save in database using AJAX request. How can I get all the values using some loop or anything. I've tried doing dataType and contentType as well. 'application/JSON' in both My Script in Template var values = { answer: [{'age': '21'},{'name': ['abc', 'xyz']}], user_id: 11 }; $.ajax({ type: 'post', url: 'respMap', data: values, success: function(result) { console.log("done"); }, error: function () { console.log("error"); } }); My Views def saveResponseMap(request): data = request.POST print(data) return HttpResponse(data) I expected a JSON but it "answer[0][name]" is coming as string in the response {'answer[0][age]': ['21'], 'answer[1][name][]': ['abc', 'xyz'], 'user_id': ['11']} -
MySQL: cannot save non-ascii characters in database
Whenever I try to save an address with non-ascii characters like: 721-1 Higashishiokōjichō, Shimogyō-ku, Kyoto, 600-8216, Japan Mysql fails with an error: OperationalError(1366, "Incorrect string value: '\\xC5\\x8Djich...' for column 'formatted_address' at row 1") What is the best practice to save foreign language characters in database? Should I just ignore these characters in code? Or find a way to store them in MySQL (how?) ? -
Cost calculations: suggestions for code improvements
I stumbled upon this piece of code to calculate costs based on country code and city(optional). There is also a condition that countries in Asia have separate pricing logic depending on both country and city and they are stored in a different table (for segregating regional price variances). For the rest, it's only dependent on country code. Let's assume we must have separate tables Asia & the rest. Please suggest some improvements in the below code. def get_cost_by_location(country_code: str, city=None) -> Optional[models.OperatorCost]: cost = None # check if the country is in Asia if models.OperatorCostAsia.objects.filter(country=country_code).exists(): cost = models.OperatorCostAsia.objects.filter(country=country_code, city__icontains=city).first() if cost is None: cost = models.OperatorCostAsia.objects.filter(country=country_code).first() else: cost = models.OperatorCost.objects.filter(country=country_code).first() return cost -
Django cannot login user after registration
The app has a basic registration form. I am trying to authenticate users after they fill it out. However, I'm unable to authenticate them. Am I going about this in the correct way? Here is the view: def registration(request): if request.method == "POST": form = CustomUserCreationForm(request.POST) if form.is_valid(): user = request.user password1 = form.cleaned_data['password1'] #this works try: validate_password(password1, user) except ValidationError as e: form.add_error('password1', e) return render(request, 'register.html', {'form': form}) profile = form.save(commit=False) profile.save() user = authenticate(username=form.cleaned_data['username'], password=form.cleaned_data['password1']) # this login not working, user is never authenticated login(request, user) return redirect('agree') else: raise ValidationError("Form is not valid. Try Again.") else: form = CustomUserCreationForm() return render(request, 'register.html', {'form': form}). Here is the forms.py. The model here is just the Django base user model. class CustomUserCreationForm(forms.ModelForm): username = forms.CharField(label='Username', widget=forms.TextInput(attrs={'class': "form-control"})) password1 = forms.CharField(label='Password', widget=forms.PasswordInput(attrs={'class': "form-control"})) password2 = forms.CharField(label='Password confirmation', widget=forms.PasswordInput(attrs={'class': "form-control"})) class Meta: model = User fields = ['username'] def clean_password(self): password1 = self.cleaned_data.get('password1') password2 = self.cleaned_data.get('password2') if password1 and password2 and password1 != password2: raise forms.ValidationError("Passwords do not match") return password2 def save(self, commit=True): user = super(CustomUserCreationForm, self).save(commit=False) user.username = self.cleaned_data['username'] user.set_password(self.cleaned_data['password1']) if commit: user.save() return user User never gets registered and authenticated. -
Django channels JsonWebsocketConsumer self.send_json() error
i'm writing a consumer that sends a list of conversation and a profile object (contact) after sending the via self.send_json() this error shows up i really don't know what is going on wondering if you could help Error: Exception inside application: 'name' File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\sessions.py", line 183, in __call__ return await self.inner(receive, self.send) File "C:\Users\DELL\ENVS\async\lib\site- packages\channels\middleware.py", line 41, in coroutine_call await inner_instance(receive, send) File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\consumer.py", line 62, in __call__ await await_many_dispatch([receive], self.dispatch) File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\utils.py", line 52, in await_many_dispatch await dispatch(result) File "C:\Users\DELL\ENVS\async\lib\site-packages\asgiref\sync.py", line 238, in __call__ return await asyncio.wait_for(future, timeout=None) File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib \asyncio\tasks.py", line 4 14, in wait_for return await fut File "C:\Users\DELL\AppData\Local\Programs\Python\Python37\lib \concurrent\futures\thread.py", line 57, in run result = self.fn(*self.args, **self.kwargs) File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\db.py", line 14, in thread_handler return super().thread_handler(loop, *args, **kwargs) File "C:\Users\DELL\ENVS\async\lib\site-packages\asgiref\sync.py", line 271, in thread_handler return func(*args, **kwargs) File "C:\Users\DELL\ENVS\async\lib\site-packages\channels\consumer.py", line 105, in dispatch handler(message) File "C:\Users\DELL\ENVS\async\lib\site- packages\channels\generic\websocket.py", line 60, in websocket_receive self.receive(text_data=message["text"]) File "C:\Users\DELL\ENVS\async\lib\site- packages\channels\generic\websocket.py", line 125, in receive self.receive_json(self.decode_json(text_data), **kwargs) File "E:\Personal Projects\Tolk\chat\consumers.py", line 41, in receive_json name = content['name'] 'name' Consumers.py: ```python class LoadConsumer(JsonWebsocketConsumer): def connect(self): if self.scope['user'].is_authenticated: self.accept() else: self.close() def receive_json(self, content, **kwargs): if content['command'] == "CHAT": name = content['name'] data = self.load_conversation_contact(name) else: data = {"success": False, "errors": "no such command"} self.send_json(data) … -
Django admin:i tried granting permission through the group but its not working,
I want to restrict what my custom users through the group permission, but its not working, they still have access to all functionalities I have added the has_add_permission,has_change_permission,has_delete_permission,has_view_permission,has_module_permission method to my custom user admin but it is still not restricting the access class CustomUserAdmin(UserAdmin): add_form = CustomUserCreationForm form = CustomUserChangeForm model = Account list_display = ('email','address', 'is_staff', 'is_active', 'is_superuser', 'is_admin') list_filter = ('email','address', 'is_staff', 'is_active','is_superuser', 'is_admin','groups') fieldsets = ( (None, {'fields': ('email','address', 'password')}), ('Permissions', {'fields': ('is_staff', 'is_active','is_superuser', 'is_admin','groups', 'user_permissions')}), ) add_fieldsets = ( (None, { 'classes': ('wide',), 'fields': ('email','address', 'password1', 'password2', 'is_staff', 'is_active','is_superuser', 'is_admin')} ), ) search_fields = ('email',) ordering = ('email',) enter code here def has_add_permission(self, request): return True def has_change_permission(self, request, obj=None): return True def has_delete_permission(self, request, obj=None): return True def has_view_permission(self, request, obj=None): return True def has_module_permission(self, request): return True admin.site.register(Account, CustomUserAdmin) I expect that when i put when i put a "can delete" permission on group, the users in that group should only be able to delete. but after doing that, they are still having permissions like the superuser. -
In a django model, provide a set of default set of fields but also allow users to add their own
Not the most descriptive title, I know, but my question is much better illustrated with an example. Let's say I'm making an application that will allow student drivers to log their driving time. They are required to log day time and night time, so I provide both fields by default. But let's say for the sake of argument that one curious teenager decides he wants to track the time he spends while driving in thunderstorms as well. And another one decides he wants to track how much time he spends driving in snow. What is the best way of making this possible using Django? This is a rough outline of how I'm thinking about this now. Assume this is in models.py: class Trip(models.Model): user = models.ForeignKey(User, on_delete = models.CASCADE) date = models.DateField() class DrivingTime(models.Model): trip = models.ForeignKey(Trip, on_delete=models.CASCADE) tag = models.ForeignKey(AcceptableTimeType, on_delete=models.CASCADE) hours = models.TimeField() class AcceptableTimeType(models.Model): name = models.CharField(max_length=50) # null/blank if visible for everyone # otherwise, should link to the user that wants this specific type of time tracked user = models.ForeignKey(User, on_delete=CASCADE, blank=True, null=True) I pre-set the list of default types of time (day/night in this example) in the Django admin and leave the User field blank. … -
Django-Template: Tap list item and make a detail page
So I have a bunch of list items, when I tap one I want to get the name and other info of that object. Right now I don't now how to parse data and need help :) As you can see I have a detail page, but my point there is to get the data at that specific index in the list view, so if I tap index one, I want the name of index one! Views: @login_required def studyplanPage(request): obj = Studyplan.objects.filter(canview__user=request.user) username = request.user context = { 'object': obj, 'MyName': username } return render(request, 'allStudyplans.html', context) @login_required def detailStudyplanPage(request): return render(request, 'detailStudyplan.html') Html List: {% for x in object %} <div class="col-lg-6"> <div class="card card-project"> <div class="card-body"> <div class="dropdown card-options"> <button class="btn-options" type="button" id="project-dropdown-button-1" data-toggle="dropdown" aria-haspopup="true" aria-expanded="false"> <i class="material-icons">more_vert</i> </button> <div class="dropdown-menu dropdown-menu-right"> <a class="dropdown-item" href="#">Edit</a> <a class="dropdown-item" href="#">Share</a> </div> </div> <div class="card-title"> <a href="detail-studyplan"> <span style=" height: 100%; width: 100%; left: 0; top: 0; z-index: 1; "> <h5 data-filter-by="text">{{x.name}}</h5> <h6 style="font-size: 12px">Studierar inför {{x.parent_assignment}}</h6> </span> </a> </div> <ul class = "hor-list"> {% for student in x.students.all %} <li class = "list-item"> <div class="circle"> <span class="initials" , style="color: #ffffff"> {{ student|make_list|first|capfirst }} </span> </div> </li> {% endfor %} … -
Google Credentials Picker
I registered api google but the account picker did not appear on the site as in the picture how the account picker appears because i searched for a long time and i did not find any solution to the problem When I click on the account picker it takes me to the Google page and I want the account picker to be on the site This is done automatically without moving to the Google page This is the problem is Authenticated in the Google page is not Authenticated in the site page and also does not appear picker in the site page https://6.top4top.net/p_13407jtc21.png https://1.top4top.net/p_1340ergmc2.png -
Not return Queryset to show in template Django
def empFil(request): dep = request.POST.get('dep',None) site = request.POST.get('site',None) print(dep) print(site) fil = TB_employee.objects.filter(dep_id = dep, site_id = site).all().select_related('site_id','dep_id','pos_id','sec_id') print(fil) return render(request,'app/employee.html',{'fil':fil}) -
Want to get text from a DIV but getting "TypeError: 'str' object is not callable" error
I'm using Python 3.7, Django, and BeautifulSoup 4. I have the below bs = BeautifulSoup(html, features="lxml") reg = re.compile(r'u\/\[deleted\]') main_elt = bs.find("button", {"data-main-id": "vote"}) print(str(main_elt.parent)) vote_div = main_elt.parent.find('div') print(str(vote_div)) print("vote text:" + vote_div.text()) Despite the fact that the print(str(vote_div)) prints out <div class="outer2 inner4" style="color:#D7DADC">434</div> The line print("vote text:" + vote_div.text()) dies with a TypeError: 'str' object is not callable What's the right way to extract the text from a DIV object?