Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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() } -
Django restframework serializer with joining tables
I'm creating a django API for a discord bot for sounds recorded management. Here are my models (simplified) : class Member(models.Model): name = models.CharField("Discord Name", max_length=100, unique=True) discord_id = models.BigIntegerField("Discord ID", unique=True, blank=True, null=True) class Sound(models.Model): id = models.AutoField("Sound ID", primary_key=True) file = models.FileField("Sound", upload_to='sounds/') added_by = models.ForeignKey(Member, verbose_name="Author", on_delete=models.SET_NULL, blank=True, null=True) tags = TaggableManager("Tags", blank=True) class MemberinSound(models.Model): sound = models.ForeignKey(Sound, on_delete=models.CASCADE, related_name="membersinsound") personality = models.ForeignKey(Member, related_name='membersinsound', on_delete=models.CASCADE) Explanations : a sound is uploaded by any member (added_by), with multiples optional tags, and personality that appears in this sound (MemberinSound). You can imagine this 3 tables like (player, match, and playersinmatch). My view to get a specific sound is : class SpecificSound(APIView): def get(self, request, id: int, formate=None, **kwargs): sound = Sound.objects.select_related().get(id=id) membersinsound = sound.membersinsound.all() serializer = SoundSerializer(sound, many=False) return Response(serializer.data) And serializers.py : class MemberInSoundSerializer(serializers.ModelSerializer): class Meta: model = MemberinSound fields = [ 'personality' ] class SoundSerializer(serializers.ModelSerializer): personality = MemberInSoundSerializer(many=True, read_only=True) class Meta: model = Sound fields = [ 'id', 'title', 'volume', 'file', 'stream_friendly', 'is_active', 'personality', ] def to_representation(self, instance): representation = super().to_representation(instance) representation['path'] = instance.file.path return representation First problem I got is in my view where I send to my serializer only Sound model (without MemberinSound), I don't … -
Djnago Form getting Error while edit record
I am getting Issue while edit a record based on CHatquestion ID, if option is null then i need to add a record based on same chatquestion id, if chatqustion id exist in option it will work, i am trying to multiple way to solve this issue but still can't find solution. Models.py # thease are all 3 models class Problem(models.Model): Language = models.IntegerField(choices=Language_CHOICE, default=1) type = models.CharField(max_length=500, null=True, blank=True) def __str__(self): return self.type class ChatQuestion(models.Model): # Eding record based on chatquestion id question = RichTextField(null=True, blank=True) problem_id = models.ForeignKey( Problem, models.CASCADE, verbose_name='Problem', ) sub_problem_id = models.ForeignKey( SubProblem, models.CASCADE, verbose_name='Sub Problem', null=True, blank=True ) def __str__(self): return self.question is_first_question = models.BooleanField(default=False) class Option(models.Model): option_type = models.CharField(max_length=250, null=True, blank=True) question_id = models.ForeignKey( ChatQuestion, models.CASCADE, verbose_name='Question', null=True, blank=True ) problem=models.ForeignKey( Problem, models.CASCADE, verbose_name='Problem', null=True, blank=True ) next_question_id = models.ForeignKey(ChatQuestion, on_delete=models.CASCADE, null=True, blank=True, related_name='next_question') def __str__(self): return self.option_type forms.py class EditQuestionForm(forms.ModelForm): class Meta: model = ChatQuestion fields =('question','problem_id') class EditOptionForm(forms.ModelForm): class Meta: model = Option fields =('option_type',) views.py def question_edit(request,id=None): if id is not None: queryset = get_object_or_404(ChatQuestion,pk=id) queryset1=get_object_or_404(Option,question_id=queryset ) else: queryset = None queryset1 = None if request.method=="POST": form = EditQuestionForm(request.POST ,instance=queryset) form1=EditOptionForm(request.POST, instance=queryset1) if form.is_valid() and form1.is_valid(): question=form.cleaned_data['question'] option_type=form1.cleaned_data['option_type'] if id: … -
Out of range value issue while migrating django's default contenttypes
When I run python manage.py migrate I am getting this error - django.db.utils.DataError: (1264, "Out of range value for column 'id' at row 1") The file at which the error is being thrown is this - import django.contrib.contenttypes.models from django.db import migrations, models class Migration(migrations.Migration): dependencies = [ ] operations = [ migrations.CreateModel( name='ContentType', fields=[ ('id', models.AutoField(verbose_name='ID', serialize=False, auto_created=True, primary_key=True)), ('name', models.CharField(max_length=100)), ('app_label', models.CharField(max_length=100)), ('model', models.CharField(max_length=100, verbose_name='python model class name')), ], options={ 'ordering': ('name',), 'db_table': 'django_content_type', 'verbose_name': 'content type', 'verbose_name_plural': 'content types', }, bases=(models.Model,), managers=[ ('objects', django.contrib.contenttypes.models.ContentTypeManager()), ], ), migrations.AlterUniqueTogether( name='contenttype', unique_together={('app_label', 'model')}, ), ] I haven't written this file. It is being generated by Django itself. I am using MYSQL 5.7 as a database.