Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django - Model property methods vs signals for field calculation
I have a model that does some basic aggregation of some values on a m2m field. I can achieve this by doing the calculation in a Model method, in which case the results would be stored in a model attribute. Or I can do the calculation in a pre_save signal function, and then the result would be stored in a model field. I want to know are there are any cons to using signals? or in which cases it would be better to use a model property method? I understand that the calculations will run at different times, with the signal function running when save() is called, and the model method running automatically. class CartItem(models.Model): name = models.CharField(max_length=100) total_price = models.DecimalField(max_digits=10, decimal_places=2) ##Model Method Approach @property def price(self): return self.extras.all().aggregate(Sum('price'))['price__sum'] ##Signal Approach def set_total_price(sender, instance, **kwargs): instance.total_price= instance.extras.all().aggregate(Sum('price'))['price__sum'] pre_save.connect(set_total_price, sender=CartItem) The signal approach has the benefit of resulting in a model field rather than a model attribute, which makes it easier use in Parent or related models for aggregation. So why would one ever use a Model method over a model signal? -
How to display data from mysql 8 in django 2.1.5?
I am trying to display some data from mysql 8 in Django 2.1. I created a database db1 and inserted some data into it and tested. All works perfectly. Then I add this piece of code into views.py: @login_required def population_list(request): names = Population.objects.all() return render_to_response('images/image/list.html', {'names': names}) inside models.py I have: class Population(models.Model): name = models.CharField(max_length=20) population = models.BigIntegerField() year = models.DateField() inside list.html I add this code: <div id="population-list"> <h3>Names here... </h3> <tbody> <tr> {% for name in names %} <td>{{ name.name }}</td> {% endfor %} </tr> </tbody> However I only see: "Names here..." text, nothing else. What is my mistake? Why I don't see the database content? How can I debug it? -
Slow server response times from Django app on Heroku
Ive grown quite stuck trying to figure out why my production Django application (E-commerce) has trouble with slow server response times on certain pages. The pages affected has quite some database requests on it because of complicated relationships between Cars and Products i.e some chargers only work with some cars and some chargers span multiple categories etc etc. The application is hosted on Heroku with a “Hobby Basic Postgres database” and "1 Professional Standard-1X dyno”. For some reason the server takes between 7-10 seconds to respond to a request on the live server. Locally everything works super smooth and fast with responses of maximum 0.5s on all pages. Has anyone had this trouble before and has any idea of how to fix it? Ive tried scaling the database and dynos without the response being any quicker.. I’ll attach som screenshots of logs and speed tests. And affected code Models, Views and Template. Heroku Metrics: https://screenshot.net/z7r4jid Heroku Logs: https://screenshot.net/ndv7ot8 Console Debugger: https://screenshot.net/m4310t3 Template: https://dpaste.de/tjEi View: https://dpaste.de/Bdut Models: https://dpaste.de/fNQY The page is: https://www.evify.se The pages with slow server response is all the car detail pages. Example: https://www.evify.se/laddboxar/jaguar-i-pace/ Would be extremely grateful if anyone has any idea, I’ve looked everywhere without finding any … -
How to convert duration into '%H:%M:%S.%f' time format, not in days
I need to convert days to hours, minutes, seconds def get_working_hours(self, obj): return datetime.strptime(str(obj.working_hours), '%H:%M:%S.%f').time() ValueError: time data '1 day, 7:06:38.340741' does not match format '%H:%M:%S.%f' -
How to set a dynamic choices tuple based on other model field values
I have a model with 2 fields: A ManyToMany field that contains a number of users who can approve a task (approvers); and An IntegerField that contains a choices tuple to return the current step of the task (step). class Task(models.Model): approvers = models.ManyToManyField( get_user_model(), through='TaskStep' ) step = IntegerField( choices=STEP_CHOICES ) I want to allow users to define the number of approvers, but also dynamically create a choice for each approver in step. How can I programmatically define the choices in my tuple to cover the number of users in the ManyToMany field? For example, if there are 3 approvers, the result would be: STATUS_CHOICES = ( (1, 'Step 1'), (2, 'Step 2'), (3, 'Step 3'), ) If there were 5 users, the result would be: STATUS_CHOICES = ( (1, 'Step 1'), (2, 'Step 2'), (3, 'Step 3'), (4, 'Step 4'), (5, 'Step 5'), ) -
Getting InvalidRequestError in stripe
I get following error: File "C:\Users\HP\AppData\Local\Programs\Python\Python36\lib\site-packages\stripe\api_requestor.py", line 151, in handle_error_response raise err stripe.error.InvalidRequestError: Request req_jQhnYD0I72zs8l: No such customer: cus_Fi7AiNV2Cpdkdi My code: def payment_method_create_view(request): print("Ajax payment") if request.method == "POST" and request.is_ajax(): billing_profile, billing_profile_created = BillingProfile.objects.new_or_get(request) if not billing_profile: return HttpResponse({"message": "Cannot find this user "}, status=401) token = request.POST.get("token") print("token is:", token) if token is not None: new_card_obj = Card.objects.add_new(billing_profile, token) print(new_card_obj) return JsonResponse({"message": "Your card was added."}) return HttpResponse("error", status=401) class CardManager(models.Manager): def all(self, *args, **kwargs): return self.get_queryset().filter(active=True) def add_new(self, billing_profile, token): if token: customer = stripe.Customer.retrieve(billing_profile.customer_id) stripe_card_response = customer.sources.create(source=token) new_card = self.model( billing_profile = billing_profile, stripe_id = stripe_card_response.id, brand = stripe_card_response.brand, country = stripe_card_response.country, exp_month = stripe_card_response.exp_month, exp_year = stripe_card_response.exp_year, last4 = stripe_card_response.last4 ) new_card.save() return new_card return None class Card(models.Model): billing_profile = models.ForeignKey(BillingProfile, on_delete=models.CASCADE) stripe_id = models.CharField(max_length=120) brand = models.CharField(max_length=120, null=True, blank=True) country = models.CharField(max_length=20, null=True, blank=True) exp_month = models.IntegerField(null=True, blank=True) exp_year = models.IntegerField(null=True, blank=True) last4 = models.CharField(max_length=4, null=True, blank=True) default = models.BooleanField(default=True) active = models.BooleanField(default=True) timestamp = models.DateTimeField(auto_now_add=True) objects = CardManager() -
Calculating two integers fields in django
I want to calculate these fields and want output for example (budget - Expense) (budget + Expense) (budget * Expense). how could i do that. Class calculate(models.Model): budget = models.IntegerField(default=0) Expense = models.IntegerField(default=0) -
Circular import error while importing urls file of another app in main app urls
I have created an app in djano with name user, and inside that user app , there is a file called urls.py, it contains various api_end points. Now I want to import this urls.py of app.py inside the urls.py file created by django project. I am getting circular import error. this is urls.py file created by django-admin urlpatterns = [ path('admin/', admin.site.urls), url(r'^api/v1/', include('user.urls')), ] and this is urls.py file created inside user app urlpatterns = [ url(r'^login/?$', token_handling.CustomTokenObtainPairView.as_view(), name='login'), ] -
Setup docker volume for django logger
I have a Django 2.2 application and want to serve the application using Docker. I have the Django logger setup as FILE_LOCATIONS = { 'debug': '{}/logs/{}/app/{}'.format('/var/log/app', 'QCG2', 'debug.log'), 'error': '{}/logs/{}/app/{}'.format('/var/log/app', 'QCG2', 'error.log'), 'info': '{}/logs/{}/app/{}'.format('/var/log/app', 'QCG2', 'info.log') } LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'formatters': { 'verbose': { 'format': '{levelname} {asctime}: ~{pathname} (line: {lineno}):: {message}', 'style': '{', }, 'simple': { 'format': '{levelname} {message}', 'style': '{', }, }, 'handlers': { 'file': { 'level': 'DEBUG', 'class': 'logging.handlers.TimedRotatingFileHandler', 'filename': FILE_LOCATIONS['debug'], 'formatter': 'verbose', 'when': 'midnight', 'interval': 1, 'backupCount': 0, }, 'console': { 'class': 'logging.StreamHandler', 'formatter': 'verbose', }, }, 'loggers': { 'app': { # Common logger, log app 'handlers': ['console', 'file'], 'level': 'DEBUG', 'propagate': True, }, 'plan_change': { # Log plan change process 'handlers': ['console', 'file'], 'level': 'DEBUG', 'propagate': True, }, } } and docker-compose.yml file as version: '3' services: nginx: image: nginx:alpine container_name: "myapp-staging-nginx" ports: - "8000:80" volumes: - .:/app - ./configs/docker/nginx:/etc/nginx/conf.d depends_on: - web web: build: . container_name: "myapp-staging-dev" command: ["./scripts/docker/wait_for_it.sh", "db:5433", "--", "./scripts/docker/docker_start.sh"] volumes: - .:/app depends_on: - db # For database - redis # For celery broker db: image: mysql:8.0 container_name: "myapp-staging-mysql-db" env_file: - configs/docker/env/mysql_env.env ports: - "5433:5432" volumes: - myapp_staging_db_volume:/var/lib/mysql/data redis: image: "redis:alpine" celery: build: . command: celery -A qcg … -
Angular router guard with Django
I am using django authentication, I want to use angular router guards when not signed in. So that it reroutes to login page if not logged in. I have tried to setup as angular usually would with router guards, but this routes to the url without a trailing slash which doesn't work with Django. I have fixed it so it keeps the trailing slash, but this doesn't route to the Django page, it seems its looking for a Angular page. But if it type in the url for the Django login page that still works. Auth Guard: checkLogin(url: string): boolean { if (this.authService.isLoggedIn) { return true; } this.authService.redirectUrl = url; this.router.navigate(['/accounts/login/.']); return false; } app-routing module: { path:"", component: ProjectHomeComponent, canActivate : [AuthGuard], children: [ { path: '', children: [ { path: 'view', component: ProjectViewComponent }, { path: 'seeManage', component: ProjectManageComponent }, { path: '**', component: PagenotfoundComponent } ] } ] } Expect to be routed to django login page, not routed to django login page -
I want save data in sqlite Database, My Query not working in webpage But same code wroking fine in Django Shell
I am trying to add some data via Views.py but it not working but the same code working in django shell. My Code : username = request.POST['username'] bp = request.POST['bp'] bs = request.POST['bs'] height = request.POST['height'] weight = request.POST['weight'] temp = request.POST['temp'] datasaved = PatTest(Patient= Patient.objects.get(username=str(username)), BS=int(bs), BP=int(bp), PatHeight=float(height), PatientWeight=float(weight), BMI=BMICal(height, weight), TEMPA=int(temp)) print("Test") datasaved.save() -
Django - How to dynamically create signals
I'm working on a model Mixin which needs to dynamically set signals based on one attribute. It's more complicated but for simplicity, let's say the Mixin has this attribute: models = ['app.model1','app.model2'] This attribute is defined in model which extends this mixin. How do I can register signals dynamically? I tried to create a classmethod: @classmethod def set_signals(cls): def status_sig(sender, instance, created, *args, **kwargs): print('SIGNAL') ... do som things for m in cls.get_target_models(): post_save.connect(status_sig,m) My idea was to call this method somewhere in class automatically (for example __call__ method) but for now, I just tried to call it and then save the model to see if it works but it didn't. from django.db.models.signals import post_save print(post_save.receivers) Realestate.set_signals() print(post_save.receivers) r = Realestate.objects.first() r.status = 1 r.save() output [] [((139967044372680, 46800232), <weakref at 0x7f4c9d702408; dead>), ((139967044372680, 46793464), <weakref at 0x7f4c9d702408; dead>)] So you see that it registered those models but no signal has been triggered after saving the realestate. Do you know how to make it work? Even better without having to call method explicitely? EDIT: I can't just put the signals creation inside mixin file because models depends on the string in child model. -
Can't Add/Accept and Decline/Cancel Friend requests on Django
Able to Send Friend requests successfully but responding to the requests are an issue. When you press Accept to Add, the button is removed but the Friend isn't added or when you press Cancel to Decline, nothing happens. Tried adding a forms class Add_Friend(forms.ModelForm): model = UserProfile def add_friend(request, user_profile): request.notification_set.get(type=Notification.FRIEND_REQUEST, sender=user_profile.user.username).delete() request.friends.add(user_profile) user_profile.friends.add(self) request.friend_requests.remove(user_profile) noti = Notification.objects.create(owner=user_profile, type=Notification.ACCEPTED_FRIEND_REQUEST, sender=self.user.username) user_profile.notification_set.add(noti) return self.friends.count() class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) first_name = models.CharField(blank=True, max_length=128) friends = models.ManyToManyField('self', blank=True, related_name='friends') friend_requests = models.ManyToManyField('self', blank=True, related_name='friend_requests') def send_friend_request(self, user_profile): self.friend_requests.add(user_profile) noti = Notification.objects.create(owner=self, type=Notification.FRIEND_REQUEST, sender=user_profile.user.username) self.notification_set.add(noti) return self.friend_requests.count() def add_friend(self, user_profile): self.friend_requests.remove(user_profile) self.notification_set.get(type=Notification.FRIEND_REQUEST, sender=user_profile.user.username).delete() self.friends.add(user_profile) user_profile.friends.add(self) noti = Notification.objects.create(owner=user_profile, type=Notification.ACCEPTED_FRIEND_REQUEST, sender=self.user.username) user_profile.notification_set.add(noti) return self.friends.count() def cancel_friend_request(self, user_profile): self.friend_requests.remove(user_profile) self.notification_set.get(type=Notification.FRIEND_REQUEST, sender=user_profile.user.username).delete() noti = Notification.objects.create(owner=user_profile, type=Notification.DECLINED_FRIEND_REQUEST, sender=self.user.username) user_profile.notification_set.add(noti) return self.friend_requests.count() def __str__(self): return self.get_first_name() #Takes you to the userprofile page def get_absolute_url(self): return "/users/{}".format(self.id) @method_decorator(login_required, name='dispatch') class SendFriendRequestView(View): def get(self, request, *args, **kwargs): profile_id = request.GET.get('profile_id') requester_id = request.GET.get('requester_id') target = UserProfile.objects.get(id=profile_id) requester = UserProfile.objects.get(id=requester_id) target.send_friend_request(requester) message = 'Friend request to {} sent!'.format(target.visible_name) messages.info(request, message) return redirect('profile', username=target.user.username) @method_decorator(login_required, name='dispatch') class CancelFriendRequestView(View): def cancel_friend_request(request, id): if request.user.is_authenticated(): user = get_object_or_404(User, id=id) frequest, created = FriendRequest.objects.filter( from_user=request.user, to_user=user).first() frequest.delete() return HttpResponseRedirect('/users') @method_decorator(login_required, name='dispatch') class AddFriendView(View): def … -
Django Forms Not Rendering In HTML
I am finding it difficult to show django forms in html template. The django form fails to render in the template. I am using class base view and below are my codes for views.py,urls.py, models.py and the html template: views.py class Home(CreateView): models = Blog queryset = Blog.objects.filter(publish = True) template_name='index.html' fields = '__all__' urls.py ... urlpatterns=[ path('', Home.as_view(), name='index'), ] models.py ... Continent = ( ('select continent', 'Select Continent'), ('africa', 'Africa'), ('europe', 'Europe'), ('north america', 'North America'), ('south america', 'South America'), ('asia', 'Asia'), ('australia', 'Australia'), ('Antarctica', 'Antarctica'), ) class Blog(models.Model): name= models.CharField(max_length = 200) company= models.CharField(max_length = 200) post = models.CharField(max_length = 200) author= models.ForeignKey('auth.User', on_delete = models.PROTECT) mantra= models.CharField(max_length = 200, help_text='make it short and precise') continent = models.CharField(choices= Continent, default= 'select continent', help_text='help us to know you even more', max_length=50) publish = models.BooleanField(default =True) def __str__(self): return self.name def get_absolute_url(self): # new return reverse('post_detail') index.html {% extends "base.html" %} {% load static %} {% block content %} <body class="loading"> <div id="wrapper"> <div id="bg"></div> <div id="overlay"></div> <div id="main"> {{form.as_p}} {% include "partials/_footer.html" %} </div> </div> </body> {% endblock %} Any assistance will be greatly appreciated. Thanks. -
local variable 'submission' referenced before assignment
I encounter this error for my django project. my app is called "scoresubmission" basially i have a feature in the website to allow user download report. So in my views.py file i have report function and import report.py file, where it shows how report is built It shows the error happens in this line of code: submission=Submission.objects.get(month=month,year=reportyear,program=program) Views.py def report(request): from scoresubmission.report import reportA, reportB, reportC reportType = request.POST["reportType"] reportYear = int(request.POST["reportYear"]) if reportType == 'a': report_content = reportA(reportYear) response = HttpResponse(report_content, content_type="text/csv") response['Content-Disposition'] = 'inline; filename=5SAuditYearlySummaryReport_%d.xlsx' %reportYear report.py where it has the relevant code for facility in facilities: worksheet.write(row,col,facility.name,facility_format) for i in range(12): # 12 months month=i+1 programs=Program.objects.filter(facility_id=facility.id) avg_totalscore=0 count=1 for program in programs: print(program) try: submission=Submission.objects.get(month=month,year=reportyear,program=program) print(submission) avg_score=Result.objects.filter(submission=submission).aggregate(Avg('NewScore')) #print avg_score.get('NewScore__avg') avg_totalscore=(avg_totalscore + avg_score.get('NewScore__avg'))/count count=count+1 except submission.DoesNotExist: pass #print avg_totalscore if avg_totalscore!=0: worksheet.write(row,i+3,avg_totalscore,red_format) else: worksheet.write(row,i+3,'-',red_format) Traceback (most recent call last): File "C:\Users\CHLOZHAO\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\exception.py", line 34, in inner response = get_response(request) File "C:\Users\CHLOZHAO\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 115, in _get_response response = self.process_exception_by_middleware(e, request) File "C:\Users\CHLOZHAO\AppData\Local\Programs\Python\Python37\lib\site-packages\django\core\handlers\base.py", line 113, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\CHLOZHAO\AppData\Local\Programs\Python\Python37\lib\site-packages\django\contrib\auth\decorators.py", line 21, in _wrapped_view return view_func(request, *args, **kwargs) File "C:\D Drive\5S Audit Website\my5saudit\scoresubmission\views.py", line 185, in report report_content = reportA(reportYear) File "C:\D Drive\5S Audit Website\my5saudit\scoresubmission\report.py", line 79, … -
DJANGO > 2.2 - Unique together on foreign keys A, B OR foreign keys A, B, C
In Django 2.2, you can get rid of unique_together in favor of a constraints list with a UniqueConstraint class that can be handy because it has a condition arg. MyObject has three foreign keys, one is optional. class MyObject(ModelBase): parent=... # mandatory source=... # mandatory subsource=... # optional class Meta: constraints = [ models.UniqueConstraint( fields=["parent", "source", "subsource"], name="unique_subsource" ), models.UniqueConstraint( fields=["parent", "source"], condition=models.Q(subsource=None), name="unique_source", ), ] Imagine I try to create successively the following objects and the expected validation: parent source subsource valid? 1. 1. 1. yes 1. 1. 2. yes 1. 1. - yes 1. 1. - no 1. 1. 3. yes 1. 2. - yes ... So I wrote two tests: def test_unique1(self): """ unique parent/source/subsource """ parent = ParentFactory() source = SourceFactory() subsource = SubsourceFactory() MyObjectFactory(parent=parent, source=source, subsource=subsource) myobj = MyObjectFactory.build(parent=parent, source=source, subsource=subsource) self.should_raise_validation_error(myobj) def test_unique2(self): """ unique parent/source """ parent = ParentFactory() source = SourceFactory() subsource = SubsourceFactory() MyObjectFactory(parent=parent, source=source) myobj = MyObjectFactory.build(parent=parent, source=source) self.should_raise_validation_error(myobj) But the latter does not raise any validation error. -
Django utf-8 urls
I have a Django app that works fine on localhost.even for utf-8 URL path.but when I use it in production it gives me an error: 2019-09-01 14:32:09.558237 [ERROR] [12257] wsgiAppHandler pApp->start_response() return NULL. Traceback (most recent call last): File "/home/medualla/virtualenv/project/3.7/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 139, in call set_script_prefix(get_script_name(environ)) File "/home/medualla/virtualenv/project/3.7/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 179, in get_script_name script_url = get_bytes_from_wsgi(environ, 'SCRIPT_URL', '') or get_bytes_from_wsgi(environ, 'REDIRECT_URL', '') File "/home/medualla/virtualenv/project/3.7/lib/python3.7/site-packages/django/core/handlers/wsgi.py", line 204, in get_bytes_from_wsgi return value.encode('iso-8859-1') UnicodeEncodeError: 'latin-1' codec can't encode characters in position 1-6: ordinal not in range(256) this error occurs when i try a url like http://meduallameh.ir/صفحه the only answer I got was that problem with the webserver. I deployed it on a shared host and I asked them and they told me that web server supports utf-8. now I need some help to fix this problem. -
setting image src from jquery with attr() from a django static directory
I am new to django and I want to set an image from a static directory to an <img> tag via jQuery. I have the below logic: <img id="A"> function showProfile(person) { $("#A").attr("src", "main/images/portrait/" + person + "1.jpg"); } However, when running the above, the image does not show. with Django static files I usually do: <img id="A" src="{% static "main/images/portrait/whatever.jpg" %}"> However, I want to get an image dynamically via jQuery how can this be done? -
How to create a dictionary from many different sources?
I want to create a dictionary just like this example : {"('Open', 'Jaipur', 'Pune')": [{1: [12, 12, 12, 12]}]} Now, every word you see here I have it but in either a dataframe, or in a list. The first word 'Open' is the truck-type which I can get by fetching it from a dataframe by using truck["Category"], the second and third are names of places, which I have stored in my items' list, and can get by using items[0].origin and items[0].destination. Also, my items list is as such [12,12,12,12]. Now, I want to recreate this as a single dictionary, with all these together, and it should always have 1 as the key. I tried something like this, but I don't get anywhere near the final output: open_list_key = [truck["Category"],items[0].origin,items[0].destination] open_list_value = items open_list = {open_list_key:open_list_value} -
Can't return QuerySet filter to html page
i want filter employee form department and site by user filter and submit i post value form html to definition in views.py @csrf_exempt 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).select_related('site_id','dep_id','pos_id','sec_id') print(fil) return render(request,'app/employee.html',{'fil':fil}) this command line 21 2 <QuerySet [<TB_employee: TB_employee object (4892)>, <TB_employee: TB_employee object (4916)>]> in employee.html {% for e in fil %} <tr> <td>{{e.en}}</td> <td>{{e.name_th}}</td> <td>{{e.surname_th}}</td> <td>{{e.name_eng}}</td> <td>{{e.surname_eng}}</td> <td>{{e.pos_id.pos_name}}</td> <td>{{e.dep_id.dep_name}}</td> <td>{{e.site_id.site_name}}</td> <td>{{e.hire_date}}</td> <td>{{e.sec_id.sec_name}}</td> <td>{{e.emp_type}}</td> <td>{{e.emp_status}}</td> <td>{{e.emp_email}}</td> <td>{{e.budget}}</td> </tr> {% endfor %} in html page cannot show data -
Django Credit System
I am making a system where users to sign up my system they have to buy credit and then I need to upload the credit in their account. When they make some actions on web site. I will decrease their credit number. How can I do that? I had try to add a field in "user model" called "credit number". But the problem is that for me: when two user make request at the same time to "credit number" section I need to apply both request respectively. I read about transaction. Do you suggest me a way to do it? -
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, …