Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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! -
Django form ChoiceField not selected when editing existing instance
I'd like to design a modelform that has a choicefield field with values that depend on the value of another field of the same form. For the sake of example, here is the modelform. The course day can be selected for each full-day course. For example, if the user has chosen MATH101, the course_day choicefield should give them a different set of days than if the user has chosen a CMPT101 course: class CourseFeeForm(ModelForm): class Meta: model = Course fields = ['course_name', 'course_day',...] def __init__(self, *args, **kwargs): super(CourseFeeForm, self).__init__(*args, **kwargs) if self.instance and self.instance.course_name == 'CMPT101': self.fields['course_day'] = forms.ChoiceField( choices= ( ('monday', 'Monday'), ('tuesday', 'Tuesday') ) elif self.instance and self.instance.course_name == 'MATH101': self.fields['course_day'] = forms.ChoiceField( choices = ( ('monday', 'Monday'), ('wednesday', 'Wednesday'),('friday', 'Friday')) ... The problem is that in the template for the edit view, I'd like the form to display what the user already selected, but if the user has selected Monday as the course_day, the <option value="monday">Monday</option> is missing the selected="selected" presumably because in __init__, we have changed the choicefield based on the course_name and so the default behavior of attaching the selected="selected" to the already selected option is overriden. Then, the question is how to bring the … -
how can we slove this path error of psycopg2 in linux?
I am using conda package and while trying to install psycopg2 i got this error. I want this for postgis and i am running on ubuntu. ERROR: Command errored out with exit status 1: command: /home/srijan/anaconda3/envs/django/bin/python -c 'import sys, setuptools, tokenize; sys.argv[0] = '"'"'/tmp/pip-install-s5yimrpg/psycopg2/setup.py'"'"'; __file__='"'"'/tmp/pip-install-s5yimrpg/psycopg2/setup.py'"'"';f=getattr(tokenize, '"'"'open'"'"', open)(__file__);code=f.read().replace('"'"'\r\n'"'"', '"'"'\n'"'"');f.close();exec(compile(code, __file__, '"'"'exec'"'"'))' egg_info --egg-base /tmp/pip-pip-egg-info-cop18avg cwd: /tmp/pip-install-s5yimrpg/psycopg2/ Complete output (14 lines): running egg_info creating /tmp/pip-pip-egg-info-cop18avg/psycopg2.egg-info writing /tmp/pip-pip-egg-info-cop18avg/psycopg2.egg-info/PKG-INFO writing dependency_links to /tmp/pip-pip-egg-info-cop18avg/psycopg2.egg-info/dependency_links.txt writing top-level names to /tmp/pip-pip-egg-info-cop18avg/psycopg2.egg-info/top_level.txt writing manifest file '/tmp/pip-pip-egg-info-cop18avg/psycopg2.egg-info/SOURCES.txt' Error: pg_config executable not found. Please add the directory containing pg_config to the PATH or specify the full executable path with the option: python setup.py build_ext --pg-config /path/to/pg_config build ... or with the pg_config option in 'setup.cfg'. ---------------------------------------- ERROR: Command errored out with exit status 1: python setup.py egg_info Check the logs for full command output. -
Django how to get admin full name
I have a model named Post, and want to save the full name of the admin automatically who created(or edited) that post. I read about get_full_name() in django documentation, but I cannot understand how to call this method. Here is my Post model class Post(models.Model): post_id = models.AutoField postname = models.CharField(max_length=50) description = models.CharField(max_length=1000) location = models.CharField(max_length=30) user = // I want to store the logged in admin full name here -
Unable to create the django_migrations table (ORA-00907: missing right parenthesis)
I have used oracle database with django. I am new with integrating oracle with django. This is my models.py: models.py : from django.db import models # Create your models here. class Users(models.Model): id = models.AutoField(primary_key=True) datetimecreated = models.DateTimeField('created_time', null=True, blank=True) name = models.CharField(max_length=100) email = models.CharField(max_length=100) contact_no = models.CharField(max_length=100) class feed(models.Model): id = models.AutoField(primary_key=True) userid = models.CharField(max_length=2000) datetimecreated = models.DateTimeField('created_time', null=True, blank=True) img = models.CharField(max_length=100) desc = models.CharField(max_length=500) class feed(models.Model): id = models.AutoField(primary_key=True) userid = models.IntegerField(default=True) datetimecreated = models.DateTimeField('created_time', null=True, blank=True) img = models.CharField(max_length=100) desc = models.CharField(max_length=500) class feed_likes(models.Model): id = models.AutoField(primary_key=True) userid = models.IntegerField(default=True) feedid = models.IntegerField(default=True) datetimecreated = models.DateTimeField('created_time', null=True, blank=True) class feed_comments(models.Model): id = models.AutoField(primary_key=True) userid = models.IntegerField(default=True) feedid = models.IntegerField(default=True) datetimecreated = models.DateTimeField('created_time', null=True, blank=True) comment = models.CharField(max_length=500) I have also migrated the models py manage.py makemigrations api py manage.py sqlmigrate api 0001 But when executing this command py manage.py migrate It give this error django.db.migrations.exceptions.MigrationSchemaMissing: Unable to create the django_migrations table (ORA-00907: missing right parenthesis) Please help me to solve this problem -
Django - Display success messages for 10 or 20 seconds in Django Admin Panel
I was working in Django admin. So while saving a modal there is an automatic success message that appears after saving. I was wondering if it is possible to set the time limit for the message to appear. So that after few seconds it deletes automatically!! In the picture below after creating a project and saving it there is a success message which says "The project 'xyzproject' was added successfully". But this message remains on the page until I refresh the page. so can anyone tell me if its possible to add a time limit for the message to appear and disappear without refreshing the page. -
decoding a list from a channels.http.AsgiRequest
I have a docker container which sends data_dict, a dictionary {'dome_temp": 15.5C, 'humidity":71%} using the requests library https://requests.readthedocs.io/en/latest/user/quickstart/ with the following code response = requests.post(dome_control_target, data=data_dict) It is received in another container running django via a daphne server. It is received in a channels consumer with this code: def receive_temperhum_data(request): logger.info(f"message received from temperhum {request.data}") return HttpResponse("temperhum data received") request.data returns the error 'AsgiRequest' object has no attribute 'data' So does request.message Request is type: 'channels.http.AsgiRequest' and has the plain text of <AsgiRequest: GET '/dome_control/temperhum/?dome_temp=15.5C&humidity=71%25'> I want to process this data in the consumer. I suppose I could just parse the text, but does anyone know how I can extract the data as a dictionary ? Thank you -
Context not showing Context variable in Template
Hellooo, I am trying to add a feature to my admin where I can download order details from a PDF file, which has gone successful so far except that only one Model is showing which is Order.Model while there is another one called OrderItems which are the items inside the Model not showing. I am not sure how to add another context for the OrderItem to appear in the PDF.html Here is the models.py class Item(models.Model): title = models.CharField(max_length=100) description = models.TextField() price = models.FloatField() class OrderItem(models.Model): item = models.ForeignKey(Item, on_delete=models.CASCADE) class Order(models.Model): items = models.ManyToManyField(OrderItem) Here is the views.py @staff_member_required def admin_order_pdf(request, order_id): order = get_object_or_404(Order, id=order_id) html = render_to_string('pdf.html', {'order': order}) response = HttpResponse(content_type='application/pdf') response['Content-Disposition'] = 'filename="order_{}.pdf"'.format(Order.id) weasyprint.HTML(string=html).write_pdf(response) return response here is the url.py path('admin/order/(<order_id>\d+)/pdf/', views.admin_order_pdf, name='admin_order_pdf') Here is the pdf.html template which is only showing as highlighted {% for order_item in order.items.all %} {{ order_item.item.title }} <----------Not Showing {% endfor %} -
RuntimeError: Never call result.get() within a task
My task (check payment status in Sberbank. If no capture - retry check): from ....celeryconf import app from . import client as sberbank from ...models import Payment, Transaction @app.task(bind=True, default_retry_delay=60, time_limit=1200) def check_status_sberbank_task(self, order_id, connection_params): sberbank_client = sberbank.Client(auth=(connection_params['login'], connection_params['password']), sandbox=connection_params['sandbox_mode']) response = sberbank_client.payment.get_status(order_id=order_id) txn = Transaction.objects.get(token=order_id) if response['actionCode'] == 0: txn.is_success = True txn.save() payment = Payment.objects.get(pk=txn.payment_id) payment.charge_status = 'fully-charged' payment.captured_amount = payment.total payment.save() return 'Success pay on Sberbank for ' + str(order_id) else: self.retry(countdown=60) in log file I have: ERROR celery.app.trace Task saleor.payment.gateways.sberbank.tasks.check_status_sberbank_task[bb384815-4a5b-49d7-bc29-114707f072b1] raised unexpected: RuntimeError('Never call result.get() within a task!\nSee http://docs.celeryq.org/en/latest/userguide/tasks.html#task-synchronous-subtasks\n',) [PID:26869:Thread-825] Traceback (most recent call last): File "/home/korolev/saleor/lib/python3.6/site-packages/celery/app/trace.py", line 385, in trace_task R = retval = fun(*args, **kwargs) File "/home/korolev/saleor/saleor/payment/gateways/sberbank/tasks.py", line 26, in check_status_sberbank_task self.retry(countdown=60) File "/home/korolev/saleor/lib/python3.6/site-packages/celery/app/task.py", line 715, in retry S.apply().get() File "/home/korolev/saleor/lib/python3.6/site-packages/celery/result.py", line 1015, in get assert_will_not_block() File "/home/korolev/saleor/lib/python3.6/site-packages/celery/result.py", line 41, in assert_will_not_block raise RuntimeError(E_WOULDBLOCK) RuntimeError: Never call result.get() within a task! See http://docs.celeryq.org/en/latest/userguide/tasks.html#task-synchronous-subtasks How do I fix this error?