Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Modify export data un module export-import django
I want to make a custom export using this module of Python(export-import) I want to modify the value of one colum. Actualy, this colum is like "uXXXXXX" and I want to delete this "u" before export. I justo try to make it overriding before_export and export function, but always queryset make again as default (because my method call super and override again my custom queryset) Any idea? thanks! -
GoDaddy custom domain hosted with Heroku throwing privacy error
I'm having trouble getting the custom domain I bought from GoDaddy to work with the Django app I have hosted on Heroku's free dyno. The Heroku app is accessible from the custom domain, however, I keep getting a privacy error from chrome. See below: My Heroku dashboard confirms that I have added my custom domain. I have tried doing this through both the CLI and GUI, with no different results. My DNS settings on my domain in GoDaddy are configured as follows. Someone had mentioned the CNAME setting should be the .herokudns domain generated by the addition of the custom domain in the Heroku dashboard, but when I make that change the website is not accessible at all. The Heroku app is named: desolate-basin-60228 and can be accessible at https://desolate-basin-60228.herokuapp.com/ and in GoDaddy I have confirmed that my forwarding is set to http (not https as I don't need a security cert. for this site): I also thought that it may be an issue with my Django settings.py file. So I adjusted any line with mention of https. This did not have any effect. Does anyone have any thoughts on what I'm missing here? -
Setup Gunicorn Workers Type Properly
Im using gunicorn + supervisor + nginx to deploy my django, now i already setup for the gunicorn worker to use gevent type so its from sync to async, but in supervisor log it says that the type of worker is sync. Gunicorn Supervisor Service: #!/bin/bash NAME="web" # Name of the application DJANGODIR=/home/webserver/0.1 # Django project directory SOCKFILE=localhost:8000 # we will communicte using this unix socket USER=root # the user to run as GROUP=root # the group to run as NUM_WORKERS=9 # how many worker processes should Gunicorn spawn DJANGO_SETTINGS_MODULE=web.settings # which settings file should Django use DJANGO_WSGI_MODULE=web.wsgi # WSGI module name TIMEOUT=30 echo "Menjalankan $NAME as `whoami`" # Activate the virtual environment cd $DJANGODIR source ../env/bin/activate export DJANGO_SETTINGS_MODULE=$DJANGO_SETTINGS_MODULE export PYTHONPATH=$DJANGODIR:$PYTHONPATH # Create the run directory if it doesn't exist # RUNDIR=$(dirname $SOCKFILE) # test -d $RUNDIR || mkdir -p $RUNDIR # Start your Django Unicorn # Programs meant to be run under supervisor should not daemonize themselves (do not use --daemon) exec /home/webserver/env/bin/gunicorn ${DJANGO_WSGI_MODULE}:application \ --name $NAME \ --workers $NUM_WORKERS \ --worker-class=gevent \ --user=$USER --group=$GROUP \ --bind=$SOCKFILE \ --log-level=debug \ --log-file="-" Supervisor Logs: [2019-11-26 23:03:55 +0800] [4802] [INFO] Starting gunicorn 19.9.0 [2019-11-26 23:03:55 +0800] [4802] [INFO] Listening at: http://127.0.0.1:8000 … -
How to write this query sql in a DJANGO ORM
I did this query to tested, but now i need to included this in my view django and i don't know how to do this, SELECT Referencia, Recebido, sum(contas_paga + Salarios_Comissao + encargos) as Contas, sum(Recebido - (contas_paga + Salarios_Comissao + encargos)) as Total FROM( SELECT vrm.mes_referencia as Referencia, vrm.mapa_atual - (vrm.mapa_atual * 0.2) as Recebido, (SELECT SUM(valor) from contas_pagar_contas_pagar where to_char(dt_pagamento, 'MMYYYY') = vrm.mes_referencia) as contas_paga, (SELECT SUM(vl_valor_pago) from func_pagamentos_pagamentos where to_char(data_pagamento, 'MMYYYY') = vrm.mes_referencia) as Salarios_Comissao, (SELECT SUM(salario * 1.8) from func_pagamentos_pagamentos where to_char(data_pagamento, 'MMYYYY') = vrm.mes_referencia) as encargos FROM venda_resumo_mapa as vrm WHERE vrm.mes_referencia like '%2019%' group by (vrm.mes_referencia, vrm.mapa_atual) order by vrm.mes_referencia) as f group by (f.Referencia, f.Recebido) -
Trying to pass two dictionaries but only first one works
views.py: def home(request): return render(request, 'blog/home.html', {'title': 'HOME'}, {'post': posts}) In this code, only title works. when I took {'post': posts} before {'title': 'HOME'} , post works but title don't. I have to use both in templates. I'm a beginner in django. How can i fix this problem ? -
My Django Project doesn't appear in my Docker-Image (Docker toolbox for windows home)
I'm trying to build a django project using docker-compose, such as it is in the Docker Documentation (I use Docker toolbox for Windows 10 Home). But when i execute the command: sudo docker-compose run web django-admin startproject composeexample . I get an bash: sudo: command not found __ Then if i execute the same command without "sudo": docker-compose run web django-admin startproject composeexample . The image is created but the django project folder is not displayed. Finally, when i run the command again i get: The Dockerfile is: FROM python:3 ENV PYTHONUNBUFFERED 1 RUN mkdir /code WORKDIR /code COPY requirements.txt /code/ RUN pip install -r requirements.txt COPY . /code/ docker-compose.yml version: '3' services: db: image: postgres web: build: . command: python manage.py runserver 0.0.0.0:8000 volumes: - .:/code ports: - "8000:8000" depends_on: - db and the requirements.txt: Django>=2.0,<3.0 psycopg2>=2.7,<3.0 -
Ajax.click function button on site not doing anything
can't work out why my button won't do anything on click. Won't even post the console log. Quite new to using ajax so bit confused. Thanks in advance, I hope it's something simple i'm missing. This is the page with the button {% extends "website/base.html" %} {% load staticfiles %} {% block content %} <style> #table td { padding: 0px; margin: 0px; } #table { border-spacing: 0px; } </style> <form id="search-form" method="POST" action="{% url 'searchs' %}"> {% csrf_token %} <div class="active-cyan-3 active-cyan-4 mb-4"> <input class="input" name="username" type="hidden" value="{{ username }}"> <input class="form-control" type="text" placeholder="Search" aria-label="Search" name="search-input" id="search-input"> </div> </form> <div class="text-center"> <button name="search-button" id="searchbut" align="centre" class="btn btn-dark btn-lg">Search</button> </div> <!-- Search form --> <br> <table id="search-tbl" class="table" width="100%" border=1> <thead class="thead-dark"> <tr> <th>Image</th> <th>Title</th> </tr> </thead> <tbody> {% for Auction in results %} <tr class='bg-white' align="center"> <td width="60%" vertical-align="middle" align="center"> {% load static %} <a href="auction/{{ Auction.id}}"> <img width="" href="auction/{{ Auction.id}}" src="{{ Auction.picture }}"> </a> </td> <td align="center"><a href="auction/{{ Auction.id}}">{{ Auction.title }}</a></td> </tr> {% endfor %} </tbody> </table> {% endblock %} <script> $(function () { $('#searchbut').click(function () { console.log("pushed") $.ajax({ url: "{% url 'searchs' %}", method: "POST", data: $("#search-form").serializeArray(), success: function (data) { console.log(data) $("#search-tbl tbody").remove(); for (var i = … -
Ajax call not calling view function in Django
I am trying to build a login form in Django, and when the user hits login, I wish to send the username and password to check which type of user it is as my system has 3 different kinds of users. Following is the code: views.py from django.shortcuts import render from django.views.decorators.csrf import csrf_exempt, csrf_protect from django.contrib.auth import authenticate, login, logout from django.contrib.auth.models import User def index(request): return render(request, "login.html") @csrf_protect def auth_login(request): print("Hello !") username = request.POST['username'] password = request.POST['password'] user = authenticate(request, username=username, password=password) group = User.objects.get(username=username).groups.values()[0]['name'] print(username) print(user) print(password) login.html - (I have a simple bootstrap login form) <body class="text-center"> <form class="form-signin" id="login-form">{% csrf_token %} <img class="mb-4" src="{% static "download.png" %}" alt="Logo" align="center" height="112" width="112"> <h1 class="h3 mb-4 font-weight-normal">Please sign in</h1> <label for="inputEmail" class="sr-only">Username</label> <input type="text" id="uname" class="form-control" placeholder="Username" required autofocus> <label for="inputPassword" class="sr-only">Password</label> <input type="password" id="passwd" class="form-control" placeholder="Password" required> <div class="checkbox mb-4"> </div> <button class="btn btn-lg btn-primary btn-block" id="loginbutton" type="submit">Sign in</button> <p class="mt-3 mb-5 text-muted">Planning Tool</p> </form> <script type="text/javascript"> $(document).ready(function () { $("#login-form").on('submit', function (e) { e.preventDefault(); login(); }); function login(){ alert($("#uname").val()) $.ajax({ url: {% url 'auth:Login' %}, method : "POST", data : { "username" : $("#uname").val(), "password" : $("#passwd").val(), 'csrfmiddlewaretoken' : "{{ csrf_token }}" }, … -
Django Rest Framework - Nested Serialization not working
model.py class Account(models.Model): name_Account= models.CharField(max_length=50, default='') fecha_nacimiento = models.CharField(max_length=150, default='') phone = models.CharField(max_length=150, default='') mail = models.CharField(max_length=150, default='') user_id = models.ForeignKey(User,on_delete=models.CASCADE) rol_id = models.ForeignKey(Rol,on_delete=models.CASCADE, null =True) class Reclamo(models.Model): nameReclamo= models.CharField(max_length=50, default='') rut = models.CharField(max_length=20, default='') numpoliza = models.CharField(max_length=30, default='') detalle_diagnostico = models.CharField(max_length=200, default='') account_id = models.ForeignKey(Account,on_delete=models.CASCADE,null =True) date = models.DateField(auto_now=True) name_estado= models.CharField(max_length=50, default='Pendiente') num_claim= models.CharField(max_length=30, default=' ' ,blank = True) serializer.py class AccountSerializer(serializers.ModelSerializer): class Meta: model = Account fields = ('id', 'name_Account', 'fecha_nacimiento', 'phone', 'mail', 'user_id', 'rol_id','rolName') class ReclamoSerializer(serializers.ModelSerializer): name_Account = AccountSerializer(many=False) #read_only=True no return, no error class Meta: model = Reclamo fields = ('id','nameReclamo','rut','numpoliza','detalle_diagnostico','account_id','date','name_estado','num_claim', name_Account) error Got AttributeError when attempting to get a value for field name_Account on serializer ReclamoSerializer. The serializer field might be named incorrectly and not match any attribute or key on the Reclamo instance. Original exception text was: 'Reclamo' object has no attribute 'name_Account'. I have tried different examples, but I cannot return what I hope -
How to generate payload using camelCase attributes with DRF serializers
So I need to consume an API that the JSON fields are all camelCase and I want to write them on my code as snake_case. How can I do this? I want something like this: serializer = MySerializer(data={'my_field': 'test'}) if serializer.is_valid(): output_data = serializer.validated_data print(output_data) # {'myField': 'test'} -
What relation should i create in models so that one user can create only one comments for Product?
This is my models. What is the best approach? OneToOneField allows to create only one comments for all time. class Person(models.Model): first_name = models.CharField( max_length=512, blank=True, null=True, ) last_name = models.CharField( max_length=512, blank=True, null=True, ) class Product(models.Model): slug = SlugField() name = NameField() description = DescriptionField() class Comment(models.Model): created_at = models.DateTimeField(auto_now_add=True) person = models.OneToOneField(Person, on_delete=models.CASCADE) text = models.TextField(null=True, blank=True) -
How to add a django application in classic asp website in IIS 7.5?
I am currently working on configuring IIS 7.5 where main website is built with classic ASP and need to implement django application INSIDE of main site. I've taken various ways to configure IIS to run django application in classic ASP webpage but for some reason it kept gives 403 Forbidden error. I've read and researched articles and posts regarding this issue but most of those resources were about permission issue. Here are steps / ways I've taken so far. Option 1 1. Add a folder where django application is located as a virtual directory in IIS 7.5 2. Configure DJANGO_SETTINGS_MODULE, PYTHONPATH, WSGI_HANDLER variables in FastCGI configuration at server level. 3. Add Handler Mapping in application level to run python in IIS. 4. Grant a permission to ASP website's application pool to the django application folder so that ASP website can access django application folder. Option 2 All of steps are same as option 1 except added django application as a application instead of virtual directory. In terms of application pool, I've tried DefaultAppPool, IIS_IUSR, IUSR, ApplicationPoolIdentity, NetworkService but none of them were working. (Btw, whenever I turn on Directory Browsing, I can navigate into django application's folder and see contents) … -
Difference between usage of Django celery and Django cron-jobs?
I am sorry if its basics but I did not find any answers on the Internet comparing these two technologies. How should I decide when to use which as both can be used to schedule and process periodic tasks. This is what an article says: Django-celery : Jobs are essential part of any application that does some processing for you in the background. If your job is real time Django application celery can be used. Django-cronjobs : django-cronjobs can be used to schedule periodic_task which is a valid job. django-cronjobs is a simple Django app that runs registered cron jobs via a management command. can anyone explain me the difference between when should I choose which one and Why? Also I need to know why celery is used when the computing is distributed and why not cron jobs -
Access files in production-mode of django project
For my Django project I have to open an xsl-file that is permanently located on the server to perform some actions on other files that the users can upload. In development mode I just used a relative path in the python script to point to that xsl-file and it worked fine: xslFile = open('./transform.xsl') However, as I am now in the stage of deploying the project to the server, I am having troubles with changing that line of code so that the file can still be found in production mode. I already tried setting an absolute path like xslFile = open('/srv/www/htdocs/djangoProject/mysite/transform.xsl') which threw errors. Furthermore I tried moving the file to the static directory which I state in my settings.py: STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') and tried then to open the file like this: from django.conf import settings xslFile = open(os.path.join(settings.STATIC_ROOT, 'transform.xsl')) However, both of these tries produce error messages of this kind: FileNotFoundError at /mysite/add/ [Errno 2] No such file or directory: 'transform.xsl' Request Method: POST Request URL: xx.xx.xx.xxx/mysite/add/ Django Version: 2.2.7 Exception Type: FileNotFoundError Exception Value: [Errno 2] No such file or directory: 'transform.xsl' Exception Location: /srv/www/htdocs/djangoProject/mysite/createDatabase.py in handleInputFiles, line 84 Python Executable: /usr/bin/python3 Python Version: … -
Can't add comment form in Django web application
I have a trouble adding form-group (I believe it's bootstrap class). The form-group doesn't do anything at all, or maybe it's a problem with form.author and form-body variables!? More simply, I need UI comment section (now only I can add and edit comments from django admin page). Some code: post_details.html <article class="media content-section"> <form action="/post/{{ post.slug }}/" method="post"> {% csrf_token %} <div class="form-group"> {{ form.author }} </div> <div class="form-group"> {{ form.body }} </div> <button type="submit" class="btn btn-primary">Submit</button> </form> <ul> {% for comment in post.comments.all %} <p> <b>@{{ comment.author }}</b> <small>{{ comment.created_date }} </small> </p> <p> {{ comment.text }}</p> <hr> {% if comment.replies.all %} <ul> {% for reply in comment.replies.all %} <p>{{ reply.text }}</p> <hr> {% endfor %} </ul> {% endif %} {% endfor %} <ul> </article> forms.py from django import forms class CommentForm(forms.Form): author = forms.CharField( max_length=60, widget=forms.TextInput( attrs={"class": "form-control", "placeholder": "Your Name"} ), ) body = forms.CharField( widget=forms.Textarea( attrs={"class": "form-control", "placeholder": "Leave a comment!"} ) ) views.py def comment(request): form = CommentForm() if request.method == "POST": form = CommentForm(request.POST) if form.is_valid(): comment = Comment( author=form.cleaned_data["author"], body=form.cleaned_data["body"], post=post, ) comment.save() context = {"post": post, "comments": comments, "form": form} if request.method == 'POST': form = CommentForm(request.POST) if form.is_valid(): comment = Comment( … -
Struggling to pass request.user.id to SQL function in python/django
hoping someone can help as I'm new django (and coding) and I'm stuck with trying to pass the current user's ID number to an SQL function. I've spent days searching for a solution but nothing I've tried has worked. I know the SQL function works as I can pass through a number without any issue, but when trying to use request.user it just comes up blank. views.py: def my_custom_sql(request): current_user = User.objects.get(request.user) with connection.cursor() as cursor: cursor.execute("SELECT first_name FROM customuser WHERE id = %s",[current_user]) row = cursor.fetchone() return row def dashboard(request): return render(request, 'dashboard.html', {'my_custom_sql': my_custom_sql}) models.py: class CustomUser(AbstractUser): pass # add additional fields in here employee_dob = models.DateField(blank=True, null=True) is_executive = models.IntegerField(blank=True, null=True) def __str__(self): return self.username dashboard.html: <a href="{% url 'home' %}">Home</a> <br> {% if user.is_authenticated %} <p>Is this the your first name?: {{my_custom_sql}}</p> {% else %} <p>You are not logged in, please do so.</p> {% endif %} I've read everything I can find around the issue but haven't found anything yet that has helped. I'm not sure if it has something to do with sessions or django hashing the info? But I'm not sure how to get around this safely. Anyone got any idea how to resolve … -
How to plug in a specific validator for all cases of a built-in type?
I recently noticed that some of my entries in a database coming from users contain incorrectly encoded strings, such as ó when ó was clearly meant. It's coming from copy-pasting of other websites that aren't properly encoded, which is beyond my control. I discovered that I can add this validator to catch such cases and raise an exception - here's an example with an attached model: from django.db import models from django.utils.translation import gettext_lazy as _ from django.core.exceptions import ValidationError import ftfy def validate_ftfy(value): value_ftfy = ftfy.ftfy(value) if value_ftfy != value: raise ValidationError( _('Potential UTF-8 encoding error: %(value)r' ' decoded to %(value_ftfy)r.'), params={'value': value, 'value_ftfy': value_ftfy} ) class Message(models.Model): content = models.CharField(max_length=1000, validators=[validate_ftfy]) def save(self, *args, **kwargs): self.full_clean() return super(Message, self).save(*args, **kwargs) The problem is that now that I discovered it, I see no point skipping it in any of my instances of CharField, TextField and the like. Is there a way to plug in this validator to all data types, so that if anything non-binary has invalid UTF-8, I can count on it not making it to the database? -
How to transfer data from a callback to another view in Django?
I have a function that makes a request to Erlang. Next, the Erlang sends a response to the url callback. I need this data in the original function to verify the success of the operation. Accordingly, the original function must wait until an answer arrives. How do I transmit this data? def pay(request): try: body = request.body.decode('utf-8') if not body: raise ValidationError('empty query') body = json.loads(body) for field_name in ['phone', 'amount', 'merchant_name', 'payment_type', 'prefix', 'number']: check_field(body, field_name) except ValidationError as error: return JsonResponse({ 'status': 'failed', 'errors': { 'code': 400, 'message': error.message }, }) except JSONDecodeError: return JsonResponse({ 'status': 'failed', 'errors': { 'code': 400, 'message': 'not Json or incorrect Json' }, }) active_subs = MfsSubscription.objects.filter( phone=body.get('phone'), is_subscribe=True, ) if not active_subs.exists(): response = mfs_create_and_activate(body.get('phone')) logger.info('activate code = {}'.format(response['code'])) if response is None: return JsonResponse({ 'status': 'failed', 'errors': { 'code': 500, 'message': 'Connection timeout', }, }) else: if response['code'] == 201 or response['code'] == 200: 'check data from callback function and next actions' @csrf_exempt def callbackpay(request): try: data = json.loads(request.body.decode("utf-8"))#here is the answer from Erlang logger.info('Callback with post data: {}'.format(data)) phone = data['details']['payment_source']['details']['msisdn'] handler = callback_factory(data['action']) response = JsonResponse({}, status=500) if handler: response = handler(phone, data) return JsonResponse({}, status=response.status_code) except ( KeyError, … -
Django Rest Framework: Set Permissions for function view
The default permissions requires token authentication. I have a function based view that has the api_view decorator. How can I explicitly set its permissions to not require authentication and csrf exempt? @api_view(['GET']) def activate(request, uidb64, token): .... -
Django get() returned more than one objects
I'm trying to add a song to the playlist model that I have but it keeps saying Direct assignment to the forward side of a many-to-many set is prohibited. Use songs.set() instead. My code for Playlist model: class Playlist(models.Model): image = models.ImageField() name = models.CharField(max_length=100) artist = models.ForeignKey(User, on_delete=models.CASCADE) fav = models.BooleanField(default=False) songs = models.ManyToManyField(Music) slug = models.SlugField(editable=False, default=name) def __str__(self): return self.name def get_absolute_url(self): return reverse('playlist-detail', kwargs={'pk': self.pk}) @classmethod def add_music(cls, new_song): playlist, created = cls.objects.get_or_create(songs=new_song) playlist.songs.add(new_song) @classmethod def remove_music(cls, new_song): playlist, created = cls.objects.get_or_create(songs=new_song) playlist.songs.remove(new_song) My code for Song model: class Music(models.Model): image = models.ImageField() name = models.CharField(max_length=100) song = models.FileField(upload_to='musics/', blank=False, null=False) artist = models.ForeignKey(User, on_delete=models.CASCADE) fav = models.BooleanField(default=False) slug = models.SlugField(editable=False, default=name) lyrics = models.TextField(default="Unknown lyrics") genre = models.CharField( max_length=2, choices=GENRE, null=False, blank=False, default="" ) def __str__(self): return self.name def get_absolute_url(self): return reverse('post-detail', kwargs={'pk': self.pk}) my view method that adds the song to the playlist object def add_to_playlist(request, operation, pk): new_song = Music.objects.get(pk=pk) if operation == 'add': Playlist.add_music(new_song) elif operation == 'remove': Playlist.remove_music(new_song) return redirect('/') Html code: {% for i in music %} {% for v in playlist %} <a class="dropdown-item" href="{% url 'add_to_playlist' operation='add' pk=i.pk %}">Add to{{v.name}}</a> {% endfor %} {% endfor %} -
MAYAN-EDMS reviews and capabilities
I am currently working on a project to convert my organization away from manual file systems. We have a fairly narrow set of requirements for a document management system, and it appears that something open source like Mayan may be suitable for our needs. What I've not been able to discern from the documentation / website is whether the software system is capable of dealing with large numbers of documents and clients on a network. Our document count is in the neighborhood of 100 billions documents, and we have a dedicated scanning department (approx 1000 users) and a client-consumer base of about 6000 users. Some initial questions: Whether the Mayan is capable of dealing with large (100 Bn) numbers of documents. Will Mayan work at an enterprise level with the user and document base I've described? Can Mayan use MS SQL, or is it PostegreSQL / MySQL only? What would a file/data migration to Mayan look like? Is there any articles / documents that could help me jump into the code base? I've been doing quite a bit of Python work lately, and would be very interested in seeing how your system works under-the-hood. Please suggest any other open source … -
Error while executing 'pip install virtualenv p1'. It installed virtualenv perfectly but It generated error while collecting p1
When i executed the above said command in command prompt it generate the following error: Requirement already satisfied: virtualenv in c:\users\user\appdata\local\programs\python\python37\lib\site-packages (16.7.8) Collecting p1 Using cached https://files.pythonhosted.org/packages/24/16/a5c2ade5472a8fca3d8ef5cee2214fd49ef827269e85e1c39b7bd6fba56a/p1-1.0.1.tar.gz Collecting rpi.gpio>=0.5.5 Using cached https://files.pythonhosted.org/packages/cb/88/d3817eb11fc77a8d9a63abeab8fe303266b1e3b85e2952238f0da43fed4e/RPi.GPIO-0.7.0.tar.gz Installing collected packages: rpi.gpio, p1 Running setup.py install for rpi.gpio ... error ERROR: Command errored out with exit status 1: command: 'c:\users\user\appdata\local\programs\python\python37\python.exe' -u -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'C:\\Users\\USER\\AppData\\Local\\Temp\\pip-install-rb458cr0\\rpi.gpio\\setup.py'"'"'; __file__='"'"'C:\\Users\\USER\\AppData\\Local\\Temp\\pip-install-rb458cr0\\rpi.gpio\\setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' install --record 'C:\Users\USER\AppData\Local\Temp\pip-record-blgtvdr9\install-record.txt' --single-version-externally-managed --compile cwd: C:\Users\USER\AppData\Local\Temp\pip-install-rb458cr0\rpi.gpio\ Complete output (32 lines): running install running build running build_py creating build creating build\lib.win-amd64-3.7 creating build\lib.win-amd64-3.7\RPi copying RPi\__init__.py -> build\lib.win-amd64-3.7\RPi creating build\lib.win-amd64-3.7\RPi\GPIO copying RPi\GPIO\__init__.py -> build\lib.win-amd64-3.7\RPi\GPIO running build_ext building 'RPi._GPIO' extension creating build\temp.win-amd64-3.7 creating build\temp.win-amd64-3.7\Release creating build\temp.win-amd64-3.7\Release\source C:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.23.28105\bin\HostX86\x64\cl.exe /c /nologo /Ox /W3 /GL /DNDEBUG /MT -Ic:\users\user\appdata\local\programs\python\python37\include -Ic:\users\user\appdata\local\programs\python\python37\include "-IC:\Program Files (x86)\Microsoft Visual Studio\2019\BuildTools\VC\Tools\MSVC\14.23.28105\include" "-IC:\Program Files (x86)\Windows Kits\NETFXSDK\4.8\include\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\ucrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\shared" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\um" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\winrt" "-IC:\Program Files (x86)\Windows Kits\10\include\10.0.18362.0\cppwinrt" /Tcsource/py_gpio.c /Fobuild\temp.win-amd64-3.7\Release\source/py_gpio.obj py_gpio.c source/py_gpio.c(87): error C2143: syntax error: missing ';' before '{' source/py_gpio.c(115): warning C4244: '=': conversion from 'Py_ssize_t' to 'int', possible loss of data source/py_gpio.c(119): warning C4244: '=': conversion from 'Py_ssize_t' to 'int', possible loss of data source/py_gpio.c(200): error C2143: syntax error: missing … -
How to get all subscription end date, so that I can send email to customer using stripe and python?
I created web hook http://example.com/api/webhook/ NOw I want to trigger this url, to get all the subscribed id, which end date is coming, or expired subscribed id Is there any code or demo to obtain it?? -
How to add minutes to datetime in postgres via django
TL;DR: I want to add minutes to a datetime in postgres and can think of two ways to do it. Consider the following django model: from django.db import models class AppointmentManager(models.Manager): def get_queryset(self): return super().get_queryset().annotate( end=models.ExpressionWrapper( models.F('start') + models.F('duration'), output_field=models.DateTimeField(), ) ) class Appointment(models.Model): start = models.DateTimeField() duration = models.DurationField() objects = AppointmentManager() Note that end is computed dynamically in the database by adding start and duration. This does exactly what I want. However, I want the UI for the duration to be a number input that gives the duration in minutes. My current approach is to use the following form field: import datetime from django import forms class MinutesField(forms.DurationField): widget = forms.NumberInput def prepare_value(self, value): if isinstance(value, datetime.timedelta): return int(value.total_seconds() / 60) return value def to_python(self, value): if value in self.empty_values: return None if isinstance(value, datetime.timedelta): return value if isinstance(value, str): value = int(value, 10) return datetime.timedelta(seconds=value * 60) This looks a little brittle to me. Is it also possible to store the duration as integer and transform it to a duration dynamically? -
Core compute for solid returned an output multiple times
I am very new to Dagster and I can't find answer to my question in the docs. I have 2 solids: one thats yielding tuples(str, str) that are parsed from XML file, he other one just consumes tuples and stores objects in DB with according fields set. However I am running into an error Core compute for solid returned an output multiple times. I am pretty sure I made fundamental mistake in my design. Could someone explain to me how to design this pipeline in the right way or point me to the chapter in the docs that explains this error? @solid(output_defs=[OutputDefinition(Tuple, 'classification_data')]) def extract_classification_from_file(context, xml_path: String) -> Tuple: context.log.info(f"start") root = ET.parse(xml_path).getroot() for code_node in root.findall('definition-item'): context.log.info(f"{code_node.find('classification-symbol').text} {code_node.find('definition-title').text}") yield Output((code_node.find('classification-symbol').text, code_node.find('definition-title').text), 'classification_data') @solid() def load_classification(context, classification_data): cls = CPCClassification.objects.create(code=classification_data[0], description=classification_data[1]).save() @pipeline def define_classification_pipeline(): load_classification(extract_classification_from_file())