Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
success url not redirecting to the page i want
I have a CreateView class where i set the success url like this class ListCreateView(CreateView): model = List fields = "_all_" success_url = "list" after submitting the form Its going to http://127.0.0.1:8000/home/create_list/list which doesnt exist I want it to go to http://127.0.0.1:8000/home/list can anyone help with some suggestions? I tried reverselazy but that brings up another big error. and im a noob. -
Django vs Tensorflow Serving
I have a Tensorflow model that I would like to deploy as a RESTful API. I'm thinking of deploying it either using Django or Tensorflow Serving. I'm very familiar with Django since I've been working with it for a few years but I heard that Tensorflow Serving is also a good choice for deploying Tensorflow models. Which option should I go for? Should I use Django or Tensorflow Serving to deploy my model? P/S: I'm leaning more towards Django because it has more flexibilities (i.e. I can deploy a Pytorch model on the same server as well) but I would really like to get more opinions on this. Thanks in advance! :) -
Get_context_detail wont return images in django
Im trying to give context to this detail view so i can show a picture in it, but when i load the page it wont show anything. Cheking on the page itself it says the source of the img is unkown. No errors so far. I changed the indexing to see if its that, still nothing views.py class Detalle_usuarios(LoginRequiredMixin, DetailView): model = User def get_context_detail(self, **kwargs): avatar = Avatar.objects.filter(user=user.id) ab = -1 for a in avatar: ab += 1 context = super(Detalle_usuarios, self).get_context_data(**kwargs) context = {"url":avatar[ab].imagen.url} return context template_name = 'Appfinal/usuario_detalle.html' template {% extends "Appfinal/template_logueado.html" %} {% load static %} {% block B %} <h1> {{user.username}} </h1> <img height = "80px" src="{{url}}"> <a href="/Appfinal/agregaravatar">Cambiar foto de perfil</a> <br> <a href="{% url 'usuarioInicio' %}">Inicio</a> {% endblock %} -
Django drf serialiser map non pk field to object of model
I have Language model like this class Language(models.Model): name = models.CharField() class Post(models.Model) title = models.CharField() language = models.ForeignKey(Language, models.SET_DEFAULT, default=1) class PostSerializer(serializers.ModelSerializer): language = serializers.CharField(source='language.name') class PostCreateAPIView(generics.ListCreateAPIView): serializer_class = serializers.PostSerializer Post payload { "title":"title_1", "language": "en" // instead of primary key } I wanted to map language name into object without using pk in payload. -
Fatal error in launcher: Unable to create process using "Path","Path" The system cannot find the file specified while using Uvicorn --reload
It's my first time with FastAPI and i'm trying to run my application, I used Uvicorn book:app --reload and my virtual environment is activated but I found this Error Fatal error in launcher: Unable to create process using '"S:\Fastapi\fastapienv\Scripts\python.exe" "S:\Fastapi\FastAPI\fastapienv\Scripts\uvicorn.exe" books:app --reload': The system cannot find the file specified. -
Docker - Build a service after the dependant service is up and running
I have a docker-compose file for a Django application. Below is the structure of my docker-compose.yml services: private-pypi-server: .... django-backend: build: context: ./backend dockerfile: Dockerfile depends_on: - private-pypi-server nginx: depends_on: - django-backend Django app is dependent on a couple of private packages hosted on the private-pypi-server without which the app won't run. I created a separate dockerfile for django-backend alone which install packages of requirements.txt and the packages from private-pypi-server. But the dockerfile of django-backend service is running even before the private pypi server is running. If I move the installation of private packages to docker-compose command code, then it works fine. Here the issue is that, if the backend is running and I want to run some commands in django-backend(./manage.py migrat) then it says that the private packages are not installed. Im not sure how to proceed with this, it would be really helpful If i can get all these services running at once by just running the command docker-compose up --build -d -
Django modify the datetime for the whole template / modify or change date time from server
I got this template {% for Ansicht in Ansicht.lehrertabelle_set.all %} <tbody> <tr> <th scope="row"></th> <td>{{Ansicht.Leitung_der_Klasse}}</td> <td>{{Ansicht.Funktion}}</td> <td>{{Ansicht.Nname}}</td> <td>{{Ansicht.Vname}}</td> <td>{{Ansicht.Einstellungsstatus}}</td> <td>{{Ansicht.Pflichtstunden_normal}}</td> <td>{{Ansicht.Status_normal}}</td> {% if Ansicht.Prognose_FK %} <td>{{Ansicht.Prognose_FK.Status}}</td> <td>{{Ansicht.Prognose_FK.Stunden}}</td> {% else %} <td>{{Ansicht.Prognose_FK.Status_2}}</td> <td>{{Ansicht.Prognose_FK.Stunden_2}}</td> {% endif %} the _FK is a foreingkey and it can be filtered by date to show me the right result if I hard code it like that {% for Ansicht in Ansicht.lehrertabelle_set.all %} <tbody> <tr> <th scope="row"></th> <td>{{Ansicht.Leitung_der_Klasse}}</td> <td>{{Ansicht.Funktion}}</td> <td>{{Ansicht.Nname}}</td> <td>{{Ansicht.Vname}}</td> <td>{{Ansicht.Einstellungsstatus}}</td> <td>{{Ansicht.Pflichtstunden_normal}}</td> <td>{{Ansicht.Status_normal}}</td> {% if Ansicht.Prognose_FK.DATEFUNCTION %} #just to name it <td>{{Ansicht.Prognose_FK.Status}}</td> <td>{{Ansicht.Prognose_FK.Stunden}}</td> {% else %} <td>{{Ansicht.Prognose_FK.Status_2}}</td> <td>{{Ansicht.Prognose_FK.Stunden_2}}</td> {% endif %} I need an input field like that <form method="GET"> <input type="date" class="form-control" id="date" value="{{something|date:'Y-m-d' }}"> <input type="submit"> </form> to filter the events by date like Prognose_FK shows when date is above or below and it goes on for the rest how can accomplish that if I use this from my models @property def DATEFUNCTION(self): return date.today() <= self.von_Datum it works perfect but I need to have this property dynamic for the user input hope someone find a solution -
Django sorting by date returns wrong sorting order
I have a query like this: Pedido.objects.filter(...).aggregate(...).values('dia_pedido').annotate(...).order_by('dia_pedido') The field 'dia_pedido' is of Date type. Data is not being displayed in the correct order: (...) 25/08/2022 26/08/2022 30/08/2022 01/09/2022 02/09/2022 28/06/2022 30/06/2022 01/07/2022 The last 3 lines above shouldn't be there, as June and July come before August and September. What could be happening? I'm using Django 4.0.1 and MySQL 8.0.30. -
Add a variable in a .env file in python
I have a .env file in my application and Im trying to run a script in docker. When docker reaches the entrypoint.sh it runs python manage.py runscript tryouts getting a count and then it goes like this (jwt_token is generated earlier in the script): ChirpStackURL = os.environ['CHIRPSTACK'] def checkNetworks(jwt_token): url = ChirpStackURL + '/api/network-servers?limit=10' res = requests.get(url, headers = {"Authorization": jwt_token}) count = res.json()['totalCount'] if count == '1' : return res.json()['result'][0]['id'] else: return False and then on my function i want to add the result as an enviromental variable so i can access it later on new requests. networkServerID = checkNetworks(jwt_token) if not networkServerID: print('success') else: 'export to .env file' 'NETWORK_ID = networkServerID' sample = os.environ['NETWORK_ID'] How do i do that ? -
Django queryset opposite of contains filter
here is my "Project" Model : class Project(models.Model): name = models.CharField(max_length=200, verbose_name="Project name", default="") I know how to use QuerySets to filter all the Project objects who contains "result" in their name (like this) : projects = Project.objects.filter(name__contains=result) (if I have three projects named "Hello", "Hello_World" and "Hi" and I do this : hello_projects = Project.objects.filter(name__contains="Hello") my QuerySet "hello_projects" will contains the projects named "Hello" and "Hello_World") I want to do it in the opposite way, and filter the projects who have their name in my result. For example, if "result" is "Hello_World_Its_Me", I want to get all projects who have their names inside result, so "Hello", and "Hello_World" Is there a way to do it ? -
how to connect auth0 database to django database with drf
So i'm trying auth0 with the django rest framework and in the documentation of connecting it with drf it only shows how to validate it but I couldnt find how to connect it to the django database. Dose anyone know how to do this -
Unable to get graphql's datetime in tenant's timezone
We are working on a multi tenant django app that needs to display datetimes in tenant's timezone. We achieve multitenancy using django-tenants, it separates tenants via Posgresql different schemas. We are using graphql through graphene to expose our APIs, and we would like to make this implementation transparent to it, thus avoiding to manipulate every datetime we receive in input with timezone.localtime(received_datetime). We've written a middleware that should do the job but graphene queries keep displaying the naive datetimes, to our understanding this is because django, while timezone aware, manage datetimes timezone only at forms and template levels, as per docs: https://docs.djangoproject.com/en/4.1/topics/i18n/timezones/ When support for time zones is enabled, Django stores datetime information in UTC in the database, uses time-zone-aware datetime objects internally, and translates them to the end user’s time zone in templates and forms. By looking at timezone.now and timezone.localtime(timezone.now) values we get the correct results, but every date we get from graphql is both aware and with django "from settings" timezone (UTC), instead of tenant's timezone: timezone.now(). # prints 2022-09-02 13:38:46.658864+00:00 timezone.localtime(timezone.now()) # prints 2022-09-02 22:56:16.620355+09:00 Querying graphql api instead outputs: "edges”: [ { “node”: { “id”: “UG9saWN5Tm9kZToxNQ==“, “createdAt”: “2022-09-01T13:55:04.542763+00:00" # in UTC timezone, instead of tenant's … -
Django - unable to test; "no such column"
I'm facing a weird issue that appeared out of the blue. My app works fine, all migrations are up to date and applied, and I am able to runserver. However, I noticed that when I try to run any tests, this is what happens (backend) samuelebonini@Samueles-MacBook-Pro-2 backend % ./manage.py test courses/tests Found 40 test(s). Creating test database for alias 'default'... Traceback (most recent call last): File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/db/backends/utils.py", line 89, in _execute return self.cursor.execute(sql, params) File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py", line 357, in execute return Database.Cursor.execute(self, query, params) sqlite3.OperationalError: error in index django_celery_results_taskresult_hidden_cd77412f after drop column: no such column: hidden The above exception was the direct cause of the following exception: Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/core/management/__init__.py", line 446, in execute_from_command_line utility.execute() File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/core/management/__init__.py", line 440, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/core/management/commands/test.py", line 24, in run_from_argv super().run_from_argv(argv) File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/core/management/base.py", line 402, in run_from_argv self.execute(*args, **cmd_options) File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/core/management/base.py", line 448, in execute output = self.handle(*args, **options) File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/core/management/commands/test.py", line 68, in handle failures = test_runner.run_tests(test_labels) File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/test/runner.py", line 1045, in run_tests old_config = self.setup_databases( File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/test/runner.py", line 941, in setup_databases return _setup_databases( File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/test/utils.py", line 220, in setup_databases connection.creation.create_test_db( File "/Users/samuelebonini/.local/share/virtualenvs/backend-tRSrcCVT/lib/python3.8/site-packages/django/db/backends/base/creation.py", … -
Django HTML Dropdown with multiple values filter
I have this below mentioned dropdown with multiple values for each option <div class="form-wrapper"> <label>Fruits Selected</label> <input type="text" readonly class="form-control" id="fruits_selected" name="fruits_selected" value="{{fruits_selected.product}}" /> </div> <div class="form-row last"> <div class="form-wrapper"> <label for="">Fruits Type</label> <select id="Fruits" name="Fruits" class="form-control"> <option disabled="disabled" selected="selected">Choose option</option> <option value="Mango,Apple,Orange"> Fresh Fruits</option> <option value="Onion,Tomato"> Vegetable</option> <option value="Apple,Beetroot,Carrot"> Diet Fruits</option> <option value="Apple,Grapes"> Healthy Fruits</option> <option value="Tomato,Mango"> Juice Items</option> </select> </div> </div> Via Django, I will get the fruits like Apple, Orange. If the input in the {{fruits_selected.product}} is Apple then in the dropdown, I need to get the options Fresh Fruits, Diet Fruits, Healthy Fruits since the dropdown value consist Apple Similarly, if the option in {{fruits_selected.product}} is Tomato then in the dropdown, I need to get the options Vegetable, Juice Items since the dropdown value consist Tomato -
How do I filter possible field values in django admin or at model level for fields linked through nested ForeignKey?
I have the two following models: class Question(models.Model): question_content = models.TextField(max_length=500) related to: class PossibleAnswer(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) answer = models.CharField(max_length=120) I would like to have a tree structure for a questionnaire, in which the option to go from one question or another might depend on the answer to the previous question. So I wanted to create another model as follows: class Relation(models.Model): child = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="child") parent = models.ForeignKey(Question, on_delete=models.CASCADE, related_name="parent") parent_answer = models.ForeignKey(PossibleAnswer, on_delete=models.CASCADE, related_name="parent_answer") Now the issue I have, is that in the django admin, when selecting through parent_answer, it gives me the possibility to select any answer. That is, not only the ones that are linked to the selected parent question (via a foreign key). I believe that the admin does not do dynamic filtering, but I would at least like the possibility to select on parent_answer is filtered once the parent question has been selected and the record saved. Or that this would somehow be enforced at the model level. Is this possible? Any help highly appreciated! -
Django - ProgrammingError - column does not exist
I normally find a solution around this problem. I even tried the nuclear option of resetting the data base completely with python manage.py flush but no luck. the exact error message is the following: column main_reviewrating.venue_id does not exist Maybe it's the first time I pay attention to this but the venue**_id** seems strange. I am quite sure the usual message would have something like main_reviewrating.venue (without the _id When I run python manage.py showmigrations <your_app_name> it does show [X] 0001_initial I should also add that I am running this on my local, so no problem specific to deployment. Here is the code (models.py) class Venue(models.Model): name = models.CharField(verbose_name="Name",max_length=100, null=True, blank=True) def __str__(self): return str(self.name) if self.name else '' class Product(models.Model): name = models.CharField('Product Name', max_length=120, null=True) class Meta: db_table='Product' def __str__(self): return str(self.name) class ReviewRating(models.Model): user = models.ForeignKey(User,blank=True, on_delete=models.CASCADE, related_name="usercomments") product=models.ForeignKey(Product,related_name="comments", on_delete=models.CASCADE) review =models.TextField(max_length=250) rating =models.IntegerField(choices=RATING, default=0) venue = models.ForeignKey(Venue, blank=True, null=True, related_name="venues", on_delete=models.CASCADE) def __str__(self): return '%s - %s'%(self.user, self.product) Any idea what I am doing wrong? -
Method Not Allowed (POST): /items/
So i'm trying to do a filter with django, to filter the items on the main page. A little context: An item can be assigned to a user or not. I want a filter, to see what items are assigned and which items aren't. This is my function in views.py: class ItemsView(ListView): template_name = 'inventory/items.html' context_object_name = 'items_list' def get_queryset(self): if (self.request.user.is_authenticated): if self.request.method == "get": searched = self.request.GET.get('searched') if searched == "None": return Item.objects.filter(assigned_user__isnull=True, company=getCompany(self.request.user)) else: return Item.objects.filter(assigned_user__isnull=False, company=getCompany(self.request.user)) else: return Item.objects.filter(company=getCompany(self.request.user)) And this is from my items.html: <form method="post" action="/items"> {% csrf_token %} <select name="item_filter"> <option value="None">Not Checked In</option> <option value="Checked_In">Checked In</option> </select> <input type="submit" value="filter"> </form> So basically what i want is, that the user can pick one of the two choices in the dropdown-menu, and the items should be listed based on the choice he made. When i use this form and click the submit button, the screen gets white and in my console, the error Method Not Allowed (POST): /items/ appears. Has this something to do with the fact i'm using the generic.ListView for my view? Thank you -
How should I change Parameter content type in swagger - django
I'm using the following serializer class to generate swagger UI. from rest_framework import serializers from django.contib.auth.models import User class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('username', 'password') The problem is my views accept form data but when using swagger UI to send requests, it sends json instead of form data. Is there any way to change Parameter content type in swagger? -
UTF-8 cannot decode ReportLab pdf
I'm having an issue regarding the decoding of pdf generated by reportlab library. Here is the code calling my function: print('Rendering Report and Sending Mail') r = renderTestPDF() sendTestPDF(r) This is the code creating the PDF: def renderTestPDF(): canvas = Canvas('hello.pdf') canvas.drawString(72, 72, "Hello, World") content = canvas.getpdfdata() return content This is the code sending the email and where I am getting the error: def sendtestpdf(report): # Variables For The Server emailhost = '' emailport = '' # Variables For The Email systemEmail = '' password = '' recieveremail = '' # Configure The Email Message message = MIMEMultipart() message["Subject"] = 'This is a test for pdf creation and attachment' message["From"] = systemEmail message["To"] = recieveremail html = """ <h1>Your report is here!</h1> """ # Turn The Message Into A MIME Object part1 = MIMEText(html, "html") **---- I THINK THIS IS WHERE THE ERROR IS LYING -----** binary_pdf = open(report, "rd") payload = MIMEBase('application', 'octate-stream', Name="Test.pdf") payload.set_payload((binary_pdf).read()) encoders.encode_base64(payload) payload.add_header('Content-Decomposition', 'attachment', filename='Test.pdf') # Add HTML/plain-text parts to MIMEMultipart message message.attach(part1) message.attach(payload) # Create Secure Connection with Server and Send Email context = ssl.create_default_context() with smtplib.SMTP_SSL(emailhost, emailport, context=context) as server: server.login(systemEmail, password) server.sendmail(systemEmail, recieveremail, message.as_string()) and lastly, this is the error I'm … -
How to solve FOREIGN KEY constraint failed ? DJANGO
I'm having a FK problem and I don't know if it's a problem with migrations or a diagram. Below are the models of my e-commerce. Where there are two types of users, Customers and Supermarkets. Each type can only assume one role. And each supermarket can have several products. The error happens when I associate a supermarket with a product. There is an error with my diagram ? products/models.py class Categoria(models.Model): nome = models.CharField(max_length=50) def __str__(self): return self.nome class Produto(models.Model): name = models.CharField(max_length=70) price = models.FloatField() qnt_stock = models.IntegerField() sold = models.IntegerField() category = models.ForeignKey(Categoria, on_delete=models.CASCADE) description = models.TextField(default="", blank=True, null=True) slug = models.SlugField(unique=True) image = models.ImageField(upload_to="products/%Y/%m/%d", blank=True, null=True) expiration_date = models.DateTimeField(null=True, blank=True) supermarket = models.ForeignKey( Lojista, on_delete=models.CASCADE, blank=True, null=True ) def __str__(self): return self.name def get_absolute_url(self): return reverse("produtos:produto_detail", kwargs={"slug": self.slug}) users/models.py class CustomUser(AbstractUser): class Role(models.TextChoices): SUPERMARKET = "SUPERMARKET", _("Supermarket") CLIENT = "CLIENT", _("Client") role = models.CharField(max_length=50, choices=Role.choices) def __str__(self): return self.username class Client(models.Model): user = models.OneToOneField(CustomUser, on_delete=models.CASCADE, primary_key=True) def __str__(self): return self.user.username class Lojista(models.Model): def upload_photo_to(instance, filename): return f"brand/{instance.name}/{filename}" supermarket = models.OneToOneField( CustomUser, on_delete=models.CASCADE, primary_key=True ) brand = models.ImageField(upload_to=upload_photo_to, blank=True, null=True) cep = BRPostalCodeField() state = models.CharField(choices=br_states.STATE_CHOICES, max_length=2, null=False) city = models.CharField(max_length=128, null=False) district = models.CharField(max_length=128, null=True) street = … -
Nasting tables in serializer showing Null
Hi everyone I getting null I have a following: serializer class MeasurmentsSerializer(serializers.ModelSerializer): class Meta: model = Measurements fields = ('measurementid','measurement') class DeviceSerializer(serializers.ModelSerializer): lastmeasurementid = MeasurmentsSerializer(db_column='measurementTime') class Meta: model = Devices fields = ("devicename", 'deviceid', 'lastmeasurementid') Models -
"Python not found" after VSCode upgrade
I am using VSCode 1.52.1 to work with Python 3.9.1 and Django. I had to upgrade VSCode to 1.71.0 and when I run Django, I get the following error: VSCode terminal error messages Nothing changed with Python. Software installed, paths are the same. Do I need to change the JSON configuration file? Can someone help me solve this issue? Thanks and best regards, -
I need to run a background request on django app, what is the best way to do this
In index.html I have a form that accept files <form method="post" enctype="multipart/form-data" action=""> {% csrf_token %} {{ form }} <button type="submit" class="btn btn-primary dropdown-toggle">Start Validation</button> </form> Then my app runs some functions to processes these files The problem is that the page keeps loading and waits for the return response my views.py class MainView(View): def get(self, request): form = UploadFileForm() return render(request, 'myapp/index.html', {'form':form}) def post(self, request): form = UploadFileForm(request.POST, request.FILES) if form.is_valid(): uploadedFile = request.FILES['file'] function_to_processes_the_file(fil=request.FILES['file']) # Takes some time return redirect('/') So my question is how can I make it process the file in the background without the need to wait for a response, will it need javascript ? -
Django Python Foreign Key issue
I am showing "well" information linked to a specific project successfully based on well_id When I try to show drilling_tools in a similar fashion I get an error. Can anyone see what I am doing wrong in my views? def well_show(request, well_id): well = Well.objects.get(pk=well_id) drilling_tools = DrillingTool.objects.get(pk=well_id) return render(request, 'geodata/well_show.html', {'well': well, 'drilling_tools': drilling_tools}) -
NOT FOUND Not Found: /docs/4.3/dist/js/bootstrap.bundle.min.js IN A DJANGO PROJECT
Not Found: /docs/4.3/dist/js/bootstrap.bundle.min.js while submitting a form in a django project , this comes up and no data is stored in database. GET /docs/4.3/dist/js/bootstrap.bundle.min.js HTTP/1.1" 404 3019(this comes in the terminal)