Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
django 'dict' object has no attribute 'job_id'
I've got this code: def create_full_data_spb(contains_name: str, language="cs", system=False) -> tuple: full_data = [] labels = [] data_pass = [] data_fail = [] data_skip = [] data_duration = [] data_estimated_duration = [] if not system: queryset = BuildRunMultiJob.objects.select_related("job_id") \ .filter(job_id__full_display_name__contains=contains_name) \ .filter(language=language) \ .values('job_id', 'job_id__pass_count', 'job_id__fail_count', 'job_id__skip_count') \ .order_by('-job_id__timestamp')[:10] for i in queryset: labels.append(str(i.job_id)) data_pass.append(i.pass_count) data_fail.append(i.fail_count) data_skip.append(i.skip_count) # stop using mili mili = int(i.estimated_duration) temp = datetime.datetime.fromtimestamp(mili / 1000).strftime('%H:%M:%S') data_estimated_duration.append(temp) mili = int(i.duration) temp = datetime.datetime.fromtimestamp(mili / 1000).strftime('%H:%M:%S') data_duration.append(temp) full_data.append([i.job_id, i.pass_count, i.skip_count, i.fail_count, temp]) return labels, data_pass, data_fail, data_skip, data_duration, data_estimated_duration, full_data Even though value() is defined, I get the error 'dict' object has no attribute 'job_id' I guess the error will also be for pass_count, skip_count and fail_count What am I supposed to do here? -
How to get linkedin access token with django python?
I am working on an django (python) application that needs that access token from Linkedin API. I tried the following library social-auth-app-django but it didn't help me because I do not need only to sign in, I want to store that access token in the below database to use the token in the future features of the app and I am not sure how to print it or get it from social-auth-app-django. ---------------------------------------- id | username | password | LinkedinToken ---------------------------------------- -
Application Error on Heroku (Django Web-App)
I am trying to deploy my Django web-app on Heroku. Build succeeds but still I get an Application Error. Below are my app's logs. Logs: 2022-03-04T12:47:48.701018+00:00 app[web.1]: File "<frozen importlib._bootstrap>", line 984, in _find_and_load_unlocked 2022-03-04T12:47:48.701018+00:00 app[web.1]: ModuleNotFoundError: No module named 'SASTRAScrapper' 2022-03-04T12:47:48.701025+00:00 app[web.1]: [2022-03-04 12:47:48 +0000] [9] [INFO] Worker exiting (pid: 9) 2022-03-04T12:47:48.745701+00:00 app[web.1]: [2022-03-04 12:47:48 +0000] [4] [WARNING] Worker with pid 9 was terminated due to signal 15 2022-03-04T12:47:48.841738+00:00 app[web.1]: [2022-03-04 12:47:48 +0000] [4] [INFO] Shutting down: Master 2022-03-04T12:47:48.841740+00:00 app[web.1]: [2022-03-04 12:47:48 +0000] [4] [INFO] Reason: Worker failed to boot. 2022-03-04T12:47:49.032701+00:00 heroku[web.1]: Process exited with status 3 2022-03-04T12:47:49.097253+00:00 heroku[web.1]: State changed from up to crashed 2022-03-04T12:48:02.499473+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sastra-scraper.herokuapp.com request_id=f5454869-83fe-41bc-a081-a0b11b419ad1 fwd="122.161.254.213" dyno= connect= service= status=503 bytes= protocol=https 2022-03-04T12:48:03.140143+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sastra-scraper.herokuapp.com request_id=8e31ba10-6112-41f6-b8f8-6c58e86acb4a fwd="122.161.254.213" dyno= connect= service= status=503 bytes= protocol=https 2022-03-04T12:49:00.300756+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sastra-scraper.herokuapp.com request_id=e0c472d9-2ce4-4c99-9048-87e95a834255 fwd="122.161.254.213" dyno= connect= service= status=503 bytes= protocol=https 2022-03-04T12:49:00.916514+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sastra-scraper.herokuapp.com request_id=f4a4d43f-aa19-4784-9602-f897e2a71238 fwd="122.161.254.213" dyno= connect= service= status=503 bytes= protocol=https 2022-03-04T12:49:04.938317+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/" host=sastra-scraper.herokuapp.com request_id=8e3167e6-c97e-42e7-8fe0-1e2a5136acc4 fwd="122.161.254.213" dyno= connect= service= status=503 bytes= protocol=https 2022-03-04T12:49:05.403850+00:00 heroku[router]: at=error code=H10 desc="App crashed" method=GET path="/favicon.ico" host=sastra-scraper.herokuapp.com … -
How to get rid of the first comma in Python
tags = ProductInStore.objects.get(id=product_in_store_id).product.tags.values_list('name', flat=True) converted_list = list(tags) tags_string = '' for tags in converted_list: tags_string += ',' + tags return tags_string The output is ,tag1,tag2,tag3,tag4,tag5 but i'd like to get rid of the first comma. Do you have any idea how to do it? -
Multiple many-to-many relations through the same model in Django problem
i have a problem i don't know how to make multiple many-to-many relations through the same model. This is my DB relations : Db architecture and this is my code, i want to know if what I did is right or not ? class Projects(models.Model): Project_name = models.CharField(max_length=50) Poject_key = models.CharField(max_length=50) CITools = models.ForeignKey(CITools,null=True,on_delete=models.CASCADE) UsersO = models.ManyToManyField(User,through='OwnerShips') # for user Ownerships UserF = models.ManyToManyField(User,through='Favorites') # for user Favorites This is my OwnerSHips class : class OwnerShips(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) project = models.ForeignKey(Projects,on_delete=models.CASCADE) And this is my Favorites Class: class Favorites(models.Model): user = models.ForeignKey(User,on_delete=models.CASCADE) project = models.ForeignKey(Projects,on_delete=models.CASCADE) -
how to solve No 'Access-Control-Allow-Origin' while creating new endpoints with terraform cloudfront and django
I have created an application using django react, terrafor, aws cloudfront and nginx all my endpoints that i have been working on for weeks work well. Now i have tried to add new endpoints when i try to make a request from the front end, i get the following errors: Access to XMLHttpRequest at 'https: //api.foo.com/new-url-enpoints/' from origin 'https: //www.foo.com' has been blocked by CORS policy: No 'Access-Control-Allow-Origin' header is present on the requested resource. main.a1abe898.chunk.js:1 Page error: Error: Network Error at e.exports (1.v3s1s213.chunk.js:1:21345) at XMLHttpRequest.p.onerror (1.v3s1s213.chunk.js:1:63362) 1.v3s1s213.chunk.js:1 POST https: //api.foo.com/new-url-enpoints/ net::ERR_FAILED 500 S3 bucket resource "aws_s3_bucket" "my_bucket" { bucket = "some-bucket" ... cors_rule { allowed_headers = [ "Accept", "Accept-Encoding", "Authorization", "Content-Type", "Dnt", "Origin", "User-Agent", "X-Csrftoken", "X-Requested-With", ] allowed_methods = ["PUT", "POST", "GET", "DELETE", "HEAD"] allowed_origins = ["https: //www.foo.com"] # i have created the space to be able to post this question on stackoverflow expose_headers = ["Etag"] max_age_seconds = 3000 } FRONTEND locals { s3_origin_id = "www.foo.com" } resource "aws_cloudfront_distribution" "front_end_cloudfront" { origin { domain_name = aws_s3_bucket.my_bucket.bucket_regional_domain_name origin_id = local.s3_origin_id s3_origin_config { origin_access_identity = "${aws_cloudfront_origin_access_identity.s3_oai.cloudfront_access_identity_path}" } } enabled = true is_ipv6_enabled = true default_root_object = "index.html" aliases = ["www.foo.com"] custom_error_response { error_caching_min_ttl = 500 error_code = 403 response_code = 403 … -
CSS doesnt link to HTML in django
I am watching beginner course on django . So basically i am running server from cmd and when i want to change anything on css file it doesnt change live . STATIC_URL = '/static/' STATICFILES_DIRS = (os.path.join(BASE_DIR, 'static'),) my html : {% load static %} <link type = "text/css" href="{% static 'style.css' %}" rel="stylesheet"> <h1>Hi welcome to my page </h1> -
How to use refresh token in request header?
I have a Django project. In this project I am using an API. I get data from this API with python requests. When I am using "access token" for request header it works but in the end of several time it logouts, so I want to use "refresh_token" instead of access_token. How can I do that? credit = requests.get(settings.API_ADDRESS + "analyze/scoring/" + id, headers={'Authorization': settings.API_TOKEN}) ... API_ADDRESS = "https://api.myaddress.com/" API_TOKEN = "Bearer <access_token>" -
My Django View is Not Sending Response to AJAX
I have an ajax script used to make a POST request on-page. function update_button() { console.log(mediaArray) alert(mediaArray) $.ajaxSetup({ headers: { "X-CSRFToken": getCookie("csrftoken") }, }); $.ajax({ type:"POST", url: "{% url 'ajaxres' %}", data: {"image":String(mediaArray)}, dataType: 'json', success: function (data) { alert(data) // do something with response window.location.replace("{% url 'posts' %}") }, }, ); } Which is successfully sending its data but reloading the page and in views, I am sending a JSON response back to ajax: return JsonResponse('Done!', safe=False) But the success function doesn't work -
Reactnative Request failed with status code 400
i trying to build an finance management application, React Native as Frontend and Django as Backend, i use axios to take data from user then send it to backend it show error Request failed with status code 400 the user enter the data through form and send it to the backend , i have used Restful API that build with django and run the server locally import * as React from "react"; import {View, Text, Image, StyleSheet, Button, TextInput} from "react-native"; import { COLORS, SIZES,FONTS} from '../styles/theme.js'; import { FieldArray, Formik} from "formik"; import axios from 'axios'; const AddScreen =()=>{ const radioopt = [{},{},{},{}]; const submit = (val) => { if(val.type == "" || val.category == "" || val.amount == ""){ alert("Please Enter all details"); return; } // 'http://192.168.8.143:8000/transactions/' axios.post('http://192.168.8.143:8000/transactions/', { "id": "1", "type": val?.type, "category": val.category, "amount": val?.amount, // "owner" : "", "date" : Date.now(), }) .then(function (response) { console.log(response); }) .catch(function (error) { console.log(error); }); } return( <View style={{flex: 1, backgroundColor:COLORS.gray}}> <Formik initialValues={{type:'',category:'', amount:''}} onSubmit={(values)=>{submit(values)}} > {(props)=>( <View style={styles.whitecard}> <TextInput style={styles.inputstyle} placeholder='type' onChangeText={props.handleChange('type')} value={props.values.type} /> <TextInput style={styles.inputstyle} placeholder='category' onChangeText={props.handleChange('category')} value={props.values.category} /> <TextInput style={styles.inputstyle} placeholder='amount' onChangeText={props.handleChange('amount')} value={props.values.amount} keyboardType='numeric' /> <View style={{margin:10,padding:0, backgroundColor:COLORS.pink, borderRadius:6}}> <Button title='Submit' color='white' onPress={props.handleSubmit}></Button> </View> </View> … -
DRF: OneToOne relation with unique_together
I am trying to understand how to use a OnetoOne relation with unique_together. Currently trying to make use of them in my serializer and view with no success. Models: class Employees(models.Model): name = models.CharField() position = models.CharField() phone = models.IntegerField() class WorkSchedule(models.Model): employee = models.OneToOneField('Employees') workday = models.DateTimeField() class Meta: unique_together = (('employee', 'workday'),) First question: Since the relation is OneToOne if i didn't have unique_together then each employee could appear in WorkSchedule once. However since i have unique_together this is not the case anymore. Correct? Second Question: How would i use such models to return all employees and their workschedules like this { "employees": [ { "employee": "John", "workschedule": [ { workday: "2022-03-03" }, { workday: "2022-03-04" } }, { "employee": "Tom", "workschedule": [ { workday: "2022-03-03" }, { workday: "2022-03-04" } } } I was able to do this with using a ForeignKey(no unique_together) and a Nested Serializer however i wasn't able to do it with using the two models as they are above. -
Django verify auth from request
I am interested in having the user send a request in this fashion, using requests: import requests url = "https://postman-echo.com/basic-auth" username = "postman" password = "password" response = requests.get(url, auth=(username, password)) Then in my Django model I need to be able to verify that those auth credentials are matching with the right user. I cannot access request.auth and there are no auth fields in request.META. What is the right way to access those credentials form the Django side? -
Django select for update behavior in test
In trying to understand django's select_for_update, I created a test to see. In my understanding, if there are two processes, one selects for update inside transaction, the other tries to write to the locked rows before transaction ends in other process, the write would fail. However, the following test passes ok. What could be wrong? @pytest.mark.django_db(transaction=True, databases=MULTIPLE_DATABASES) def test_select_for_update(): ExampleModel.objects.create(type="test1") ExampleModel.objects.create(type="test2") import os child_pid = os.fork() if child_pid == 0: sleep(5) qs = ExampleModel.objects.all() ExampleModel.objects.bulk_update(qs, ["type"]) else: with transaction.atomic(): qs = ExampleModel.objects.all().select_for_update() for obj in qs: obj.type = "test3" ExampleModel.objects.bulk_update(qs, ["type"]) sleep(10) -
IntegrityError - NOT NULL constraint failed
def teachertests(request): form = InitialForm() if request.method == "POST": form = InitialForm(request.POST) if form.is_valid(): data_form = form.cleaned_data question = Questions() question.test_label = data_form.get('Test_Name') question.Q1 = data_form.get('Q1') question.Topic1 = data_form.get('Topic1') question.Option1_Q = data_form.get('Option1_Q') question.Option1_Q = data_form.get('Option2_Q') question.Option1_Q = data_form.get('Option3_Q') question.Option1_Q = data_form.get('Option4_Q') question.save() return render(request, 'teachertests.html', {'form':form}) Hey, sorry if this is a simple issue, new to Django and any development like this. When doing this, it gives me the error: IntegrityError at /teacher/tests NOT NULL constraint failed: main_questions.Q1 Anyone able to help me out? Willing to provide any information you would like. -
Which framework to choose for building a web application in python to do data science? [closed]
I am currently a developer in a company that is specialized in predictive maintenance. I have developed a lot of algorithms for decision support. I would like to make these algorithms available to users to whom I provide access (loggin by email and password which are stored in a postgres database) I am looking for a python framework to develop a web application where the user can choose a solution in which he can upload a file in CSV format. The back-end will mainly collect the file and perform a processing on it then return results in the form of text and graphics. I mainly use the library pandas, numpy, tensorflow, keras, matplot, seaborn, plotly. I found the following python framework for web application development. Streamlit, Django, Flask. Which framework would you recommend for the development of python web application to perform data science type processing as mentioned above ? I thank you in advance for your answers. -
django FilterView shows duplicated filter in template
I've got problem with showing filters in my template. I have view in views.py as follows: class SearchDocView(FilterView): template_name = 'searchdoc.html' context_object_name = 'founddocs' filterset_class = FilterDoc paginate_by = 5 def get_queryset(self): queryset = super(SearchDocView, self).get_queryset() queryset = FilterDoc(self.request.GET, queryset) return queryset I've created my own filter in filters.py: class FilterDoc(django_filters.FilterSet): usr_choices=( ('foo.user', 'foo.user'), ('test.user','test.user'), ) class Meta: model=Doc fields = ['doc_application_id','doc_client_nip','user_id'] appid = django_filters.CharFilter(field_name='doc_application_id',lookup_expr='icontains') nip = django_filters.CharFilter(field_name='doc_client_nip',lookup_expr='icontains') usrid = django_filters.MultipleChoiceFilter(field_name='user_id', choices=usr_choices) amd my template is: <body> <form method="get"> {{ filter.form.as_p }} <button type="submit">Search</button> </form> {% if founddocs %} <table> <thead> <tr> <td>DOC APPLICATION ID</td> ... </tr> </thead> <tbody> <tr> {% for doc in founddocs %}{#WZORZEC NAZWA MODELU + '_list'#} <td>{{ doc.doc_application_id }}</td> ... </tr> {% endfor %} </tbody> </table> {% else %} <p>Nothing to see here!.</p> {% endif %} </body> Filters works perfectly. The problem is every time I load the page I see duplicated filter fields. Like this: Why is that? How can I drop duplicates. Why user have two different widgets. The second one (combobox) is related with id not username. When I try choose something I got "Field 'id' expected a number but got 'test.user'" -
Writing files on heroku dyno filesystem to be used later?
I know the heroku filesystem is ephemeral. The files I'm writing are captchas, mp3s, and other images that only need to be in the file system for a few minutes. But I can't get anything to work right. For the captchas, here's the code: def new(request): r = redis.Redis(host='localhost', port=6379, db=0) image = ImageCaptcha() alphanum_str = '0123456789ABCDEF' captcha_answer = ''.join( random.choice(alphanum_str) for i in range(5)) timestamp = str(datetime.now().timestamp()) image.write(captcha_answer, os.path.join( settings.BASE_DIR, f'hendrixia/static/captchas/{timestamp}.png')) context = { 'captcha_timestamp': timestamp } r.set(f'id-{timestamp}', captcha_answer) r.expire(f'id-{timestamp}', 300) template_name = 'the_axis/new.html' return render(request, template_name, context) The problem is at the image.write() line. It's using this package: https://github.com/lepture/captcha I've tried hendrixia/staticfiles/captchas, hendrixia/media/captchas, staticfiles/captchas, temp_captchas/ and others. And yes, I did make sure that those directories existed at the heroku dyno (I placed an empty a.txt in each). Can anyone help with this? -
Can we create a table in django without models class?
I need to dynamically create database tables depending on user requirements. so apart from a few predefined databases, all other databases should be created at runtime after taking table characteristics(like no of cols, primary key etc.) from user. I read a bit of docs, and know about django.db.connection but all examples there are only for adding data to a database, not creating tables. (ref: https://docs.djangoproject.com/en/4.0/topics/db/sql/#executing-custom-sql-directly) So is there anyway to create tables without models in django, this condition is a must, so if not possible with django, which other framework should I look at? note: I am not good at writing questions, ask if any other info is needed. Thanks! -
Do weed something to sync elasticsearch dsl to postgres databse
Actually we are deploying elasticsearch django application in aws ec2.Here, i need to know something about elasticsearch. Will elasticearch automatically updates with the update in postgres or do we need to use extra modules to sync elasticsearch and postgres together so that whatever changes happens in postgres database, it will also update in elasticsearch. -
How to get a variable from response.body Python
I have this function that should get me a value for key "product" in my api response The response has "product": 59, def _get_product_id(self, data): if isinstance(data, bytes): data = data.decode(errors='replace') if isinstance(data, list): return [self._clean_data(d) for d in data] if isinstance(data, dict): data = dict(data) product_id = data['product'] return product_id i call it like this 'product_id': self._get_product_id(request.body) But when i run this, i get an error that it gives me null value when trying to add it into database. django.db.utils.IntegrityError: null value in column "product_id" of relation "analytics_logs" violates not-null constraint Do you have any idea how to get this value as an integer? -
Django HTML Template Image Carousel Slider Touch Enabled
I am making a Blog website. I am using django template to view the posts. I have a page where I show all the posts and each post contains multiple images. I want to show an image carousel for each post with touch enabled for mobile devices. I am unable to find any relevant resources for this. can some one help me out. I am using forloop to iterate over the different posts and then inside the loop I am iterating over the Images queryset to display different images for each post. I am trying to use the bootstrap carousel but I am having difficulty. Please help me out as I am not very good with the designing part. The resources that I have referred to are -> 1. https://codepen.io/bushblade/pen/ZEpvzbK 2. Bootstrap website Thanks in advance. -
How to upload file on Django REST endpoint quickly?
I am using Django REST framework to upload a large csv file and extract the data from the file and save the data in the data. By large file I mean file of like 10 to 50mb but when I upload a file its taking way longer then expected like 10 to 15mins but the endpoint keeps on processing and does not returns the response here is how my views.py looks like: from asyncore import read from django.shortcuts import render from rest_framework.views import APIView from rest_framework.decorators import api_view from rest_framework.parsers import MultiPartParser, FormParser from rest_framework.response import Response import pandas as pd from .models import ExtractedData from .urls import urlpatterns from django.urls import path # Create your views here. class FileUploadView(APIView): parser_classes = ( MultiPartParser, FormParser) def put(self, request, format=None): file_obj = request.FILES['file'] df = pd.read_csv(file_obj) dict_data = df.to_dict(orient='records') for dict in dict_data: ExtractedData.objects.get_or_create(data=dict) return Response({'details':"File Saved Succesfully"}, status=204) -
unable to pass image value with other form value through AJAX
I am trying to pass form values to views.py in django using AJAX. My form contains 1 image field with other fields. Here my problem is when use $(this).serialize() to save input values to a variable.It doesn't takes image field value. It pass only other field values. how can i pass image field value with other form values? I tried append method. append method is not working here.. var serializedData = $(this).serialize(); //var image = $('#id_image')[0].files[0]; //serializedData.append('image', image); $.ajax({ type: 'POST', url: "{% url 'create' %}", data: serializedData, }, -
django reverse foreignkey in template
Hej! I have multiple connected models and want to display the info via a template. All models are connected via foreignkeys, but I only can display the info in one direction. Does anyone know how to reverse to show both ways? I can easily get the information of 'Survey' and 'Certification' but can't get to 'SurveyBga' and 'Address'. Any help is appreciated! :) # models.py class Survey(models.Model): survey_bga_id = models.ForeignKey( SurveyBga, on_delete=models.PROTECT, related_name="experiment" ) year = models.PositiveSmallIntegerField( validators=[validate_year] ) class Certification(models.Model): survey_bga_yeardependent_id = models.ForeignKey( Survey, on_delete=models.PROTECT, related_name="certification" ) type_of_experience = models.BooleanField( blank=True, null = True ) class Address(models.Model): street = models.CharField( max_length = 150, blank = True, ) class SurveyBga(Address): internal_id = models.CharField( unique = True, max_length = 10 ) # views.py def experiment_bga_view(request): bga = Survey.objects.all() context = {"bga": bga} return render(request, 'app/template.html', context) I tried {% for survey in bga %} {% for plant in survey.experiment_set.all %} {{plant.internal_id}} {% endfor %} {% endfor %} {% for survey in bga %} {% for plant in survey.experiment.all %} {{plant.internal_id}} {% endfor %} {% endfor %} {% for survey in bga %} {{survey.experiment.internal_id}} {% endfor %} -
Radio button - Javascript runs if True, but not if False
With the following code, the elements get shown when the radio button is clicked, but don't get hidden, when the radio button is unselected. I have no idea why... // Show an element var show = function (elem) { elem.style.display = ''; }; // Hide an element var hide = function (elem) { elem.style.display = 'none'; }; var displayLogicStudentLoanPaymentMethod = function(){ if (studentLoanPaymentPayrollRadioButton.checked == true) { show(completedStudiesContainer); show(studentLoanPlansContainer); return; } if (studentLoanPaymentPayrollRadioButton.checked == false) { hide(completedStudiesContainer); hide(studentLoanPlansContainer); return; } displayLogicStudentLoanPaymentMethod(); studentLoanPaymentPayrollRadioButton.addEventListener('change', studentLoanPaymentPayrollRadioButtonListener); function studentLoanPaymentPayrollRadioButtonListener(){ displayLogicStudentLoanPaymentMethod() }