Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 61] Connection refused
I am trying to run celery without running RabbitMQ. But this repo I am working on has these two lines CELERY_BROKER_URL = 'amqp://localhost' # for RabbitMQ CELERY_RESULT_BACKEND = 'rpc://' # for RabbitMQ which gives me this error consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 61] Connection refused. How can I run celery successfully without RabitMQ I tried running celery without RabbitMQ but failed -
Django - Prefill admin creation form with inline forms
I'm trying to create a form in Django admin, that, when you create a new entry, will take the latest entry, and fill the new entry with that data. E.g. (Book and Author are just examples) class Book(models.Model): id = models.Autofield(primary_key=True) author = models.ForeignKey(Author, on_delete=models.CASCADE) name = models.Charfield(max_length=200) class Author(models.Model): id = models.Autofield(primary_key=True) name = models.Charfield(max_length=200) I then added this to the admin page: class BookInline(StackedInline): model = Book extra = 0 class AuthorAdmin(ModelAdmin): inlines = [BookInline] admin.site.register(Author, AuthorAdmin) Now when I create a new Author, I want the form to be filled in with the last created author and his books So if said author had 5 books, it would now fill this form with the name of that author, and also add the 5 books. I was able to fill the author form by adding this to the AuthorAdmin class: def get_changeform_initial_data(self, request): return model_to_dict(Codebook.objects.all().get())#Temp But the books are not filled this way. Is it somehow possible, to pass the books into the inline forms? (Running Django 3.2 and Python 3.9) -
Correct way to add dynamic form fields to WagtailModelAdminForm
I have a use case where I need to add dynamic form fields to a WagtailModelAdminForm. With standard django I would normally just create a custom subclass and add the fields in the __init__ method of the form. In Wagtail, because the forms are built up with the edit_handlers, this becomes a nightmare to deal with. I have the following dynamic form: class ProductForm(WagtailAdminModelForm): class Meta: model = get_product_model() exclude = ['attributes', 'state', 'variant_of'] def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) if self.instance: self.inject_attribute_fields() def inject_attribute_fields(self): for k, attr in self.instance.attributes.items(): field_klass = None field_data = attr.get("input") field_args = { 'label': field_data['name'], 'help_text': field_data['help_text'], 'required': field_data['is_required'], 'initial': attr['value'], } if 'choices' in field_data: field_args['choices'] = ( (choice["id"], choice["value"]) for choice in field_data['choices'] ) if field_data['is_multi_choice']: field_klass = forms.MultipleChoiceField else: field_klass = forms.ChoiceField else: typ = field_data['attr_type'] if typ == 'text': field_klass = forms.CharField elif typ == 'textarea': field_klass = forms.CharField field_args['widget'] = forms.Textarea elif typ == 'bool': field_klass = forms.BooleanField elif typ == 'int': field_klass = forms.IntegerField elif typ == 'decimal': field_klass = forms.DecimalField elif typ == 'date': field_klass = forms.DateField field_args['widget'] = AdminDateInput elif typ == 'time': field_klass = forms.TimeField field_args['widget'] = AdminTimeInput elif typ == 'datetime': field_klass = forms.DateTimeField … -
Only allow specific url
The user can type an URL like this https://music.apple.com/us/artist/billie-eilish/1065981054. But the us in the URL can also be de or ru (depending on artist). Some URLs can also be written like this https://www.example.com. How can I check if the users typed URL is build like this example URL? -
Download videos from a remote site with PyhtonDownload videos from a remote site with Pyhton
Hello I want to download videos from x one site locale with pyhton, when I search the Internet I only download the video at the given address, can you help this process how to pull videos from http traffic while browsing within a single site Hello I want to download videos from a site x locale with pyhton, when I search the Internet, it only downloads the video at the given address, how can you help me pull videos from http traffic while browsing within a single site? -
Send data in a complete tree structure using django serializers
I have 2 models: Folder and Entity. class Folder(models.Model): name = models.CharField(max_length=255, null=False, blank=False) parent = models.ForeignKey('self', on_delete=models.SET_NULL, null=True, blank=True, related_name="child") class Entity(models.Model): name = models.CharField(max_length=255, null=False, blank=False) folder = models.ForeignKey('Folder', on_delete=models.SET_NULL, null=True, blank=True, related_name="entities") So a folder can have both child folders and entities. Now I want to send the data in a tree structure and I have written a serializer for it. class ListFolderSerializer(serializers.ModelSerializer): children = serializers.SerializerMethodField() class Meta: model = Folder fields = ['id', 'name', 'children'] def get_children(self, instance): child_folders = Folder.objects.filter(parent=instance).order_by("name") child_entities = Entity.objects.filter(folder=instance).order_by("name") all_children = [] if child_folders or child_entities: child_folders_data = ListFolderSerializer(child_folders, many=True).data child_entities_data = ListEntitySerializer(child_entities, many=True).data all_children.extend(child_folders_data) all_children.extend(child_entities_data) return all_children else: return None class ListEntitySerializer(serializers.ModelSerializer): class Meta: model = Entity fields = ['id', 'name'] This is working fine but as the data keep on increasing the time to get this tree is increasing. So any optimized way to do this? -
Display records with respect to their id's in Django
My Django application includes a page named list in which list creates against a user to after analysis of .pcap file: The problem is I want to display the results on the basis of id in hash table. The id in hash_mod table has one to many relationships. Therefore, It'll be easy for me to fetch the results on the basis of id. How I will use the primary key (id in hash_mod) table to link through foreign key (hash_id in demo) table to fetch the results. I have also share the image url to view the list.html what it looks like. In list.html there is a button named "View" which is using the post method. There is for loop in list.html which recognize the total number of files analyzed by a user. When a user will analyze a file an id and hash will create in "hash_mod" table which I have mentioned below. Id will treat as a foreign key in another table, so I want to fetch the result witch respective to their primary key id and foreign key id. if anyone have still problem to understand the question anyone can ask. But please don't give a negative … -
How can I filter groups based on user_id in django-template-language
how can I filter the groups based on the user in Django-template-language with if else condition <tbody> {% for group in groups %} <tr> <td>{{group.name}}</td> <td><input type="checkbox" name="add_group[]" id="group-{{group.id}}" value=" {{group.id}}" checked ></td> </tr> {% endfor %} </tbody> -
How to log requests in Django Rest Framework?
I am using middleware to log requests: class RequestsMiddleware(MiddlewareMixin): def __init__(self, get_response): self.get_response = get_response def __call__(self, request): logger.info(request) logger.debug(request.body) response = self.get_response(request) return response If I send an image to the server: response = self.client.post( self.url, data={ 'id': user_id, 'photo': open(f'{test_data}/image.jpeg', 'rb'), 'licenses': [f'{self.license_id}'],}, format='multipart', HTTP_AUTHORIZATION=f'{token}') logger.debug(request.body) shows something like: b'--BoUnDaRyStRiNg\r\nContent-Disposition: form-data; name="id"\r\n\r\ndbdeb624-fba8-4718-819c-b6c4eb358dbf\r\n--BoUnDaRyStRiNg\r\nContent-Disposition: form-data; name="photo"; filename="image.jpeg"\r\nContent-Type: image/jpeg\r\n\r\...\r\n--BoUnDaRyStRiNg\r\nContent-Disposition: form-data; name="licenses"\r\n\r\ncbe1ed8f-52eb-4089-b66b-ea01fc9e450g\r\n--BoUnDaRyStRiNg--\r\n' This message is unreadable. Is there a way to format the message? -
Field 'id' expected a number but got 'POST'
This is my view: def edit_bendrija_view(request, bendrija_id): """ A view to edit Bendrijos name """ bendrija = get_object_or_404(Bendrija, id=bendrija_id) if request.method == 'POST': existing_bendrija = BendrijaForm(request.POST, instance=bendrija) if existing_bendrija.is_valid(): existing_bendrija.save() messages.success(request, "Your Bendrija Was Updated") return redirect(reverse('bendrijos')) else: messages.error(request, "Your Bendrija Was Not Updated") existing_bendrija = BendrijaForm(instance=bendrija) context = { 'existing_bendrija': existing_bendrija, "bendrija": bendrija, } return render(request, 'home/edit_bendrija.html', context) I am trying to edit an existing model using a form, the model only has 2 CharFields so its very simple, everything works up until I click the submit button, then the error that is the title comes up, and I am completely lost, especially because the error says the problem is on the "bendrija = get_object_or_404(Bendrija, id=bendrija_id)" line, this is the form if you are wondering: <form action="POST"> {% csrf_token %} <div class="row"> {{ existing_bendrija.name | as_crispy_field }} </div> <div class="row"> {{ existing_bendrija.address | as_crispy_field }} </div> <div> <p> <button type="submit" class="btn btn-success">Submit</button> </p> </div> </form> any suggestions? because I have 0 idea why the id is getting the request method and not the model id -
Pylint is not able to locate the model in the context of the views.py file
I'm using VSCode and the Pylint that ships with it, i.e., no extension. Everything has been running smooth for many months and I've never had an issue with Pylint presenting weird alerts. I recently started learning Django and today when following the official Django Documentation tutorial part 4 pylint could not recognize a couple of statements related to a model. Pylint can't recognize the (choice_set) method below selected_choice = question.choice_set.get(pk=request.POST['choice']) Pylint can't recognize (question.id) below return HttpResponseRedirect(reverse('polls:results', args=(question.id,))) The errors I get from pylint are below choice_set: Unknown Cannot access member "choice_set" for type "Question" Member "choice_set" is unknownPylancereportGeneralTypeIssues and id: Unknown Cannot access member "id" for type "Question" Member "id" is unknownPylancereportGeneralTypeIssues At first I thought the issue might've been I'd forgot to cross reference the Question and Choice models, but this is not the case. For reference, here are the related files for the project #models.py from django.db import models from django.utils import timezone import datetime class Question(models.Model): question_text = models.CharField(max_length=200) pub_date = models.DateTimeField('date published') def __str__(self): return self.question_text def was_published_recently(self): return self.pub_date >= timezone.now() - datetime.timedelta(days=1) class Choice(models.Model): question = models.ForeignKey(Question, on_delete=models.CASCADE) choice_text = models.CharField(max_length=200) votes = models.IntegerField(default=0) def __str__(self): return self.choice_text #views.py from .models import Choice, … -
ValueError: Expected a boolean type django and mysql
I can't start my django with mysql, it's inside docker and it gives me a valueerror that I don't know how to fix self.raise_on_warnings = config["raise_on_warnings"] File "/usr/local/lib/python3.10/site-packages/mysql/connector/abstracts.py", line 937, in raise_on_warnings raise ValueError("Expected a boolean type") ValueError: Expected a boolean type -
Django database object save() fails silently [closed]
I have a bug which is not reproducible and occurs rarely. Get object of the database: db_obj= My_Db_Model.objects.get(ID=id_from_param) # called always with same id_from_param Modify fields like: db_obj.value = 123 db_obj.save() No. 3 is surrounded by try, except (Exception), which means it applies for all exceptions and it should log the exception. Most of the times it works, but sometimes the value is not updated, without having any exception. Could there be some explanation how this could happen and under which circumstances it could fail silently like this? It is a postgresql database and I was also not able to figure out something from the database logs. Maybe there is a way to check if the database works correctly? -
How to display data frame in template page using django
I am trying to populate my data frame in Django, But I am getting a blank page. Here I am sharing my sample code <html> <head> <title>API Display</title> </head> <body> <h1>List of Data </h1> {% for i in d %} <strong>{{i}}</strong> {% endfor %} </body> </html> def index(request): url = "http://153.24.76.45:9000/abc/" response = requests.get(url) z = response.json() # df = z.reset_index().to_json(orient ='records') df = pd.DataFrame(z['Result']['LSData']) context = {'d': df} return render(request,'index.html',context) can anyone help me to solve this problem ? -
Why don't bootstrap codes run on my django website?
Hello I'm having trouble applying bootstrap to my website in django. I copied the bootstrap link in the html page and wrote the navbar codes in the body part, but when I hit runserver, the website page doesn't change at all! where is the problem from? I also installed the bootstrap plugin in Visual studio code, but it still doesn't change anything! Thank you for your guidance The** navbar** should have applied to my page, but it didn't I use visual studio code and django framework -
Trying to render two different views in one template according to their specific url routing
Im trying to render login and register view in a single template using variable assignment and if-else. I'm sorry if its a rookie mistake, Im pretty new to this.. github repo- https://github.com/varundhand/DevSearch my urls.py :- urlpatterns = [ path('login/',views.loginUser,name='login'), path('logout/',views.logoutUser,name='logout'), path('register/',views.registerUser,name='register'), path('',views.profiles,name='profiles'), path('profile/<str:pk>/',views.userProfile,name='user-profile'), ] my views.py :- def loginUser(request): page = "login" if request.user.is_authenticated: return redirect('profiles') if request.method == 'POST': username = request.POST.get('username') password = request.POST.get('password') try: user = User.objects.get(username=username) except: messages.error(request,'Username doesnt exist') user = authenticate(request,username=username,password=password) if user is not None: login(request,user) return redirect ('profiles') else: messages.error(request,'Username/Password incorrect') context = {page:'page'} return render(request, 'users/login_register.html', context) def logoutUser(request): logout(request) messages.error(request,'User was logged out!') return redirect('login') def registerUser(request): page = "register" context= {page:'page'} return render(request,'users/login_register.html', context) my html template file :- {% extends 'main.html' %} {% block content %} {% if page == "register" %} <h1>Register User</h1> <p>Already have an account? <a href="{% url 'login' %}">Login</a> </p> {% else %} <form action="{% url 'login' %}" method="POST"> {% csrf_token %} <input type="text" name="username" placeholder="Username"> <input type="pass`your text`word" name="password" placeholder="Enter Password"> <input type="submit" value="Login"> <p>Dont have an account? <a href="{% url 'register' %}">Sign Up</a></p> </form> {% endif %} {% endblock content %} My Approach I gave variable assignment of page='login' and page='register' in … -
Error "Expecting value: line 1 column 1 (char 0)" in postman while generating token through a post Api
@api_view(["POST"]) @permission_classes([AllowAny]) def LoginView(request): data = {} details = request.body reqBody = json.loads(details) username = reqBody['username'] password = reqBody['password'] Inside 'details' I am getting a Form-Data instead of string due to which getting above error if any suggestion . How to convert 'form-data' in 'string' Or directly convert 'form-data' to 'string' I tried details = request.body reqBody = json.loads(details.decode('utf-8') But it gives the same error . -
npm dev run generates huge main.js file
I have a Django application and trying to rewrite my JS frontend to React. I found some tutorial how to organize the structure of React app: frontend/ static/frontend/main.js/main.js src/ index.js components/App.js package.json { "name": "frontend", "version": "1.0.0", "description": "", "main": "index.js", "presets": [ "@babel/preset-env", "@babel/preset-react" ], "scripts": { "dev": "webpack --mode development ./src/index.js --output-path ./static/frontend/main.js", "build": "webpack --mode production ./src/index.js --output-path ./static/frontend/main.js", "test": "echo \"Error: no test specified\" && exit 1" }, "keywords": [], "author": "", "license": "ISC", "devDependencies": { "@babel/core": "^7.20.12", "@babel/preset-env": "^7.20.2", "@babel/preset-react": "^7.18.6", "babel-loader": "^9.1.2", "react": "^18.2.0", "react-dom": "^18.2.0", "webpack": "^5.75.0", "webpack-cli": "^5.0.1" }, "dependencies": { "fs-promise": "^2.0.3" } } webpack.config.js module.exports = { devtool: false, module: { rules: [ { test: /\.js$/, exclude: /node_modules/, use: { loader: "babel-loader", options: { presets: ['@babel/env','@babel/preset-react'] }, } } ] } }; index.html <!DOCTYPE html> <html> <head> <meta charset="utf-8"> <meta name="viewport" content="width=device-width, initial-scale=1"> <title>Django REST with React</title> </head> <body> <h1>Anything</h1> <div id="app"> <!-- React will load here --> </div> </body> {% load static %} <script src="{% static "frontend/main.js/main.js" %}"></script> </html> sample code in App.js import React from 'react'; import ReactDOM from 'react-dom'; function App() { const [value, setValue] = React.useState(0); function increment() { setValue(value + 1); } return ( <div … -
how to run specific test files from tests folder in django?
I'm doing some api testing I have these files in it tests/test_one.py tests/test_two.py how can I test a single file using python manage.py test -
Getting " ValueError: No route found for path 'socket/order' ' " in Django Channels when trying to connect with Angular frontend
I am trying Django Channels for the first time. I am trying to connect it with an existing Angular frontend application. But for some reason the routing isn't working I cannot figure out why. I have written the codes exactly how the Django Channels documentation instructs to. The error message goes as such - Watching for file changes with StatReloader Performing system checks... System check identified no issues (0 silenced). January 10, 2023 - 15:34:50 Django version 4.1.3, using settings 'BrokerBackEnd.settings' Starting ASGI/Daphne version 4.0.0 development server at http://127.0.0.1:8000/ Quit the server with CTRL-BREAK. WebSocket HANDSHAKING /socket/order [127.0.0.1:63732] HTTP GET /orders/ 200 [0.07, 127.0.0.1:63731] Exception inside application: No route found for path 'socket/order'. Traceback (most recent call last): File "C:\Users\Neha\Documents\broker-back-end-py\env\lib\site-packages\django\contrib\staticfiles\handlers.py", line 101, in __call__ return await self.application(scope, receive, send) File "C:\Users\Neha\Documents\broker-back-end-py\env\lib\site-packages\channels\routing.py", line 62, in __call__ return await application(scope, receive, send) File "C:\Users\Neha\Documents\broker-back-end-py\env\lib\site-packages\channels\routing.py", line 134, in __call__ raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'socket/order'. WebSocket DISCONNECT /socket/order [127.0.0.1:63732] Would really appreciate if anyone could suggest anything. Thank you. settings.py INSTALLED_APPS = [ 'daphne', 'channels', 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', 'corsheaders', 'rest_framework', 'Orders' ] ASGI_APPLICATION = 'BrokerBackEnd.asgi.application' asgi.py import os from django.core.asgi … -
Is Supervisor needed?
So I've started to use django with SQS to run tasks at a given time where the celery-broker and beat start at deployment. Now Since I'm using autoscaling if an instance fails and gets replaced will the worker and beat start again ? I've seen that a solution could be to have a supervisor . Can anyone shine some lights there ? Not sure what's the best approach . Many Thanks -
Django: Database column not updating from variable, taking it as hardcoded name
I have the following code for updating a database column. def update_itemamadeus(check_flight_differences): for item_id, flight_details in check_flight_differences.items(): for field, value in flight_details.items(): ItemAmadeus.objects \ .filter( Q(id=item_id) ) \ .update( field = value ) return It's taking 'field' not as the variable it should be which is 'code_airport_from_id'. item_id = 130 field = code_airport_from_id value = BCN The dreaded yellow screen error: Can this be achieved? -
I am using Django and I want encrypt my data such us URLs is there any way to do that
I am using Django can someone help me to encrypt my data I want do encrypt my data but I do not know how to do it I am using Django and flutter and I want to encrypt my data to not be readable by any one is there any way to do that I want to get answer please can someone help me -
Count django records and list them
I want to get the list and count of houses under a location How to do it in djano do you have any idea Tables are frontend_property and frontend_locations how to join and get the result in django -
Dynamically add input field with select option tag based on chosen model
<script> $(document).ready(function(){ $("#experienceNo").on("change",function(){ var numInputs = $(this).val(); $('#experienceSection').html(''); for(var i=0; i < numInputs; i++) { var j = i*1; var $section = $('<div class="form-group"><label for="" class="col-4 col-form-label">Company Name '+j+'</label><div class="col-6"><input type="text" name="companyname[]" class="form-control" required></div></div>'); $('#experienceSection').append($section); } }); }); </script> <div class="col-6"> <select name="experienceNo" id="experienceNo" class="custom-select mb-2 mr-sm-2 mb-sm-0"> <option value="">Select Value</option>`enter code here` <option value="0">0</option> <option value="1">1</option> <option value="2">2</option> <option value="3">3</option> <option value="4">4</option> <option value="5">5</option> </select> </div> </div> I want to make dynamically add input field with select option tag based on chosen model, but the option didnt appear, even after i was selected the value model How to make options dynamically appear based on chosen model option?