Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to add a user-filtered button in Django
I have a Base.html template that extends to the rest of my HTML pages in my app, In this base.html file, it has a nav-bar that has a bunch of < a > tags that link to the different pages. Is it possible to limit the visibility of this < a > tag based on a user's name or users role on the database or would I need to add this in the function of rendering the page to which the < a > tag loads? -
Django template dictsort not ordering correctly when spanish language
Currently I have a countrie's dict COUNTRIES = { "countries": [ { "name_en": "Afghanistan", "name_es": "Afganistán", "dial_code": "+93", "code": "AF" }, { "name_en": "Albania", "name_es": "Albania", "dial_code": "+355", "code": "AL" }, { "name_en": "Algeria", "name_es": "Argelia", "dial_code": "+213", "code": "DZ" }, { "name_en": "AmericanSamoa", "name_es": "Samoa Americana", "dial_code": "+1684", "code": "AS" }, { "name_en": "Andorra", "name_es": "Andorra", "dial_code": "+376", "code": "AD" }, { "name_en": "Angola", "name_es": "Angola", "dial_code": "+244", "code": "AO" }, { "name_en": "Anguilla", "name_es": "Anguilla", "dial_code": "+1264", "code": "AI" }, { "name_en": "Antarctica", "name_es": "Antártida", "dial_code": "+672", "code": "AQ" }, { "name_en": "Antigua and Barbuda", "name_es": "Antigua y Barbuda", "dial_code": "+1268", "code": "AG" }, { "name_en": "Argentina", "name_es": "Argentina", "dial_code": "+54", "code": "AR" }, { "name_en": "Armenia", "name_es": "Armenia", "dial_code": "+374", "code": "AM" }, { "name_en": "Aruba", "name_es": "Aruba", "dial_code": "+297", "code": "AW" }, { "name_en": "Australia", "name_es": "Australia", "dial_code": "+61", "code": "AU" }, { "name_en": "Austria", "name_es": "Austria", "dial_code": "+43", "code": "AT" }, { "name_en": "Azerbaijan", "name_es": "Azerbaiyán", "dial_code": "+994", "code": "AZ" }, { "name_en": "Bahamas", "name_es": "Bahamas", "dial_code": "+1242", "code": "BS" }, { "name_en": "Bahrain", "name_es": "Baréin", "dial_code": "+973", "code": "BH" }, { "name_en": "Bangladesh", "name_es": "Banglades", "dial_code": "+880", "code": "BD" }, { "name_en": "Barbados", "name_es": … -
ImportError: cannot import name 'Affiliate' from partially initialized module 'affiliate.models' (most likely due to a circular import)
I'm getting a circular import error in django and can't seem to solve it. here's my models.py in affiliate(app) from member.models import Member class SubAffiliate(models.Model): member_id = models.ForeignKey(Member, on_delete=models.CASCADE) and here's my models.py in member(app) from affiliate.models import Affiliate class Member(models.Model): affiliates = models.ManyToManyField(Affiliate, blank=True, related_name="members_affiliate") for solving the problem I tried importing like this import affiliate.models and there use it like this affiliate.models.Affiliate then I get this error AttributeError: module 'affiliate' has no attribute 'models' what should I do to resolve this error. Thank You! -
"TypeError: cannot unpack non-iterable AsyncResult object" while using Django?
I'm using Django with Celery to make an async call that returns multiple values. However, when trying to unpack these variables in my Django view, it throws up the TypeError mentioned above. Here's what I have so far: Relevant Code views.py def render_data(request): reddit_url = request.POST.get('reddit_url') sort = request.POST.get('sort') var1, var2 = celery_run.delay(reddit_url, sort) data = { 'var1': var1, 'var2': var2, } return JsonResponse(data) tasks.py @shared_task def celery_run(reddit_url, sort): var1, var2 = run_data(reddit_url, sort) return var1, var2 Expected Result vs Actual Ideally, the function would properly unpack and each variable would be assigned to the proper value from the function. Instead, I receive a typeerror indicating that I can't unpack async objects. I'm not entirely sure, but is that because I'm trying to unpack from a function thats still running? What I've tried Unpacking variables within tasks.py instead in views.py, did absolutely nothing but I prayed Followed the solution from TypeError: cannot unpack non-iterable NoneType object but unfortunately extra indents makes my code work less If I could get any info on what causes this error and the best method to approach this, I'd be grateful. Thanks! -
Use Verbatim tag inside a django simple tag
I wrote a simple tag that gets one argument and returns True or False. @register.simple_tag def iswatched(movieDB_id): try: movie = TitleMovie.objects.get(movieDB_id=movieDB_id) return movie.watched except: return False I use a javaScript library called Handlebars which has syntax exactly like Django template tag. So I use {%verbatim%} tag to not render those parts. but I need to get the value with Handlebars tag like this ( {{value}} ) and pass it to simple tag {%iswatched {{value}} as watched%}. but it gets an error because it render {{value}} as Django template tag. I tried this but it didn't work. {%iswatched ({%verbatim%}{{id}}{%endverbatim%}) as watched%} how should i have it not render {{value}} inside iswatched simple tag -
How to add a background image to my reactjs django project?
import React, {Component} from "react"; import CreateRoomPage from "./CreateRoomPage"; import RoomJoinPage from "./RoomJoinPage"; import Room from "./Room"; import { Grid, Button, ButtonGroup, Typography } from "@material-ui/core"; import {BrowserRouter as Router, Switch, Route, Link, Redirect} from "react-router-dom"; import Info from "./info"; import "../images/xonebg.jpeg"; export default class HomePage extends Component { constructor(props) { super(props); this.state = { roomCode: null, }; this.clearRoomCode = this.clearRoomCode.bind(this); } async componentDidMount(){ fetch("/api/user-in-room").then((response) => response.json()).then((data) => { this.setState({ roomCode: data.code }); }); } I suppose needed code should be in renderHomePage() function. I add few things like div and ımage elements. When i added right below the return it caused a problem. renderHomePage(){ return( <Grid container spacing={3}> <Grid item xs={12} align="center"> <Typography variant = "h3" compact="h3"> Xone Music </Typography> </Grid> <Grid item xs={12} align="center"> <ButtonGroup disableElevation variant="contained" color="primary"> <Button color="primary" to="/join" component={Link}> Join a Room </Button> <Button color="default" to="/info" component = {Link} > <Typography variant = "h5" compact="h5"> ? </Typography> </Button> <Button color="secondary" to="/create" component = {Link}> Create a Room </Button> </ButtonGroup> </Grid> </Grid> ); } clearRoomCode(){ this.setState({ roomCode:null }); } render(){ return ( <Router> <Switch> <Route exact path="/" render={() => { return this.state.roomCode ? (<Redirect to={`/room/${this.state.roomCode}`}/>) : (this.renderHomePage()); }}/> <Route path="/join" component={RoomJoinPage}/> <Route path="/info" component={Info}/> <Route path="/create" … -
Totals\Subtotals in Django
I'm new to django and I have a problem to get right report layout. I have a model Contract and I have certain problems getting following report layout: Bussines unit: x contractnox client1 net_price vat price contractnoy client2 net_price vat price ..... Bussines unit x subtotals: net_price, vat, price Bussines unit: y you get the point Totals in the end. My Contract model is like this: class Contract(models.Model): contract_no = models.IntegerField(verbose_name='Number:') client= models.CharField( max_length=50, verbose_name='Client:') address = models.CharField( max_length=50, verbose_name='Address:') date = models.DateField(default=timezone.now, verbose_name='Contract date:') price = models.FloatField(max_length=10,default=10.00, verbose_name='Price:') vat = models.FloatField(max_length=10,default=0.00, verbose_name='VAT:') net_price = models.FloatField(max_length=10,default=0.00, verbose_name='Net price:') canceled = models.BooleanField(default=False, verbose_name='Canceled:') business_unit=models.ForeignKey('BussinesUnit', on_delete=models.CASCADE, verbose_name='Bussines unit') I have tried this in view: b_units= BussinesUnit.objects.all() contract= Contract.objects.filter(canceled=False) data={} for unit in b_units: data[unit] = contract.filter(business_unit=unit.pk),\ contract.filter(business_unit=unit.pk).aggregate(price_sub=Sum('price')),\ contract.filter(business_unit=unit.pk).aggregate(net_price_sub=Sum('net_price')),\ contract.filter(business_unit=unit.pk).aggregate(vat_sub=Sum('vat')),\ contract.filter(business_unit=unit.pk).aggregate(items_sub=Count('contract_no')) context = { 'bussines_units': data } In report I did this: {% for data, data_items in bussines_units.items %} {{ data }} <div> <table width="100%" border="0" cellspacing="0" cellpadding="0"> <tr> <td class='detailsCenter' style="width: 5.5%">Contract</td> <td class='detailsCenter' style="width: 33%">Client</td> <td class='detailsCenter'style="width: 28.5">Adress</td> <td class='detailsRight'style="width: 11%">Net price</td> <td class='detailsRight' style="width: 11%">VAT</td> <td class='detailsRight' style="width: 11%">Price</td> </tr> {% for data in data_items%} {% for x in data%} <tr> <td class='detailsCenter' style="width: 5.5%">{{x.contract_no}}</td> <td class='details' style="width: 33%">{{x.client}}</td> <td … -
How to have dynamic data on webpage using Django models?
I have a requirement where the dropdown menu using Django models in my webpage needs to have live/dynamic data from a third party server. For eg. current models data is emp1,emp2 but if the third party server adds emp3, then I should be able to display emp1,emp2,emp3 in my webpage when a user refreshes the webpage. How can I achieve that using django models? (I know we can do this without Django models by making an ajax call directly from the webpage, but I can't do so because of security restriction so I have to fetch this data in the backend, and with Django models currently I am only able to get the data in my database once when the server is started and NOT when the third party server updates its database). -
Heroku push can't find Django 3.2.8
When pushing my git repository to heroku it fails and gives this error: remote: Compressing source files... done. remote: Building source: remote: remote: -----> Building on the Heroku-20 stack remote: -----> Using buildpack: heroku/python remote: -----> Python app detected remote: -----> No Python version was specified. Using the same version as the last build: python-3.9.7 remote: To use a different version, see: https://devcenter.heroku.com/articles/python-runtimes remote: -----> Requirements file has been changed, clearing cached dependencies remote: -----> Installing python-3.9.7 remote: -----> Installing pip 20.2.4, setuptools 57.5.0 and wheel 0.37.0 remote: -----> Installing SQLite3 remote: -----> Installing requirements with pip remote: Collecting Gunicorn==20.1.0 remote: Downloading gunicorn-20.1.0-py3-none-any.whl (79 kB) remote: Collecting Jinja2==2.11.2 remote: Downloading Jinja2-2.11.2-py2.py3-none-any.whl (125 kB) remote: Collecting Django-Heroku==0.3.1 remote: Downloading django_heroku-0.3.1-py2.py3-none-any.whl (6.2 kB) remote: ERROR: Could not find a version that satisfies the requirement Django-3.2.8 (from -r /tmp/build_43fa9180/requirements.txt (line 4)) (from versions: none) remote: ERROR: No matching distribution found for Django-3.2.8 (from -r /tmp/build_43fa9180/requirements.txt (line 4)) remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed remote: ! remote: ! ## Warning - The same version of this code has already been built: 262a4549043aa448dc2000c886cad672f979d8f0 remote: ! remote: ! We have detected that you have triggered a build from … -
How to allow only React to make an API request in my Django-React Project?
I was making a tutorial integrating Django and React to make a full-stack project, and in a part of it they configured in settings.py to allow anyone to make an api request,but it's too dangerous to allow it,everybody could wipeout my whole database or make something else with my application,and then I came with the idea to restrict to only React to do it -
How much time it should take to upload a big csv file (100MB) using Django?
I want to know how much time it should take for a scalable django app. How can I define scalable in this scenario? -
Aggregating data
I'm using django and django rest framework, trying to save a series of data from a digital device i.e sensor owned by a customer, in a PostgreSQL database. The incoming data should have this schema: i. timestamp: RFC3339 timestamp ii. reading: float iii. device_id: UUIDv4 iv. customer_id: UUIDv4 I've created a device model like this: from django.db import models from django.contrib.postgres.fields import ArrayField from customer.models import Customer import uuid class Device(models.Model): timestamp = models.DateTimeField(auto_now_add=True) reading = models.FloatField() device_id = models.UUIDField(primary_key=True) customer_id = models.ForeignKey(Customer, on_delete=models.CASCADE) def __str__(self): return str(self.device_id) and a Customer model like this: from django.db import models class Customer(models.Model): timestamp = models.DateTimeField(auto_now_add=True) customer_id = models.UUIDField(primary_key=True) def __str__(self): return str(self.customer_id) The CustomerSerializer looks like this: from rest_framework import serializers from .models import Customer from django.db.models import Avg, Max, Min, Count, Sum class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = '__all__' The DeviceSerializer looks like this: from rest_framework import serializers from .models import Customer class CustomerSerializer(serializers.ModelSerializer): class Meta: model = Customer fields = '__all__' The views.py file for Customer looks like this: from rest_framework import generics from .serializers import DeviceSerializer from .models import Device # Create a new device class CreateDevice(generics.CreateAPIView): serializer_class = DeviceSerializer # List all devices class ListDevices(generics.ListAPIView): … -
Django Pagination count increasing endlessly
I have created a Django app wherein my views.py I have the following code: a)For a POST request view- p = Paginator(bigarray, 5) page = request.POST.get('page' , 1) pagelist = p.get_page(page) a)For a GET request view- p = Paginator(bigarray, 5) page = request.GET.get('page' , 1) pagelist = p.get_page(page) The HTML page that renders this code is the follows: <ul class="pagination justify-content-center"> {% if data.has_previous %} <li class="page-item"> <a href="?page=1" class="page-link">&laquo; First</a></li> <li class="page-item"> <a class="page-link" href="?page={{ data.previous_page_number }}">Prev</a> </li> {% endif %} {% if data.has_next %} <a href="?page={{ data.next_page_number }}" class="page-link">Next</a></li> <li class="page-item"> <a class="page-link" href="?page={{ data.paginator.num_pages }}">Last &raquo;</a> </li> {% endif %} <li class="page-item disabled"> <a href= "#" class="page-link"> Currently {{data.number }} of {{data.paginator.num_pages }} pages </a> </li> </ul> The page renders this image in the link: [1]: https://i.stack.imgur.com/MBrIM.png But now if I go over to the last page, it becomes this(one extra pagination page is getting create): Currently 3 of 4 pages (Could not append the image as only one image link was being supported on this post) The contents on each of the paginated sections is just replicated. What could be the root cause of the ever increasing pagination sections? Any help would be greatly appreciated, thank … -
django - how to reset superuser passwowrd if it's lost when the app online
I'm still a biginner whith django and web development in general and I now almost nothing about deployment and how the stuff works online, I noticed that the login page on django admin panel does not contain a button or a url to reset the passowrd of the superuser if it's lost although it's possible to recreate a new one with the cmd, but I was wondering how will the user reset he's password or recreate a new superuser when the app is online ? -
Error Django The 'imagem' attribute has no file associated with it
can someone help me understand why the tag: {{ post.author.imagem }} Returns me --> perfil/imagem1.jpg and the tag {{ post.author.imagem.url }} Returns me an error: The 'imagem' attribute has no file associated with it. html {% if post.author.imagem %} <img src="{{ post.author.imagem.url }}" alt="{{ post.author.first_name }}" class="rounded-circle" style="width: 50px; height: 50px; margin-right: 20px;"> {% endif %} class Post(models.Model): author = models.ForeignKey(get_user_model(), verbose_name='author', on_delete=models.CASCADE , null=True, blank=True) -
How to get latest db record based on 2 columns in django
I have a table which have combination of foreign keys F1, F2 and a column for storing the created datetime. How can I query the latest records for the combinations of the foreign keys. These are the columns in table. ChallengeID, UserID, createdDatetime, points If a challengeID is CH1 and we have 2 users U1, U2, and there could be multiple records for that combination. for ex. CH1 and U1, there are 5 records. and out of those one is latest record based on createdDatetime. How do I get the points value from the latest records for all the users for a particular challenge using Django ORM? something like: CH1, U1 - PV1 CH1, U2 - PV2 CH1, U3 - PV3 Here's the code that I tried. def challenge_leaderboard(request): challenge_id = request.GET.get('challenge_id') users = RewardPointLog.objects.filter(challenge_user__challenge_id=challenge_id).values_list('user', flat=True) users_points = {} for user in users: points = RewardPointLog.objects.filter(challenge_user__challenge_id=challenge_id, challenge_user__user=user).latest('created_datetime').points users_points[user.id] = points return Response(users_points, status=200) -
I have face a problem with python datetime objects, specifically the datetime.timedelta()
I am trying to find the difference in days as a number and not a datetime.timedelta() instance. I am using Django version 3.2 and fetching date values from a form on a template [Assume all the neccesary libaries are imported because its not an import error i am facing here] here is the code from the template - dateform.html <span style="position: absolute; right: 0%;font-size: 0.5em;" class="pull-left"> <form method="GET" action="{% url 'shifts:timeSheetFiltered' %}"> {% csrf_token %} start <input type="date" id="start-date" name="start-date" > end <input type="date" id="end-date" name="end-date" > <button type="submit" class="btn btn-xs btn-info"><i class="fa fa-filter"></i></button> </span> </form> </span> here is the view function in one of the django views. def timeSheetFiltered(request): end_date = forms.DateField().clean(request.GET.get('end-date')) start_date = forms.DateField().clean(request.GET.get('start-date')) num_days = end_date - start_date num_weeks = math.ceil(num_days/7) week_pack = [] counter = 0 while counter <= num_days: week_pack.append(start_date + timedelta(days=counter)) counter = counter + 1 shifts = Shift.objects.filter(time_added__range = [start_date,end_date]) context = { 'shifts': shifts, 'start_date': start_date, 'end_date': end_date, 'week_pack': week_pack, 'num_weeks': num_weeks } return render(request, 'shifts/timeSheetFiltered.html', context) Now when trying to process the request, i know the num_days variables is returning a datetime.timedelta(days={what-ever-the difference-here}) . I do not want that object, how can i extract the number of days as a plain … -
Is it valid to use LoginRequiredMixin, PermissionRequiredMixin in DRF APIview?
**DRF API view ** class UserAPI(**LoginRequiredMixin, PermissionRequiredMixin,**generics.ListAPIView): queryset = User.objects.filter(user_type="BRANCH_MANAGER") serializer_class = UserSerializer permission_required = ["accounts.view_branchmanager"] login_url = "api-auth/login/" -
PersonalInfo matching query does not exist
I wanted to add a multiple choice field to my form and after searching I finally made it work. however, when I create a new user and try to fill the personal info form, it gives me PersonalInfo matching query does not exist error. these are my codes: models.py: class Field(models.Model): id = models.AutoField(primary_key=True) slug = models.CharField(max_length=16, default='default') title = CharField(max_length=32) class PersonalInfo(models.Model): id = models.AutoField(primary_key=True) isCompleted = models.BooleanField(default=False) interested_fields = models.ManyToManyField(Field, blank=True) forms.py: class InterestedFieldsForm(forms.ModelForm): interested_fields = forms.ModelMultipleChoiceField(widget=forms.CheckboxSelectMultiple, queryset=Field.objects.all(), required=False) class Meta: model = PersonalInfo fields = ['interested_fields'] views.py: class PersonalView(View): template_name = 'reg/personal.html' def get(self, request, *args, **kwargs): context = {} context['fields'] = Field.objects.all() return render(request, self.template_name, context=context) def post(self, request, *args, **kwargs): user = request.user if request.method == 'POST': form = InterestedFieldsForm(request.POST, instance=PersonalInfo.objects.get(user=user)) if form.is_valid(): profile = form.save(commit=False) profile.user = request.user profile.save() form.save_m2m() else: form = InterestedFieldsForm() return render(request, 'reg/done.html', context={'form': form}) I know that the issue is because of this line in views: form = InterestedFieldsForm(request.POST, instance=PersonalInfo.objects.get(user=user)) when I remove the instance, the form gets saved as the users' personal info but form wont replace the previous, it creates a new one. then again I put instance back and try to save the form and everything … -
Share details view to modal in django
Getting stuck to share details view to modal. Found this answer but can't understand it properly. I am sharing my code below. Views.py from django.shortcuts import render from .models import Post from django.views.generic.list import ListView from django.urls import reverse_lazy class PostListView(ListView): model = Post context_object_name = 'posts' template_name = 'f_home/index.html' models.py from django.db import models from django.contrib.auth.models import User # Create your models here. class Post(models.Model): name = models.CharField(max_length=200, blank=True) email=models.CharField(max_length=200, blank=True) address=models.CharField(max_length=400, blank=True) weblink = models.URLField(max_length=200) image = models.ImageField( default='default.png', upload_to='uploads/%Y/%m/%d/') author = models.ForeignKey(User, on_delete=models.CASCADE) def __str__(self): return f'Added {self.name} Profile' Template {% for post in posts %} <div class="purple card"> <div class="image"> <img src="{{ post.image.url }}"> </div> <div class="content"> <div class="header"><a href="{{ post.weblink }}">{{ post.name }}</a></div> </div> <div class="ui bottom attached button" onclick="pop()"> <i class="globe icon"></i> <p>View Details</p> </div> </div> {% endfor %} <div class="ui modal"> <i class="close icon"></i> <div class="header"> Modal Title </div> <div class="image content"> <div class="ui medium image"> <img src="{% static 'images/cool-background.png' %}"> </div> <div class="description"> <div class="ui header">We've auto-chosen a profile image for you.</div> <p>We've grabbed the following image from the <a href="https://www.gravatar.com" target="_blank">gravatar</a> image associated with your registered e-mail address.</p> <p>Is it okay to use this photo?</p> </div> </div> </div> <script src="https://cdnjs.cloudflare.com/ajax/libs/jquery/3.6.0/jquery.min.js" integrity="sha512-894YE6QWD5I59HgZOGReFYm4dnWc1Qt5NtvYSaNcOP+u1T9qYdvdihz0PPSiiqn/+/3e7Jo4EaG7TubfWGUrMQ==" … -
TypeError: Cannot read properties of undefined (reading 'image')
import React from 'react' import { Link } from 'react-router-dom' import { Row, Col, Image, ListGroup, Button, Card } from 'react-bootstrap' import Rating from '../components/Rating' import products from '../products' function ProductScreen({ match }) { const product = products.find((p) => p._id === match.params.id) return ( Go Back <Col md={3}> <ListGroup variant="flush"> <ListGroup.Item> <h3>{product.name}</h3> </ListGroup.Item> <ListGroup.Item> <Rating value={product.rating} text={'${product.numReviews} reviews'} color={'#f8e825'} ></Rating> </ListGroup.Item> <ListGroup.Item> Price: ₹{product.price} </ListGroup.Item> <ListGroup.Item> Description: {product.description} </ListGroup.Item> </ListGroup> </Col> <Col md={3}> <Card> <ListGroup variant="flush"> <ListGroup.Item> <Row> <Col>Price:</Col> <Col> <strong>{product.price}</strong> </Col> </Row> </ListGroup.Item> <ListGroup.Item> <Row> <Col>Status:</Col> <Col> {product.countInStok > 0 ? 'In Stock' : 'Out of Stock'} </Col> </Row> </ListGroup.Item> <ListGroup.Item> <Button className='btn-block' type='button'> add to Cart </Button> </ListGroup.Item> </ListGroup> </Card> </Col> </Row> </div> ); } export default ProductScreen enter image description here -
django: how to read and manipulate .csv file from View.py
I am trying to work from csv files located inside of a django app. I am trying to load the file using pandas like: pd.read_csv("...") without success, I keep getting an error. Here is what the directory tree looks like: ├── __pycache__ │ ├── forms.cpython-36.pyc │ ├── models.cpython-36.pyc │ ├── views.cpython-36.pyc │ └── urls.cpython-36.pyc ├── apps.py ├── files │ ├── t1.csv │ ├── t2.csv │ ├── t3.csv │ ├── t4.csv │ └── parametre.csv ├── finished_apps.py ├── forms.py ├── migrations │ ├── 0001_initial.py │ ├── __init__.py │ └── __pycache__ │ ├── 0001_initial.cpython-36.pyc │ ├── 0002_remove_carriers_carriersheet.cpython-36.pyc │ ├── 0003_auto_20211021_1200.cpython-36.pyc │ ├── 0004_auto_20211021_1203.cpython-36.pyc │ └── __init__.cpython-36.pyc ├── models.py ├── views.py ├── templates │ ├── add_carrier.html │ ├── base.html │ ├── delete_carrier.html │ ├── delete_carrier_confirmation.html │ ├── _carrierdetails.html │ ├── _carrierlist.html │ ├── simulation.html │ └── update_carrier.html └── urls.py I have tryed the following inside of views.py df = pd.read_csv("/files/t1.csv") #not working df = pd.read_csv("./files/t1.csv") #not working df = pd.read_csv("t1.csv") #not working df = pd.read_csv("../files/t1.csv") #not working I have also tried doing that: from files import t1 that's not working either. I am now wondering whether it is possible to import a file this way or I am missing something obvious here! -
Django/Celery task received but nothing happened
Im trying to update database object via celery task. without celery task im able to update the db object but when i add .delay() and send it to celery task ive got Task passenger.tasks.create_circle[3e60c0ee-6da7-4e7c-80c8-663b27b90762] received child process 116 calling self.run() child process 5952 calling self.run() and then nothing happened.I cant update the db object whatsoever. here is my settings.py BROKER_URL = 'redis://localhost:6379' CELERY_ACCEPT_CONTENT = ['application/json'] CELERY_TASK_SERIALIZER = 'json' CELERY_RESULT_SERIALIZER = 'json' and here is the tasks.py @shared_task(bind=True) def create_circle(self, userid): print('celery working') radius = 500 user = Passenger.objects.get(id = userid) point = user.location point.transform(6347) poly = point.buffer(radius) poly.transform(4326) user.circle = poly user.save() any idea? -
535, b'Error: authentication failed when using os.environ to get the password
I'm trying to setup the password-reset route on Django, for not showing the account and the password directly in the code, I set them in the Mac environment, but keep getting the 535 error. its working if I write the password in the code, but getting error through "os.environ.get". EMAIL_HOST_USER = os.environ.get('DB_USER') EMAIL_HOST_PASSWORD = 'THESAMEPASSWORD'//this line works EMAIL_HOST_PASSWORD = os.environ.get('DB_PASS')//this line getting error DEFAULT_FROM_EMAIL = os.environ.get('DB_USER') -
Call django view in the background (every 15 seconds) until to get the customer details on form and then call auther view
I explain my problem to you i have two views function on django (check_flights and save_booking ) and i must Call check_flights successfully in two phases: 1st phase: Call check_flights every 2 or 3 seconds in the first 10 seconds of calling it, until i receive the parameters with the following values: - "flights_checked": true "price_change": false "flights_invalid": false 2nd phase: Once the flights are checked ("flights_checked: true"), continue calling check_flights in the background (every 15 seconds) until i get the customer details and then call save_booking. I need help from the 2nd phase thanks