Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Djang multiple levels of template extension while keeping the elements of the upper levels
I have 3 templates as following: base.html (the top level template, as usual). <body> <div id="header"> ... </div> <div id="content"> {% block content %} {% endblock %} </div> </body> category.html : {% extends "base.html" %} {% block content %} ....display some elements here... <div class="item_row"> {% block level_2_content %} {% endblock %} </div> </div> {% endblock %} and item.htlm {% extends "category/category.html" %} {% block level_2_content %} <div id="test_div"> {% for item in menu_items %} <p>{{item.name}}</p> {% endfor %} </div> {% endblock %} When item.html is rendered, all the elements that were rendered by category.html are gone. Only the elements of the base.html are retained. How do I retain all elements in all parent templates instead of just base.html? A general method to do this for more than 3 levels of extension like in my case? -
Django Rest Framework object has no attribute pk
I am working in Django / DjangoRestFramework trying to use extra actions to build out a foreignkey that is routable. I am getting the following error, I believe it has something to do with the create method on the FinancialsSerializer, or lack thereof, but I am not sure web_1 | AttributeError: 'dict' object has no attribute 'pk' stocks.viewset 19 class StockViewSet(viewsets.ModelViewSet): 20 queryset = Stock.objects.all() 21 serializer_class = StockSerializer 22 lookup_url_kwarg = "ticker" 23 lookup_field = "ticker__iexact" 24 25 @action(detail=True, methods=["POST", "GET"]) 26 def financials(self, request, ticker=None): 27 if request.method == "GET": 28 stock = self.get_object() 29 financials = stock.get_financials() 30 financials = FinancialsSerializer(financials) 31 return Response(financials.data) 32 if request.method == "POST": 33 serializer = FinancialsSerializer(request.data) 34 financials = Financials.objects.create(serializer.data) 35 financials.save() FinancialsSerializer 9 class FinancialsSerializer(WritableNestedModelSerializer): 10 balance_sheet = BalanceSheetSerializer() 11 income_statement = IncomeStatementSerializer() 12 cashflows_statement = CashflowsStatementSerializer() 13 14 class Meta: 15 model = Financials 16 fields = ["balance_sheet", "income_statement", "cashflows_statement"] -
django simple history field indexing
How can I tell DSH to index particular field? Some queries that I do to historical models take too much time I've base abstract model and all my models inherit from that model. The history field is also defined in this base model: class BaseModel(models.Model): class PublishingStatus(models.TextChoices): DRAFT = 'draft', _('Draft') ACCEPTED = 'accepted', _('Accepted'), REJECTED = 'rejected', _('Rejected'), MODIFIED = 'modified', _('Modified') publishing_status = models.CharField( max_length=9, choices=PublishingStatus.choices, default=PublishingStatus.DRAFT, help_text=_("Publishing status represents the state of the object. By default it is 'draft'") ) history = HistoricalRecords(inherit=True) And I've also added indexes in this base model class Meta: abstract = True indexes = [models.Index(fields=[ 'publishing_status', ])] It would be nice if Django Simple History could check which fields are indexed and create the same indexes in the historical models Maybe there is a way to tell django simple history explicitly which field must be indexed additionally? -
ValueError at /profiles/user-profile/ Field 'id' expected a number but got 'testuser'
I am creating follow system in my project but got an error. Can anybody tell me how i can fix it? models.py class UserProfile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) follower = models.ManyToManyField(User, related_name ='is_following',blank=True) avatar = models.ImageField(("Avatar"), upload_to='displays', default = '1.jpg',height_field=None, width_field=None, max_length=None,blank = True) create_date = models.DateField(auto_now_add=True,null=True) def __str__(self): return f'{self.user.username}' views.py class UserProfileFollowToggle(View): def post(self, request, *args, **kwargs): print(request.POST) user_to_toggle = request.POST.get('username') print(user_to_toggle) profile_ = UserProfile.objects.get(user__username__iexact=user_to_toggle) profile_1 = request.user.userprofile user = request.user print(user,'p') if user_to_toggle in profile_.follower.all(): profile_.follower.remove(user_to_toggle) else: profile_.follower.add(user_to_toggle) return redirect(f'/profiles/{profile_.pk}') If more code or detail is require than tell me in comments i will share that by updating my question with that detail. -
In Django My form is resubmitting every time I refresh, I know I can solve this by redirecting it but i also want to pass pass data to my template
This is my code in views def pay(request): if request.method == 'POST': name=request.POST.get('name') email=request.POST.get('email') phone=request.POST.get('phone') course_name=request.POST.get('course_name') amount=int(request.POST.get('amount')) client = razorpay.Client(auth=('rzp_test_W8wCwbUqAGeqku','uETWabWBUeK53r70Qnz0Sg2Vknb')) payment = client.order.create({'amount':amount*100, 'currency':'INR', 'payment_capture':'1'}) order = Order(course_name=course_name, name=name, email=email, phone=phone, amount=amount, payment_id=payment['id']) order.save() return render(request, 'pay.html',{'payment':payment}) `I know I can solve this by redirecting it like this return redirect('womenlab:pay') but I also want to pass payment variable` return render(request, 'pay.html') I do not want every time I refresh the page it get resumbitted, please help -
Djnago Template - Url with multiple parameter
I am using Django template. I want to add multiple parameter in URL currently I am passing only one parameter my reset_password.html Click on this link to reset your password {% if htmlVersion %} <div> <a href="{{domain}}{% url 'pweuser:user_password_sms_reset' token %}"> {{domain}}{% url 'pweuser:user_password_sms_reset' token %} </a> </div> {% else %} {{domain}}{% url 'pweuser:user_password_sms_reset' token %} {% endif %} This link will expire in 15 minutes my urls.py url(r"^resetPasswordSms/(?P<token>[-\w_=]{28})/$", PasswordResetSmsView.as_view(), name="user_password_sms_reset",), my views.py t = loader.get_template("reset_password.html") c = {"htmlVersion": True, "domain": settings.SITE_DOMAIN, "token": token.token} htmlVersion = t.render(c) c = {"htmlVersion": False, "domain": settings.SITE_DOMAIN, "token": token.token} textVersion = t.render(c) Here its is working good in this I want to add more than 1 parameter. means here token is the 1st parameter and I need to add userId as 2nd parameter and need to pass in template.. how can i add multiple parameter in URL and template URL -
Trying to return a variable mid script to my template
I am wanting to display a dynamic count on my home.html. While my for loop is running I would like my Template to display the current count of the loop. Is this possible, and if so what is this process called so I can read up on it. home.html <!DOCTYPE html> <html> <body> {% block content %} {% if output >= 1 %} <p>Current count is {output}</p> {%endif%} {% endblock content %} </body> </html> views.py def page_objects(request): output = 0 for row in c: output = output + 1 return output return render(request, 'home.html') urls.py from django.urls import path from . import views urlpatterns = [ path('', views.home, name = 'home'), path('views', views.page_objects, name = 'page_objects') ] -
How to get data form MySQL by dates in django?
I have an app that I'm building using Django and I want to filter the data by dates. Basicaly, I used the raw sql query for this one. Is there any one that can help me? Here's what I've one so far : views.py def getConnection(): host = config['oof_ord']['host'] port = config['oof_ord']['port'] database = config['oof_ord']['database'] password = config['oof_ord']['password'] user = config['oof_ord']['user'] try: connection = MySQLdb.connect(host=host, user=user, password=password, database=database) cursor = connection.cursor() print("Connection to" + f'{connection}' + "successfully") return cursor except: return False def getDate(request): weight_date = None if request.GET.get('weight_date') != None and request.GET.get('weight_date') != "": weight_date = request.GET.get('weight_date') else: weight_date = request.session.get('weight_date') return weight_date def filler_weight(request): template_name = 'oof_ord/fill_weight.html' cursor = getConnection() date = getDate(request) try: query = "SELECT * FROM fill_weight where weight_date = '{rundate}' ".format(rundate = getDate(request)) cursor.execute(query) rows = cursor.fetchall() print(rows[1][5]) for row in rows: print(row) finally: cursor.close() return render(request, template_name, {"rows" : rows}) My code is working if I am going to show all the data in my MySQL but what if I want to filter data by it's specific dates and show it in my template ? BTW, I get an error running this: mysql.connection.query(self, query) MySQLdb._exceptions.OperationalError: (1525, "Incorrect DATE value: 'None'") -
how to combine image and videoembed in listview django
I have two class model image and videoembed. the question is how to put two class in single listview.. when there's no image, video embed show up it's my code. views.py def news_list(request): """news list category""" category = Category.objects.get(id=1) a_list = Article.objects.filter(category=1) g_list = Gallery.objects.filter(category=1) v_list = Videoembed.objects.filter(category=1) object_list = sorted( chain(a_list, g_list, v_list), key=attrgetter("publish"), reverse=True ) paginator = Paginator(object_list, 4) # 3 posts in each page page = request.GET.get("page") try: posts = paginator.page(page) except PageNotAnInteger: # If page is not an integer deliver the first page posts = paginator.page(1) except EmptyPage: # If page is out of range deliver last page of results posts = paginator.page(paginator.num_pages) return render( request, "blog/post/news.html", {"category": category, "page": page, "posts": posts}, ) and in news.html <div class="row"> {% for post in posts %} <div class="col-lg-4 col-md-6 col-sm-12 pb-4"> {% if forloop.counter0|divisibleby:3 and not forloop.first %}<div class="w-100"></div>{% endif %} {% video post.video %} <img src="{{ post.images.url }}" width="300px"> <P> <h2><a href="{{ post.get_absolute_url }}"> {{ post.title }} </a> </h2> </p> <p class="date"> Published {{ post.publish }} by {{ post.author }} </p> {{ post.body|safe|truncatewords:30|linebreaks }} </div> {% endfor %} thanks for any help -
Saving/Updating nested data from 3rd party API Django Rest
serializers.py class MajorUnitLaborSerializer(serializers.ModelSerializer): class Meta: model = MajorUnitLabor fields = '__all__' depth = 1 class MajorUnitPartsSerializer(serializers.ModelSerializer): class Meta: model = MajorUnitParts fields = ['DealerId', 'Description', 'SetupInstall', 'Qty', 'Cost', 'Price'] depth = 1 class MajorUnitSerializer(serializers.ModelSerializer): Parts = MajorUnitPartsSerializer(many=True) Labor = MajorUnitLaborSerializer(many=True) class Meta: model = MajorUnit fields = '__all__' def create(self, validated_data): parts_data = validated_data.pop('Parts') labor_data = validated_data.pop('Labor') majorunit = MajorUnit.objects.create(**validated_data) for part_data in parts_data: MajorUnitParts.objects.create(Unit=majorunit, **part_data) for labor in labor_data: MajorUnitLabor.objects.create(MajorUnitHeaderId=majorunit, **labor) return majorunit def update(self, instance, validated_data): instance.Parts = validated_data.get('Parts', instance.Parts) [setattr(instance, k, v) for k, v in validated_data.items()] instance.save() instance.Labor = validated_data.get('Labor', instance.Labor) [setattr(instance, k, v) for k, v in validated_data.items()] instance.save() return instance views.py @api_view(['GET','POST']) def majorunitapilist(request): query = '76179602' api_majorunit_list = get_majorunit(query) for unit in api_majorunit_list: pk = unit.get('MajorUnitHeaderId') try: obj = MajorUnit.objects.get(MajorUnitHeaderId=pk) serializer = MajorUnitSerializer(instance=obj, data=unit) if serializer.is_valid(): serializer.save() except: serializer = MajorUnitSerializer(data=unit) if serializer.is_valid(): serializer.save() else: print(serializer.errors) return Response(serializer.data) I have so many questions I don't know where to begin. Here is the basic rundown of what I'm trying to do.. Make call to 3rd party API Create/Update records in my database (data-dump) The api_majorunit_list var is a complete list of the data queried. My thought is to grab the value I'm using as … -
Can't pass dictionary in Django
So I was trying something new and I decided to try Django... And I was building a self motivated project of a hotel eCommerce site.. I was playing around with different template tags and I found moyself in a bit of a pickle... :/ Below is the attached code, if you have time to check it... Thank You... Also I have another question: Does include tag automatically inherits the contexts from the index html or should I have to pass the context from the index page with a 'with' keyword? Although I tried both "with" and without "with" with no luck. Thanks again, I am stuck in this for quite some time now... My views.py def home_view(request, *args, **kwargs): ob1 = Room.objects.all() return render(request, 'index.html', {'Rooms': ob1}) My included html snippet: {% if not Rooms %} <script type="text/javascript">console.log("No!!")</script> {% endif %} {% if Rooms %} {% for room in rooms %} <h1>{{ room.Room_Types }}</h1> <script type="text/javascript">console.log("Yes!!")</script> {% endfor %} {% endif %} Sadly, The console log was always no!!! ;( -
Encrypted model fields for sensitive data in Django
Hi I am currently developing a website with a react frontend and django backend. I need to store a gitlab access token for each user in my db so that it can be used to interact with the gitlab api (using python gitlab api https://python-gitlab.readthedocs.io/en/stable/), so that the user can create or modify a git repository using this access token. I want to store the GitLab access token in a model with the users email so that when they for example want to create a repository the view will take the users input such as repository name etc and then use the access token to create the repository but I am wary about storing the access token as I know this could be a security risk. This is for a personal project for self-education purposes so if I do make a mistake the repurcussions will be low as no actual users will be using this program just me. I still want to do this the "right way" however and I am wondering, is there any way in django to create an encrypted field for the access token field in the model, that can then be obtained and decrypted when it … -
Django setvar custom template variable availability issue
I created an custom_template_tag.py as this: from django import template register = template.Library() @register.simple_tag def setvar(val=None): return val now in my template I am looping through db and getting the correct data, but when I am trying to use my set variable outside of for loop I get nothing {% for personLiked in Post.likes.filter %} {% if request.user.id == personLiked.id %} {% setvar "True" as is_liked %} {{is_liked}} <--------GETTING VALUE HERE {% endif %} {% endfor %} {{is_liked}} <--------NOT GETTING VALUE HERE Not sure what I am missing since I believe this should be available to the rest of the page. I am aware that this is happening because I am inside of for loop. but Any suggestions how to solve this? -
Postgres manipulating sequence for bulkinsert on multiple tables
I am writing a migration script to migrate a data from old db schema to new db schema. I am doing bulk insert two tables lets assume Table A and Table B, Table B have a fk relation with Table A. The reason i am doing bulkinsert because the old tables have millions of data, so i am using postgres copy method. To achive this i am manipulating Table A sequence to allocate from N number to N number and using that allocated number to generate the data from old database to a csv and table 2 relation id. In this method everything working fine, but when i insert something through the API which is written in Django. For insertion the Django still taking the id's from the allocated sequence. Because of this even if the migration run smooth after migration the insertion is failing. I have chekced the sequence manipulation part, the count increments are working fine and also the nextval is also fetching the right one when i do it in the console. any idea what i am missing here? -
Posting access_token to Django backend to retrieve a DRF token for API usage results to Your credentials aren't allowed in social_django
What I am doing : I am trying to use google sign in button so that I can get a tokenId and send it to the django rest api where it can verify with Google api and create a new user from the email retrieved (if the user is not registered by the email ID) and respond with a default Token (Django Rest Frameworks's) to the Android Client so that it can further be used to do some CRUD operations for the DRF How I am doing : I created two credentials, one for the Android App and the other for the web app Added the SHA-1 fingerprint in the Android credential by copying it from Android studio's gradle signingReport (Without providing SHA-1 to the credential one will not get the desired idToken ) Then I am manually getting the tokenId private void handleSignInResult(Task<GoogleSignInAccount> completedTask) { try { GoogleSignInAccount account = completedTask.getResult(ApiException.class); // Signed in successfully, show authenticated UI. updateUI(account); } catch (ApiException e) { // The ApiException status code indicates the detailed failure reason. // Please refer to the GoogleSignInStatusCodes class reference for more information. Log.w(this.getLocalClassName(), "signInResult:failed code=" + e.getStatusCode()); updateUI(null); } } private void updateUI(GoogleSignInAccount account){ Toast.makeText(this,"SUCCESS",Toast.LENGTH_SHORT).show(); Log.w(this.getLocalClassName(), … -
Running Django server via Dockerfile on GAE Custom runtime
I am trying to deploy my Docker container with Django server on Google APP Engine Custom environment, although it gets deployed but it doesn't start working the way it should work i.e it seems django runserver is not working . App.yaml runtime: custom env: flex service: jobs resources: cpu: 4 memory_gb: 8 disk_size_gb: 30 DOckerfile: FROM hsingh1993/jobs:fourth EXPOSE 8000/tcp RUN id USER jovyan WORKDIR /home/jovyan/trustdjobs CMD ["python","./manage.py","runserver","0.0.0.0:8000"] -
Why does random in django rest serializer always return the same field?
I have a simple serializer class Serializer(serializers.Serializer): name = serializers.CharField(required=False, default='someName') id = serializers.IntegerField(required=False, default=random.randrange(100, 200)) And when I create multiple instances of the serializer it always returns the same field a = Serializer(data={}) a.is_valid(data={}) data = a.data data['id'] // return for example 150 b = Serializer(data={}) b.is_valid(data={}) b_data = b.data b_data['id'] // return also 150 Why it happens? How to get rid of this? -
Getting undefined from .val()
So when I call: var productId = $(this).find('#productnumber').val(); I get undefined as a result. However, when I use var productId = $('#productnumber').val(); I get the id value. But in HTML I have a for loop which makes multiple similar items with different id's. and without (this) I see the id only of the first element -
how to make an object for multiple users , similar to facebook page django
i try to make an app for real estates , some of real estates profile have several employees , the owner of the real estate make an object from RealEstate class , and generates a unique uuid key , then if the Real estate agency had several employees , each employee make a profile ,and the owner should provide the key to access to the RealEstate object , in order to be one the RealEstate employees accounts : class Profile(models.Model): user = models.OneToOneField(User , on_delete=models.CASCADE) image = models.ImageField(upload_to='profiles' , default='pyart.png') phone = models.CharField(max_length=11 , default='',blank=True) bio = models.CharField(max_length=100 , default='',blank=True) date = models.DateTimeField(default=datetime.now) active = models.BooleanField(default=False) def __str__(self): return f'{self.user}' and each RealEstate can have several admins with one super admin , who added other admins depend on the code field class RealEstate(models.Model): admins = models.ManyToManyField(User,on_delete=models.CASCADE) code = models.UUIDField(unique=True,default=uuid.uuid4,editable=False) real_estate_name = models.CharField(max_length=40,unique=True) image = models.ImageField(upload_to='realestate',default='realestates.png') phone = models.CharField(max_length=11) bio = models.CharField(max_length=200) city = models.ForeignKey(City,on_delete=models.CASCADE) address = models.ForeignKey(Address,on_delete=models.CASCADE) nearest_place = models.CharField(max_length=40) date = models.DateTimeField(default=auto_now_add=True) status = models.BooleanField(default=True) and the listings table class Listing(models.Model): objects = ListingManager() company = models.ForeignKey(settings.AUTH_USER_MODEL , on_delete=models.CASCADE) title = models.CharField(max_length=200) slug = models.SlugField(unique=True , default=radnom_generating(),blank=True) #others how to make it happen , only by accessing the RealEstate … -
Line chart by dates with django models
I’m trying to build a line chart using Chart.js and Django. This chart will shows the account of class “anomalies” per month. The class anomalie has date_report attribute. This date will repeat because there are many anomalies that could happen in the same month. So I need to group them per month and count the amount of anomalies in this month, then I need to show this in a graph, in order to see the historic progress: In X the month and In Y the amount of anomalies To achieve that in my view.py I have trunked by month months and count by id count_per_month like this: @login_required(login_url='login') def home_screen_view(request): context = {} user_aisles = request.user.aisle.all() list_anomalies_user = [] anomalies = Anomalie.objects.all() anomalies_per_aisle = anomalies.filter(aisle__in=user_aisles) # line chart months = anomalies_per_aisle.annotate( month=TruncMonth('date_report')).values('month').annotate(c=Count('id')).values('month') count_per_month = anomalies_per_aisle.annotate( month=TruncMonth('date_report')).values('month').annotate(c=Count('id')).values('c') print('months', months) print('count_per_moth', count_per_month) context = {'list_anomalies_user': list_anomalies_user, 'anomalies_per_aisle': anomalies_per_aisle,'count_per_month': count_per_month, 'months': months} return render(request, "personal/home.html", context) Then I’m passing this data to "labels" and "data" into the scripts using “safe” like this: <script> var ctx = document.getElementById("myAreaChart"); //"myAreaChart" var myLineChart = new Chart(ctx, { type: 'line', data: { labels: [{{ months| safe}}], datasets: [{ label: "Sessions", lineTension: 0.3, backgroundColor: "rgba(2,117,216,0.2)", borderColor: "rgba(2,117,216,1)", pointRadius: … -
Calling a Django function inside an AWS Lambda
I want to defer some processing load from my Django app to an AWS Lambda. I'm calling my code from the Lambda like this: lambda.py: @bc_lambda(level=logging.INFO, service=LAMBDA_SERVICE) def task_handler(event, context): message = event["Records"][0]["body"] renderer = get_renderer_for(message) result = renderer.render() return result get_renderer_for is a factory method that returns an instance of the class Renderer: from myproject.apps.engine.documents import ( DocumentsLoader, SourceNotFound, source_from_version, ) from myproject.apps.engine.environment import Environment class Renderer: def __init__(self, message): self.message = message def render(self): ENVIRONMENT = Environment(DocumentsLoader()) version_id = self.message.get("version_id") try: source = source_from_version(version_id) except SourceNotFound: source = None template = ENVIRONMENT.from_string(source) if template: return template.render(self.message) return None def get_renderer_for(message): """ Factory method that returns an instance of the Renderer class """ return Renderer(message) In CloudWatch, I see I'm getting this error: module initialization error. Apps aren't loaded yet. I understand that Django is not available for the Lambda function, right? How can I fix this? How can I make the rest of the project available to the lambda function? -
Email verification is not enforced. Disregarding ACCOUNT_EMAIL_VERIFICATION setting
I'm using two packages to assist me with authentication. One is js_rest_auth and the other one is allauth. The latter has a setting to require users to validate their email addresses before a login is possible. I'm setting ACCOUNT_EMAIL_VERIFICATION = "mandatory" but it has no effect. My relevant settings look as follows: INSTALLED_APPS = [ ... "django.contrib.sites", "rest_framework.authtoken", "allauth.account", "allauth.account", "allauth.socialaccount", "dj_rest_auth", .... ] ACCOUNT_EMAIL_VERIFICATION = "mandatory" ACCOUNT_EMAIL_CONFIRMATION_EXPIRE_DAYS = 90 ACCOUNT_USER_MODEL_EMAIL_FIELD = "email" ACCOUNT_AUTHENTICATION_METHOD = "email" ACCOUNT_EMAIL_REQUIRED=True ACCOUNT_UNIQUE_EMAIL = True ACCOUNT_USERNAME_REQUIRED=False ACCOUNT_USER_MODEL_USERNAME_FIELD = "email" ACCOUNT_PRESERVE_USERNAME_CASING = False ACCOUNT_ADAPTER = "users.accountadapter.CustomAccountAdapter" AUTHENTICATION_BACKENDS = [ 'django.contrib.auth.backends.ModelBackend', 'allauth.account.auth_backends.AuthenticationBackend', ] REST_FRAMEWORK = { .... "DEFAULT_AUTHENTICATION_CLASSES": [ "rest_framework.authentication.TokenAuthentication", ], "DEFAULT_PERMISSION_CLASSES": [ "rest_framework.permissions.IsAuthenticated", ] } The users I create aren't verified (verified attribute an Email Address Model) but are created with is_active=True. When I send a login request for a non-verified user, a valid token is issued. -
How to run python script as daemon/cronjob in Django?
I have developped a Django app and try to solve what should be simple... but more I read about this and more it seems to be complicated. I want an email to be send to new user each time new user account is created in auth_user. I first thought about signals and it works but not when I execute a sql script to create user account. So, I thought about using trigger and Postgresql LISTEN/NOTIFY. I have created a trigger on auth_user insert and a function executed with this trigger that NOTIFY this event using perform pg_notify('new_user', NEW.username); Then, I have a python script that LISTEN new_user signal and send email. #!/usr/bin/env python # -*- coding: utf-8 -*- # https://www.depesz.com/2012/06/13/how-to-send-mail-from-database/ # https://www.psycopg.org/docs/connection.html # https://www.psycopg.org/docs/advanced.html#async-notify import select import psycopg2 import psycopg2.extensions from django.core.mail import send_mail import random, string from django.contrib.auth.hashers import make_password dbc = psycopg2.connect(database='db', host='localhost', port=5433, user='user', password='user') dbc.set_isolation_level(psycopg2.extensions.ISOLATION_LEVEL_AUTOCOMMIT) cur = dbc.cursor() cur.execute('LISTEN new_user_handle') while 1: if not select.select([dbc], [], [], 5) == ([], [], []): dbc.poll() while dbc.notifies: notify = dbc.notifies.pop() user_email = [] password = generer_mot_de_passe(8) user_email.append('user@domain.fr') email = email_compte(user_email,notify.payload,password.get("plaintext")) def generer_mot_de_passe(length): """Générer une chaîne aléatoire de longueur fixe""" motDePasse = {} str = string.hexdigits password_plaintext = ''.join(random.choice(str) … -
Failed to establish a new connection: [Errno -3] Temporary failure in name resolution in requests python
I am getting name resolution error with requests occasionally, it's happening approx once in 20 requests. I have checked with request domain service provider, they say it works fine with their other clients. I am not sure if this is because of DNS resolution on the system level. I am running an ubuntu instance on digital ocean. Let me know if anyone else has faced this problem as I am facing(on an occasional basis). Please find the stack trace gaierror: [Errno -3] Temporary failure in name resolution File "urllib3/connection.py", line 159, in _new_conn (self._dns_host, self.port), self.timeout, **extra_kw) File "urllib3/util/connection.py", line 57, in create_connection for res in socket.getaddrinfo(host, port, family, socket.SOCK_STREAM): File "python3.7/socket.py", line 752, in getaddrinfo for res in _socket.getaddrinfo(host, port, family, type, proto, flags): NewConnectionError: <urllib3.connection.VerifiedHTTPSConnection object at 0x7f53b0d24790>: Failed to establish a new connection: [Errno -3] Temporary failure in name resolution File "urllib3/connectionpool.py", line 600, in urlopen chunked=chunked) File "urllib3/connectionpool.py", line 343, in _make_request self._validate_conn(conn) File "urllib3/connectionpool.py", line 839, in _validate_conn conn.connect() File "urllib3/connection.py", line 301, in connect conn = self._new_conn() File "urllib3/connection.py", line 168, in _new_conn self, "Failed to establish a new connection: %s" % e) MaxRetryError: HTTPSConnectionPool(host='demo.api.afex.com', port=7890): Max retries exceeded with url: /api/bank/find (Caused by … -
Update Form Instances when marked for Deletion
I am trying to update an instance of a form model with 'deleted' values for auditing, and not actually delete the records. Currently I have the following views.py for del_form in formset.deleted_forms: del_form.save(commit=False) del_form.cleaned_data['id_trn'].deleted_trn = True del_form.cleaned_data['id_trn'].date_deleted_trn = datetime.datetime.now() del_form.cleaned_data['id_trn'].deleted_usr_trn = request.session.get('user') del_form.save() However, it's not updating the DB record. TIA!