Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
UnboundLocalError at /register/ local variable 'form_value' referenced before assignment
I'm trying to get into it the register page but i cant views.py def registerPage(request): if request.user.is_authenticated: return redirect('home') else: if request.method == 'POST': form_value = CreateUserForm(request.POST) if form_value.is_valid(): form_value.save() user = form_value.cleaned_data.get('username') messages.success(request, 'Account was create for {}'.format(user)) return redirect('login') context = {'form_key':form_value} return render(request, 'accounts/register.html', context) Traceback File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\core\handlers\exception.py", line 47, in inner response = get_response(request) File "C:\Users\le\anaconda3\envs\myenv\lib\site-packages\django\core\handlers\base.py", line 181, in _get_response response = wrapped_callback(request, *callback_args, **callback_kwargs) File "C:\Users\le\Desktop\django-course\Django(02-09-21)\crm1\accounts\views.py", line 26, in registerPage context = {'form_key':form_value} UnboundLocalError: local variable 'form_value' referenced before assignment Maybe have problem with indentation, please help me -
How to change queryset to dataframe in an environment where pandas is not installed or how to run code without pandas
I'm running the code in an environment where pandas cannot be installed. What do I need to fix to make the code below work in an environment without pandas ? (This is the code that ran successfully when tested in the environment where pandas is installed.) def download_supporting(request): locale.setlocale(locale.LC_ALL, 'ko_KR.UTF-8') supportings = Supporting.objects.filter(is_deleted='0').order_by('register_date') \ .annotate(register_date_str=Cast('register_date', CharField())) \ .values_list(register_date_str', 'name', 'sex', 'age', 'memo') #supportings = pd.DataFrame.from_records(supportings) #supportings = supportings.rename(columns={0: 'register_date_str', # 1: 'name', # 2: 'sex', # 3: 'age', # 4: 'memo'}) ----> Commented out to run without pandas. output = io.BytesIO() workbook = xlsxwriter.Workbook(output) worksheet = workbook.add_worksheet() merge_format = workbook.add_format({'bold': True, 'border': 1, 'align': 'center', 'valign': 'vcenter', 'text_wrap': True}) for supporting in supportings[0].unique(): ----> 'tuple' object has no attribute 'unique' u = supportings.loc[supportings[0] == supporting].index.values + 1 if len(u) < 2: pass # do not merge cells if there is only one supporting day else: worksheet.merge_range(u[0], 0, u[-1], 0, supportings.loc[u[0], 'Day'], merge_format) workbook.close() output.seek(0) supportings.set_index(supportings.columns[:-1].tolist()).to_excel('supporting.xlsx') -
How can I successful POST a Choice that is linked to a Question in a Poll's API in Django?
I am creating a survey / voting api, I can successfully POST question but I am getting the following error Choice() got an unexpected keyword argument 'question' when I try to create a choice that is linked to a question, I can't figure it out. These are the models from django.db import models import datetime from django.utils import timezone # Модели для опоросов class Question(models.Model): poll_question = models.CharField(max_length=255, blank=False) title = models.CharField(max_length=255, blank=True) start_date = models.DateTimeField('date published', blank=False) def __str__(self): return self.poll_question def published_not_longage(self): now = timezone.now() return now - datetime.timedelta(days=1) <= self.start_date <= now #Модель для Выбора class Choice(models.Model): poll_question = models.ForeignKey(Question, on_delete=models.CASCADE) poll_question_choice = models.CharField(max_length=255) votes = models.IntegerField(default=0) The choices serializer class ChoiceSerializer(serializers.Serializer): poll_question_choice = serializers.CharField(max_length=255) def create(self, validated_data): return Choice.objects.create(**validated_data) #The choices view - The error is arising when I pass in the question instance in the serializer.save() method. @api_view(['POST']) def choice_details(request, pk): question = Question.objects.get(pk=pk) # question = get_object_or_404(Question, pk=pk) serializer = ChoiceSerializer(data=request.data) if serializer.is_valid(): poll_question_choice = serializer.save(question=question) return Response(ChoiceSerializer(poll_question_choice).data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) -
Reverse query name clash on Django Abstract base classes
I am constructing Django model of files and I want to use an abstract base class for generic attributes and have it inherited by my specific models just like this. class File(models.Model): options = (("published", "Published"), ("draft", "Draft")) name = models.CharField(max_length=255) folder = models.ForeignKey(Folder, on_delete=models.CASCADE, blank=True, null=True, related_name="resource_file") status = models.CharField(max_length=10, choices=options, default="draft") tags = models.CharField(max_length=10) assignee = models.ForeignKey( settings.AUTH_USER_MODEL, on_delete=models.SET_NULL, blank=True, null=True, related_name="+", ) dateCreated = models.DateTimeField(default=timezone.now) dateUpdated = models.DateTimeField(default=timezone.now) class Meta: abstract = True def __str__(self): return self.name class QuillFile(File): content = models.TextField(blank=True, null=True) def upload_to(instance, filename): return "posts/{filename}".format(filename=filename) class UploadedFile(File): file = models.FileField(upload_to=upload_to, blank=True, default="") but I when I run makemigrations I got this error that says: Reverse query name for 'classrooms.UploadedFile.folder' clashes with reverse query name for 'classrooms.QuillFile.folder'. HINT: Add or change a related_name argument to the definition for 'classrooms.UploadedFile.folder' or 'classrooms.QuillFile.folder'. I tried changing and doing what's on the hint and put the assignee field on the children model and have them different related_name but I still got an error. Help. -
PackagesNotFoundError: The following packages are not available from current channels: - manage
This is my first question here. I'm new to Python, Django and Anaconda. I am trying to follow this tutorial but I keep running into hiccups. I found a similar answer to my question and I'm willing to admit that I could be misunderstanding something due to my lack of experience. I am using PyCharm and I'm installing the necessary packages (as needed for the tutorial) via the gui and I'm using the terminal inside PyCharm. At this part of the tutorial where you're supposed to run the server of the project, I keep getting this error: PackagesNotFoundError: The following packages are not available from current channels: - manage Whenever I go to install from conda forge or pip install in the terminal, I am met with the same errors. Like I said, I found a similar post on here, but it is not the solution I need. I'm also not exactly sure what I'm doing wrong. I've installed and updated python and django, and everything requested in the tutorial. PackagesNotFoundError: The following packages are not available from current channels: Thank you in advance for anyone who helps me. -
Converting/ Parsing HTML to Word in a Django Project
I want to add the option to convert my HTML with information in to a word document. I have the PDF with some CSS: <h1> {{ info.businessName }}<br /> <small style="color: rgb(187, 187, 184); margin: 0px 0px 0px 0px" >Business Plan <br /> Prepared {{ info.date_posted|date:"F Y" }} </small> </h1> Here is the views.py def order_word(request, info_id): info = get_object_or_404(Info, id=info_id) html = render_to_string('businessplan/word.html', {'info': info}) response = HttpResponse(content_type='application/word') response['Content-Disposition'] = 'attachment; filename="{}-Business Plan.pdf"'.format(info.businessName) return response Here is the URL.py path('<str:info_id>/word/', order_word, name='order_word'), Here is the link to download the word: <a href="{% url 'businessplan:order_word' form.instance.id %}"> <button type="button" class="btn btn-primary"> Download Word </button> </a> -
Uncaught ReferenceError: jQuery is not defined Django jQuery CDN
I am building a Django webapp and want to use a JS extension that creates a weekly schedule link. I have placed this extension in the static directory of my project and imported jQuery and the extension in the of my base.html as so: <!-- jquery --> <script src="https://code.jquery.com/jquery-3.3.1.min.js" defer></script> <!-- jQuery schedule display (includes css and js) --> <link rel="stylesheet" href="{% static 'Dynamic-Weekly-Scheduler-jQuery-Schedule/dist/jquery.schedule.css' %}"> <script src="{% static 'Dynamic-Weekly-Scheduler-jQuery-Schedule/dist/jquery.schedule.js' %}"></script> Yet, when I attempt to pass data into this plugin as so: <script type="text/javascript"> console.log({{schedule_data}}) $("schedule").jqs({{schedule_data}}) </script> I get an error in jquery.schedule.js: Uncaught ReferenceError: jQuery is not defined referring to the end of this file that is: $.fn[pluginName] = function (options) { var ret = false; var args = Array.prototype.slice.call(arguments); var loop = this.each(function () { if (!$.data(this, 'plugin_' + pluginName)) { $.data(this, 'plugin_' + pluginName, new Plugin(this, options)); } else if ($.isFunction(Plugin.prototype[options])) { ret = $.data(this, 'plugin_' + pluginName)[options](args); } }); if (ret) { return ret; } return loop; }; })(jQuery, window, document); What am I doing wrong? Should I not be using jQuery CDN? Note that jQuery isn't defined elsewhere in the jquery.schedule.js document. Thank you -
TemplateDoesNotExist at / index.html in Docker | react with django
Why my react build folder doesn't serve after run python manage.py collectstatic command in Dockerfile? I have tried for a long time to dockerized my whole project but I did fail to collect static files. Where I miss please have a look into it. ***This is my backend/Dockerfile inside django project *** FROM python:3.9.5-slim ENV PYTHONUNBUFFERED 1 RUN pip install --upgrade pip RUN apt-get update && apt-get install build-essential python-dev -y COPY requirements.txt requirements.txt RUN pip3 install -r requirements.txt && pip3 install uwsgi WORKDIR /django COPY . . CMD ['RUN', 'python', 'manage.py', 'collectstatic', '--noinput'] EXPOSE 8000 CMD ["uwsgi", "--http", ":9090", "--wsgi-file", "IMS/wsgi.py", "--master", "--processes", "4", "--threads", "2"] And this is my frontend/Dockerfile inside my react folder FROM node:13.12.0-alpine WORKDIR /react COPY . . RUN npm install RUN npm run build EXPOSE 3000 And finally, this is my docker-compose.yml file where I setup 3 services version: "3.3" services: backend: build: context: ./backend/ command: gunicorn IMS.wsgi --bind 0.0.0.0:8000 container_name: ims-backend restart: always ports: - "8000:8000" networks: - ims-network ims-postgres: image: "postgres:14beta2-alpine3.14" restart: always container_name: ims-postgres hostname: emrdsaws.czlz2b677ytu.ap-south-1.rds.amazonaws.com environment: - POSTGRES_PASSWORD=zkf!%uW_?&UG%4 - POSTGRES_DB=imsrds - POSTGRES_USER=dbrdsubuntume12 ports: - 5432 frontend: build: context: ./frontend/ volumes: - react_build:/react/build expose: - 3000 stdin_open: true nginx: image: nginx:latest … -
axios get request depending on user data fails
I've setup an auth system with nuxtjs & django. However i do not understand nuxtjs completely <template> <div> {{ this.$auth.$storage.state.user.email }} </div> </template> <script> import axios from 'axios'; export default { } axios.get('/api/v1/is-success-or-not?email='+this.$auth.$storage.state.user.email) .then((response) => { if(response.data === "True") { console.log("Player is success") $nuxt.$router.push('/schedule') } }) axios.get('failureornot?email='+this.$auth.$storage.state.user.email) .then((response) => { if(response.data > 3) { console.log("failure") $nuxt.$router.push('/failure') } }) </script> This is my code I've the email that shows up with {{ this.$auth.$storage.state.user.email }} but when i try to adapt the get request depending on the user, i get this error Cannot read properties of undefined (reading '$auth') I do not understand because $auth is obviously define if i can print the value thanks for your help ! -
Django - Sqlite column names different from model field name
I've had a model with a field named enclosure_id. I changed the field name to enclosure_name in the model and everywhere in the code, since that seemed more appropriate to the content. Now the respective column in the db is called enclosure_name_id I do not understand how this name is created. And I'm not able to get rid of this. I've deleted the database (I'm still at a testing phase) and all migrations, it's always regenerated as enclosure_name_id. Nowhere in my entire code is there an occurence of enclosure_name_id. If anyone could help me out, this would be great. Best regards, Gero -
How to serialize multiple models in on serializer with Django?
I try to combine multiple serializers into 1 so I don't have to do multiple fetch on the front end for the same page. Seems that I must use SerializerMethodField. My views is quite simple : @api_view(['GET']) def get_user_profile_by_name(request, name): try: user_profile = UserProfile.objects.get(display_name=name.lower()) serializer = UserProfileSerializer(user_profile, many=False) return Response(serializer.data) except ObjectDoesNotExist: message = {'detail': 'User does not exist or account has been suspended'} return Response(message, status=status.HTTP_400_BAD_REQUEST) As this can be accessed by Anonymous user, I can't use request.user All models I want to access inside UserProfileSerializer are related to UserProfile. So I dont really know how to setup my serializer. ( I have more serializer to combine but I limited this to one serializer inside the serializer for the example ) class UserProfilePicture(serializers.ModelSerializer): class Meta: model = UserProfilePicture fields = '__all__' class UserProfileSerializer(serializers.ModelSerializer): profile_picture = serializers.SerializerMethodField(read_only=True) class Meta: model = UserProfile fields = '__all__' def get_profile_picture(self, obj): # What to do here ? I struggle to understand how to acces " user_profile " object from UserProfileSerializer in order to query the right UserProfilePicture object and return the data combined inside UserProfileSerializer. -
django can't import anything from django allauth
So i have my django project running inside a docker container i have included this in my requirements.py file django-allauth==0.45.0 and this in my settings.py file INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'django.contrib.sites', 'main.apps.MainConfig', 'rest_framework', 'django.contrib.humanize', 'allauth', 'allauth.account', 'allauth.socialaccount', 'allauth.socialaccount.providers.facebook', 'allauth.socialaccount.providers.google', ] and this in my urls.py and it's running perfectly urlpatterns = [ path('admin/', admin.site.urls), path('', include('main.urls')), path("accounts/", include("allauth.socialaccount.providers.google.urls")), path("accounts/", include("allauth.socialaccount.providers.facebook.urls")) ] in my signals.py file this is what's not working, it's this line: from allauth.account.views import LoginView, allauth.account.views is underlined in red and i didn't get any error in the terminal but in the problems section i have Import "allauth.account.utils" could not be resolved -
In Django template, how can we access column from other child from same parent
I have Stocks as a parent table, Advice and Indexmapper as child table, from view I am returning Advice queryset nad in template, I want to access Indexmapper.index_name from Advice queryset. model.py class Stocks(models.Model): ticker = models.CharField(max_length=30, primary_key=True, unique=True) company_name = models.CharField(max_length=100, blank=True, null=True) sector = models.CharField(max_length=50, blank=True, null=True) class Meta: db_table = 'stocks' class Advice(models.Model): ticker = models.ForeignKey(Stocks, db_column='ticker', related_name='advices', on_delete=models.CASCADE) advice_date = models.DateTimeField(blank=True, null=True) high20 = models.FloatField(blank=True, null=True) class Meta: db_table = 'advice' unique_together=(('ticker','advice_date'),) class IndexMapper(models.Model): index_name = models.TextField(blank=True, null=True) ticker = models.ForeignKey(Stocks, db_column='ticker',on_delete=models.CASCADE, related_name='indexmap', blank=True, null=True) class Meta: db_table = 'indexmapper' unique_together=(('index_name','ticker'),) view.py ifund = IndexMapper.objects.filter(index_name='NIFTY 50') filter_stock = all_stocks_obj.filter(indexmap__in=ifund) result = Advice.objects.filter(ticker__in=filter_stock) return render(request, 'screeners.html',{'result':result}) in template I want to access IndexMapper.index_name. I tried like this but not working {{result.ticker.indexmap.index_name}} -
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): …