Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to return a excel file back to a user using Django and Pandas
I am currently taking an excel file from the user on my home.html page, passing it to my python, using the values to do some logic, and wanting to returned a excel file back to the user after the logic has edited the data. I had this working as an .exe on my computer already but wanted to move it to a web page. I am not currently getting any errors. Does anyone know how to do this, or know of a walkthrough that might can help me? def page_objects(request): Area = request.POST["Area"] Output = request.POST["Output"] FilePath = request.FILES['myfile'] if Output == 'List': zone = pd.read_excel(FilePath, sheet_name= "Form", header=0, usecols=list(range(7))) WC = zone.iat[3,4] data = pd.read_excel(FilePath, sheet_name="Form", header=0, usecols=list(range(7)), skiprows=8) data2= pd.read_excel(FilePath, sheet_name="Form", header=0, usecols=list(range(7)), skiprows=8) Then I do some logic writer = ExcelWriter(FilePath) data.to_excel(writer, 'Sheet1', index=False) data2.to_excel(writer, 'Sheet2', index=False) writer.save() When I was using the .exe ExcelWriter("location where I saved the new file") was how I returned the edited data to myself. -
unsupported operand type(s) for /: 'NoneType' and 'int' [closed]
I have some classes in django class Computer(models.Model): SerialNumber = models.CharField(max_length=30,primary_key=True) Name = models.CharField(max_length=50,unique=True,blank=False) ComputerPicture = models.CharField(max_length=150,blank=True) Details = models.ManyToManyField('Detail',blank='True',related_name='Computers') def sum(self): a = self.Details.all().aggregate(Sum('Price'))['Price__sum'] return a/2 class Detail(models.Model): SerialNumber = models.CharField(max_length=30, primary_key=True) Name = models.CharField(max_length=50, unique=True, blank=False) DetailPicture = models.CharField(max_length=150, blank=True) Price = models.FloatField(blank=False) later i try to use fucntion in shell: pc - element of Computer class >>> type(pc.Details.all().aggregate(Sum('Price'))['Price__sum']) <class 'float'> >>> pc.Details.all().aggregate(Sum('Price'))['Price__sum'] 82500.0 >>> type(pc.Details.all().aggregate(Sum('Price'))['Price__sum']) <class 'float'> >>> pc.Details.all().aggregate(Sum('Price'))['Price__sum']/2 41250.0 it works! but then i try this in code: def sum(self): a = self.Details.all().aggregate(Sum('Price'))['Price__sum'] return a/2 i get an error: unsupported operand type(s) for /: 'NoneType' and 'int' -
How can I have Django serve React using Apache2 on Ubuntu 18.04?
I am trying to deploy a Django application with a React frontend using Apache2 on Ubuntu 18.04. The React application is being served by Django through the staticfiles app. For context, let's start off with how Django is serving React. The following code is from nerd-rich-django-back-end/nerdrich/urls.py. from homepage.views import index url_patterns = [ path('', index, name=index), ] Next we have nerd-rich-django-back-end/homepage/views.py from django.views.generic import TemplateView from django.views.decorators.cache import never_cache index = never_cache(TemplateView.as_view(template_name='build/index.html')) With this configuration Django will serve the React application when the user hits the root endpoint. This works in development, but when I try to replicate this in production I run into some problems. Namely... Here is the site I am using in Apache2 - /etc/apache2/sites-available/000-default-le-ssl.conf <Directory /home/jakuta/.venv/bin/djangoprojects/nerd-rich-django-back-end/nerdrich> <Files wsgi.py> Require all granted </Files> </Directory> <Directory /home/jakuta/.venv/bin/djangoprojects/nerd-rich-django-back-end/nerd-rich-front-end/build> Require all granted </Directory> The DocumentRoot directive was deleted and the Django application works fine as there are other endpoints to test like the API endpoints using DRF. But when a request to https://nerdrich.net/ is made, there is only a blank page. If you navigate to https://nerdrich.net/jakuta you will get the browsable API. For additional context, here are some of the settings in Django nerd-rich-django-back-end/nerdrich/settings.py CORS_ORIGIN_WHITELIST = [ 'http://localhost:3000' 'http://localhost:5000' ] … -
How to understand following nested function where function passed as argument?
How to understand the following code? nested function function as an argument def check_password(self, raw_password): """ Returns a boolean of whether the raw_password was correct. Handles hashing formats behind the scenes. """ def setter(raw_password): self.set_password(raw_password) self.save(update_fields=["password"]) return check_password(raw_password, self.password, setter) -
Django Rest Framework upload file and in response show the url without database ref
I am trying to upload file directly to server with my expected name and trying to give the file url send in response without saving its ref database field. This is my views: class DocumentUploadView(APIView): parser_classes = [MultiPartParser] def post(self, request, format=None): file_obj = request.data['file'] return Response( status=204 ) I tried to upload with postman and i see no data is saved in my server media folder. Can anyone help me in this case? I dont want to save the url of the file in database imageField or or FileField, i just want to upload it to save it directly in server and in response, it should send me the url. Can anyone help me in this case? -
how to define dependent IntegerField
I'm a beginner with Django and have a model class myModel(models.Model): XYZ = ( (1, "X"), (2, "Y"), (3, "Z"), ) ABC = ((1, "xA"), (2, "xB"), (3, "xC"), (4, "yA"), (5, "yB"), (6, "yC"), (7, "yD"), (8, "zA"), (9, "zB"), ) xyz = models.IntegerField(_('XYZ_Field'), choices=XYZ) abc = models.IntegerField(_('ABC_Field'), choices=ABC) I want to define abc as a dependent field. for example, if the user selects "X" for xyz, valid values for choosing abc are just < xA or xB or xC > or if the user chooses "Z" for xyz, he can just choose zA or zB as right values of abc field. how can I define it in models.py I tried to define XYZ as a dictionary , but I didn't know how to use it for defining choices parameter of abc. XYZ = { (1, "X"): ((1, "xA"), (2, "xB"), (3, "xC")), (2, "Y"): ((4, "yA"), (5, "yB"),(6, "yC"), (7, "yD")), (3, "Z"): ((8, "zA"), (9, "zB"))} xyz = models.IntegerField(_('XYZ_Field'), choices=XYZ) abc = models.IntegerField(_('ABC_Field'), choices=**?????**) Some say it must be handled in forms.py, but I want to do it once in models.py . So all forms which uses this model doesn't need to implement the specific criteria. Any … -
Login not working with react and Django Rest APIs
This is my first time building a React / Django Web App and I am experiencing troubles with the authentication of my platform. I am using Insomnia to test out my Django APIs. Everything works fine so far: I can make a POST request to api/auth and log in. After that I can access to every @login_required route of my APIs. @csrf_exempt def auth(request): if request.method == "POST": # Attempt to sign user in body = json.loads(request.body) username = body["username"] if body["username"] else None password = body["password"] if body["password"] else None user = authenticate(request, username=username, password=password) # Check if authentication successful if user is not None: login(request,user) return JsonResponse(user.serialize(),status=200) else: return JsonResponse({"error":"Invalid username and/or password."},status=403) if request.method == "GET": if request.user in Users.objects.all(): return JsonResponse(request.user.serialize(),status=200) else: return JsonResponse({"error":"Not logged in."},status=404) return JsonResponse({"error":"Wrong method."},status=405) Here comes the tricky part: when I log in through the Login page ( created with react-router-dom ) it just works and I get my user object from the APIs. But then I go to my home page and everything acts like I'm not logged in. It seems like that the server doesn't recognise that the request on the home page comes from the same client that … -
It is a best practice use a Primary Key in a serializer who do not represent a Model Object?
I'm creating an endpoint in Django for a post REST API. I put the parameters of the post body on a class, to handle it internally, but the senior developer says it is better to use a serializer. I create a serializer and everything worked perfectly until the same senior says I have to add a PrimaryKeyRelatedField. That is when my confusing started because this serializer is not for a Model, but for the body of the request object (who has 3 parameters, one mandatory and two optional), and when I added the mandatory parameters as PrimaryKeyRelatedField, I start to receive on the validated_data an empty OrderedDict() My questions are: It makes sense to have a PrimaryKeyRelatedField in a serializer who does not represent a Model? In case it makes sense, how I can make it work (or why when I make one of the fields primary key, I receive an empty dict?) PS: I make sure to send the right data to the endpoint, so this is not a case of receiving an empty OrderedDict because I did not send the mandatory field -
How to start Django models auto increment key from a certain number like 2456?
In mysql if you want to start your auto-increment key from 2456 you can write AUTO_INCREMENT=2456 Also in PostgreSQL we can do this by using Sequence CREATE SEQUENCE serial START 2456; INSERT INTO distributors VALUES (nextval('serial'), 'nothing'); But in Django Rest Framework or Django by default auto-increment starts from 1. If I have a model like this class Content(models.Model): title = models.CharField(max_length=70, blank=False, default='') description = models.CharField(max_length=200,blank=False, default='') published = models.BooleanField(default=False) How can I make sure that the first Content starts from 2456? -
Stack advice for a data visualization project
Since I'm not familiar with all the frontend and backend technologies, I wanted to ask here to get some "best possible approach" ideas. So here is what I wanna do: I have a couple of scripts written in python that do some scientific calculations and modellings by using source and target data in csv formats. Then outputs the results as a text file. 1-) I want to create private user profiles that has custom UI, something like Bootstrap admin dashboard templates with charts, maps and graphs that attached to the user's database. 2-) An admin interface where I can implement and run my python scripts, print the results to a spesific user's database where the charts&graphs recieves their data from. 3-) It will be a commercial platform, so a CMS feautures are needed for tracking orders and etc. I initially thought going with Vue & Django but I'm not so sure it's the best and easiest way of up and run such a project. I appreciate the experienced user's opinions. Thanks in advance. -
Problem with hyperlink in django project in templates html
I have a problem with the hyperlink in my django project. I use python 3.8.5 django 3.1.1. I created 2 applications: blog and pages (with many subpages). https://github.com/Charnel2500/blog_ai_py385_django311 This is my base.html <!DOCTYPE html> <html lang="en"> <link> <meta charset="UTF-8"> <title>Strona startowa</title> <link rel="stylesheet" href="base.css"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> <script src="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/js/bootstrap.min.js" integrity="sha384-ChfqqxuZUCnJSK3+MXmPNIyE6ZbWh2IMqE241rYiqJxyMiZ6OW/JmZQ5stwEULTy" crossorigin="anonymous"></script> <script src="https://code.jquery.com/jquery-3.3.1.slim.min.js" integrity="sha384-q8i/X+965DzO0rT7abK41JStQIAqVgRVzpbzo5smXKp4YfRvH+8abtTE1Pi6jizo" crossorigin="anonymous"></script> <script src="https://cdnjs.cloudflare.com/ajax/libs/popper.js/1.14.3/umd/popper.min.js" integrity="sha384-ZMP7rVo3mIykV+2+9J3UJ46jBk0WLaUAdn689aCwoqbBJiSnjAK/l8WvCWPIPm49" crossorigin="anonymous"></script> </head> <body> <div w3-include-html="base.html"></div> <div class="container"> <h1>Witaj użytkowniku w świecie sztucznej inteligencji</h1> <section> <nav class="navbar navbar-expand-lg navbar-dark bg-primary"> <a class="navbar-brand" href="">Strona Główna</a> <button class="navbar-toggler" type="button" data-toggle="collapse" data-target="#navbarSupportedContent" aria-controls="navbarSupportedContent" aria-expanded="false" aria-label="Toggle navigation"> <span class="navbar-toggler-icon"></span> </button> <div class="collapse navbar-collapse" id="navbarSupportedContent"> <ul class="navbar-nav mr-auto"> <li class="nav-item active"> <a class="nav-link" href="blog/"> Newsy <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="history/"> Historia </a> </li> <li class="nav-item active"> <a class="nav-link" href="present/"> AI obecnie <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="philosophy/"> Filozofia AI <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="chatbot/"> Chatbot <span class="sr-only">(current)</span></a> </li> <li class="nav-item active"> <a class="nav-link" href="talk/"> Rozmowa z moim chatbotem <span class="sr-only">(current)</span></a> </li> </div> </nav> </section> {% block content %} {% endblock %} <img src="AI.jpg" alt="Nie znaleziono obrazu"> </div> </body> </html> Here you can see my hyperlinks <li class="nav-item active"> <a class="nav-link" href="blog/"> Newsy <span class="sr-only">(current)</span></a> </li> … -
Django, same file at the output of two different loaded files on one page
model.py: class InJPG(models.Model): file_path = models.FileField(upload_to="media",unique=True) #in forms.py I am taking only this file_path in meta class views.py from model import InJPG def get_name(request): if request.POST: file1=InJPG(request.POST or None) file2=InJPG(request.POST or None) if file1.is_valid(): file1.save() print(file1) if file2.is_valid(): file2.save() print(file2) return redirect(get_name) return render(request,'files.html',{'file1':file1,'file2':file2}) files.html ... {% block page %} <form method="post" enctype="multipart/form-data"> {% csrf_token %} {{file1}} {% csrf_token %} {{file2}} <button type="submit">upload file2</button> </form> {% endblock %} Situation: As you can see I have page where I am uploading two separate files using browse option in Django, and then to Upload them I'm using submit button, in same form in html file. Problem: I don't know why, but after submit, when I am checking which file has been uploaded, (using print(file1) and print(file2) ) I am receiving ONLY file2. In models.py I have parameter unique=True so names are not identical but, they are coming from same file (file2) How to solve it, and receive file1 and file2 in same method inside view.py ? -
How to leverage Django forms in Next.js frontend application?
I am developing an application which has backend written in Django (Django REST Framework API) and frontend written in Next.js. I am now facing a situation where I need to implement a form that is highly correlated with my Django models. Is there a way to leverage Django's own form system instead of re-implementing it from scratch in Next.js? -
By Post request received data is None. Why it's possible
I have django app in it's views.py created for accepting, and saving objects from received data into database. from .models import Hook def hooktrack(request): source=requests.POST.get("source") b=Hook(dsourse=source).save() Than I link this view to .urls.py urlpatterns = [ path("hooktrack/",hooktrack), ] My full url use http protockol not https maybe it involved in my problem I several times tested hooktrack view and it was accept and save received data. curl -d "source=google" -X POST http://example.net/hooktrack/ After curling sent source=value accessible to query from dB. from my.models import Hook a=Hook.objects.all() for item in a: print(item.dsource) ...google Than I linked my hooktrack view to production for accepting hooks from our business partner. After receiving them all of them saved to database but has None value -
Operational error while adding values in a text field in django
I get this error when I add a something to the text field.I'm trying to create a project where someone can enter random messages. OperationalError at /admin/submit/submit/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8000/admin/submit/submit/add/ Django Version: 2.1 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: D:\Anaconda1\lib\site-packages\django\db\backends\sqlite3\base.py in execute, line 296 Python Executable: D:\Anaconda1\python.exe Python Version: 3.8.3 Python Path: ['D:\\PyProjects\\Website', 'D:\\Anaconda1\\python38.zip', 'D:\\Anaconda1\\DLLs', 'D:\\Anaconda1\\lib', 'D:\\Anaconda1', 'C:\\Users\\heman\\AppData\\Roaming\\Python\\Python38\\site-packages', 'D:\\Anaconda1\\lib\\site-packages', 'D:\\Anaconda1\\lib\\site-packages\\win32', 'D:\\Anaconda1\\lib\\site-packages\\win32\\lib', 'D:\\Anaconda1\\lib\\site-packages\\Pythonwin'] Server time: Mon, 5 Oct 2020 17:19:26 +000 This is my models.py from django.db import models # Create your models here. class Submit(models.Model): title = models.TextField(max_length=140, default='SOME STRING') status = models.TextField(max_length=140, default='SOME STRING') description = models.TextField(max_length=140, default='SOME STRING') Here is my setting.py installed apps INSTALLED_APPS = [ 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'submit.apps.SubmitConfig', ] Here is my apps.py from django.apps import AppConfig class SubmitConfig(AppConfig): name = 'submit' Here is my admin.py from django.contrib import admin from .models import Submit # Register your models here. admin.site.register(Submit) I also ran python manage.py makemigrations and python manage.py migrate Please help me...Thanks in advance -
Not Found: Requested url was not found on this server. AWS django elastic beanstalk
Hello let me apologize in advance since I am a beginner and this may be a very simply fix but I just launched my first elastic beanstalk server trying to host my portfolio. I followed the tutorial laid out by amazon at https://docs.aws.amazon.com/elasticbeanstalk/latest/dg/create-deploy-python-django.html but something must've gone wrong. I'll include a picture of my hierarchy, my applications.py and my urls.py if you need anything else don't hesitate to ask any help is very appreciated thanks! """ WSGI config for Portfolio project. It exposes the WSGI callable as a module-level variable named ``application``. For more information on this file, see https://docs.djangoproject.com/en/3.1/howto/deployment/wsgi/ """ import os from django.core.wsgi import get_wsgi_application os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'Portfolio.settings') application = get_wsgi_application() There is my application.py and now my urls.py from django.contrib import admin from django.urls import path, include from . import views urlpatterns = [ path('', views.index, name='index'), path('admin/', admin.site.urls), path('sudoku/', views.sudoku, name='sudoku'), ] and finally my hierarchy enter image description here -
How to mock info.context in Django / Graphene tests
Problem I'm trying to test a graphql query. The query requires that the user associated with the request (info.context.user) is a super user (.is_superuser). Otherwise it throws an exception. I'm trying to test that the query works properly but am unsure how to ensure that info.context.user.is_superuser resolves to true in the test. Please help! schema.py class Query(graphene.ObjectType): gardens = graphene.List(GardenType) def resolve_gardens(self, info): user = info.context.user if not (user.is_superuser or user.is_staff): raise Exception("You must be staff or a superuser to view all gardens") return Garden.objects.all() tests.py from graphene_django.utils.testing import GraphQLTestCase, graphql_query from users.models import CustomUser class TestGraphQLQueries(GraphQLTestCase): """ Test that GraphQL queries related to gardens work and throw errors appropriately """ def test_gardens_query(self): response = self.query( """ query { gardens { id name owner { id email } } } """ ) self.assertResponseNoErrors(response) Error Thrown gardens/tests.py:93: _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ _ ../env/lib/python3.6/site-packages/graphene_django/utils/testing.py:114: in assertResponseNoErrors self.assertNotIn("errors", list(content.keys())) E AssertionError: 'errors' unexpectedly found in ['errors', 'data'] -------------------------- Captured log call --------------------------- ERROR graphql.execution.utils:utils.py:155 Traceback (most recent call last): File "/home/dthompson/Code/personal/gardenbuilder-backend/env/lib/python3.6/site-packages/promise/promise.py", line … -
Implementar botão com evento onchange [closed]
Coloquei um techo do codigo HTML de um projeto Django que peguei nesses dias, na aplicação na pagina web tem essa opção de SERVIÇO para o usuario escolher o tipo de serviço que ele quer em um dropdown, mas quando o usuario escoher 1 serviço a tela recarrega e o serviço fica no dropdown e segue para o outro dropdown que é o de veiculos que corresponde ao serviço que foi escolhido, estou tentando implementar uma opção para o usuario poder escolher mais de um serviço e clicar com botão quando ele terminar, (ainda não criei o botão), mas estou com problemas pq nesse codigo tem o evento ONCHANGE e quando seleciono o serviço so fica 1 apenas, usei o SELECT2 mas sem sucesso, o evento ONCHANGE que pode esta causando isso, por causa disso não estou conseguindo, alguem pode me ajudar nesse codigo? Como fazer essa implementação de poder selecionar varios serviços e finalizar com o batão e depois recarregar a pagina com os serviços escolhidos? <h3><strong>Serviço</strong></h3> <select id="servico_cad" name="servico_cad" onchange="saveValue(this);this.form.submit();"> {% for i in cad_servico %} <option value='{{i}}'>{{i}}</option> {% endfor %} <option value='Todos'>Todos</option> </select> -
Django REST difference in views and viewsets
I have a fairly simple REST api, but I still dont understand the difference between the type of views. Anything related to a model, I do through ModelViewSets and ModelSerializers. You can use the router, you have parameters in swagger docs, all good! BUT, if I dont have a model (for example I have a function that accepts 2 parameters (var1 and var2) and the POST requests multiplies them, what is my best option? I prefer an option which involves a serializer as I am hoping to get parameters showing in the Swagger Documentation. I know I have the ViewSet option but that doesnt give me parameters in swagger. Is there any option that does give me those options? -
Adding Days of the Week as choices (datetime object) in a model field
I have a field in my models where I want it to be a datetime field and it would just hold the days of the week as choices. Is this possible i.e. the choices are datetime objects with the days of the week as the value. I assume that by doing this, I'll be able to sort the objects in chronological order. So if object1 has tuesday and object2 has monday and object3 is friday -- it can be sorted as object2, object1, object3 -
Serializer removing data in Django 3.1
I'm trying to validate data in order to store it. But the serializer is removing valid fields. Here my code: models.py class MyModel(models.Model): user_id = models.UUIDField('action uid',default=uuid.uuid4,null=False,primary_key=True,blank=False,editable=False, unique=True) city = models.CharField('City', max_length=50, null=True, blank=True, editable=False) latitude = models.CharField('Latitude', max_length=50, null=True, blank=True, editable=False) longitude = models.CharField('Longitude', max_length=50, null=True, blank=True, editable=False) datetime = models.DateTimeField('datatime', null=False, blank=False, editable=False) serializer.py class MyModelSerializer(serializers.ModelSerializer): class Meta: model = MyModel fields = '__all__' view.py def save_my_data(self, request): user_info ={ "user_id": data['user_uid'], "city": data['user_city'], "latitude": "17.6801", "longitude": "83.2016", "datetime": timezone.now() } serializer = serializers.MyModelSerializer(data=user_info) print( serializer.data ) # returns void Any thoughts about this? thanks in advance. -
Comments under Post
I created model Post and Comment, now I want to display comments from Post but I have a problem. In tutorial there is a line of code in html {% for comment in post.comments.all %} but isn't working in my app. If I set {% for comment in comments %} it works but displays all comments from models (I want only comments from the post). How to fix that? Below I pasted my code. models.py from django.db import models class Post(models.Model): title = models.CharField(max_length=64, blank=False, null=False) short_text = models.TextField(blank=False, null=False) text = models.TextField(blank=False, null=False) image = models.TextField(blank=False, null=False) date = models.DateTimeField(auto_now_add=True, blank=True) views = models.IntegerField(default=0) class Comment(models.Model): post = models.ForeignKey('main.Post', on_delete=models.CASCADE) author = models.CharField(max_length=200) text = models.TextField() created_date = models.DateTimeField(auto_now_add=True, blank=True) approved_comment = models.BooleanField(default=False) def approve(self): self.approved_comment = True self.save() def __str__(self): return self.text views.py from django.shortcuts import get_object_or_404, render, redirect from .models import Post, Comment def index_pl(request): posts = Post.objects.all() return render(request, 'index_pl.html', {'posts': posts}) def single_article_pl(request, id): posts = get_object_or_404(Post, pk=id) posts.views = posts.views + 1 posts.save() comments = Comment.objects.all() return render(request, 'single_article_pl.html', {'posts': posts, 'comments': comments}) html {% for comment in post.comments.all %} <div class="comment"> <div class="date">{{ comment.created_date }}</div> <strong>{{ comment.author }}</strong> <p>{{ comment.text|linebreaks }}</p> </div> {% … -
celery beat and worker doesn't work as expected
I want to make two functions that update and show a global list named websites, and execute them by celery. To initialize websites, I made a file named config.py: # config.py # I have to declare global variables outside of the init(), # otherwise Django doesn't recognize these global variables outside of the `config.py` global websites global flag flag = True # this method should be executed just One time!!! def init(): global flag flag = False global websites websites = [] print("===========IN Config.init()==========") I made two functions to be executed, check_list() executes every 2 seconds and initializes and shows the websites content, and update_list() executes every 10 seconds and add some elements to websites. Here is my tasks.py: (I made some prints in order to make the finding bug process easy.) # tasks.py from celery import shared_task from .celeryapp import app from . import config @shared_task def check_list(): try: print("config.flag First : " + str(config.flag)) if config.flag: config.init() print("This should be seen one tiiiiiiiiiiiiiiiiiiiiime") print("config.websites check_list : ===> " + str(config.websites)) except Exception as e: print(e) @shared_task def update_list(): try: print("config.flag First : " + str(config.flag)) if config.flag: config.init() print("This should be seen one tiiiiiiiiiiiiiiiiiiiiime") urls = ['first', 'second', … -
How can i redirect to the same page when a function executed Django
I have a like function in views.py and whenever the function executes i want to return the user to the same page he/she was. what should i write in return of my function? -
ModelForm not rendering to page?
This is a strange one for me because this is not the only ModelForm I have in this project and the other one is perfectly fine. Could someone have a look and see why the 'bid_input' input field for my form is not showing up on the page? My views.py admittedly isn't quite complete and functioning the way I want it to but I was at least expecting the input box to show but only the 'Place Bid' is showing. models.py class Bid(models.Model): bidder = models.ForeignKey(User, on_delete=models.CASCADE, related_name="bidders") item = models.ManyToManyField(Listing, related_name="bid_item", default=None, blank=True) bid_input = models.DecimalField(max_digits=9, decimal_places=2, default=None) time = models.TimeField() forms.py class BiddingForm(forms.ModelForm): class Meta: model = Bid fields = ["bid_input"] widgets = { "bid_input": forms.NumberInput(attrs={'autocomplete':'off'}) } urls.py path("listing/<int:id>/bid", views.bidding, name="bidding") views.py def bidding(request, id): listing = get_object_or_404(Listing, id=id) if request.method == "POST": form = BiddingForm(request.POST or None) if form.is_valid(): newbid = form.save(commit=False) newbid.bidder = request.user newbid.item = listing newbid.time = timezone.now() bid = newbid.save() return redirect("listing", bid_id=newbid.id) else: return render(request, "auctions/listingPage.html", { "form": form}) else: form = BiddingForm() return render(request, "auctions/listingPage.html", { "form": form }) listingPage.html {% extends "auctions/layout.html" %} {% block body %} <div> <form action="{% url 'bidding' listing.id %}" method="POST" name="bid_input"> {% csrf_token %} {{ …