Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
data doesn't show on django template
My Views enter image description here My Template enter image description here My Result enter image description here my data enter image description here how i solve it data on django template doesn't show but when i change it is a number it changed -
Django: Deleting multiple objects with a view that requires a object pk?
Hey I got this Code to remove my keys: class AKeysRemove(DeleteView, ProgramContextMixin): model = AKeys template_name = 'administration/keys/remove.html' def dispatch(self, request, *args, **kwargs): return super(AKeysRemove, self).dispatch(request, *args, **kwargs) def get_success_url(self): return reverse('akeys_index', args=[self.get_program_id()]) def delete(self, request, *args, **kwargs): # Get the query parameters from the request is_active = request.GET.get('is_active') category = request.GET.get('category') # Build a Q object to filter AccessKeys by is_active and category q_filter = Q() if is_active is not None: q_filter &= Q(is_active=is_active) if category is not None: q_filter &= Q(category=category) # Check if there are any filters has_filters = is_active is not None or category is not None # Delete the AKeys that match the filter, or just the one AKey if has_filters: queryset = self.get_queryset().filter(q_filter) deleted_count, _ = queryset.delete() if deleted_count == 1: messages.success(request, f"One AKey deleted.") else: messages.success(request, f"{deleted_count} AKeys deleted.") else: obj = self.get_object() obj.delete() messages.success(request, f"AKey {obj} deleted.") return redirect(self.get_success_url()) My url looks like this: re_path(r'^p/(?P<p_id>[0-9]+)/keys/(?P<pk>[0-9]+)/delete/?$', AKeysRemove.as_view(), name='akeys_delete'), Deleting one Single Key works fine, but I build myself a filter to delete Keys from a certain category or if they're active or not (is_active) <div class="row" style="margin-top: 10px"> <div class="col-md-12"> <form method="POST" action="{% url 'akeys_delete' p.id %}" id="delete-akeys-form"> <div class="form-group"> <label for="category-filter">Category:</label> <select … -
Microservices Architecture Django
I am new to microservices architecture. I have a microservice (A) responsible for registering and logging in users. And, I have another microservice (B) responsible for storing the bookings, order form the logged in user. Both microservices (A) and (B) are having a separate database. How can I store the user bookings and orders on microservice (B) based on microservice (A) using a Rest API? I'm using Django Rest framework to build my system. I am unsure how to maintain an interface between two databases. I need guidance with the best approaches to sync data to microservice (B) when a user from microservice (A) make a booking or order -
Django Form - Pass Extra Arguments (Dynamic Form Creation)
I am trying to pass extra parameters (not provided by the Forms) in customize my template In this case I am passing an icon font. class AddForm(forms.Form): def __init__(self, *args, **kwargs): *passing some args* self.fields[field_key] = forms.CharField(**field_args) self.fields[field_key].icon = 'fa-font' template.html {% for field in form%} {{field.icon}} {{field}} {% endfor %} When I render the form to to the view, no icon is printed out. How can I pass extra parameters to a form field? -
DRF Allow AnonymousUser owner with HyperlinkedModelSerializer
When the book owner is authenticated it's ok, but if the book owner is not authenticated this error appears ValueError: Cannot assign "<django.contrib.auth.models.AnonymousUser object at 0x000002677F18EE00>": "Book.owner" must be an instance of " CustomUser".. I think this problem is caused by HyperlinkedModelSerializer. The owner of the book is specified in the perform_create() method, which is taken from self.request.user. I want authenticated users or non-authenticated users to be able to create books. models.py class Book(models.Model): owner = models.ForeignKey( settings.AUTH_USER_MODEL, blank=True, null=True, # allow Anonymous user on_delete=models.CASCADE, related_name="books", ) title = models.TextField() serializers.py class BookSerializer(serializers.HyperlinkedModelSerializer): owner_username = serializers.ReadOnlyField(source="owner.username") class Meta: model = Book fields = ( "url", "owner", "owner_username", "title", ) read_only_fields = ("owner",) views.py class BookViewSet(viewsets.ModelViewSet): serializer_class = BookSerializer queryset = Book.objects.all() def perform_create(self, serializer): serializer.save(owner=self.request.user) I need your help to fix this problem. Thanks in advance. -
Password shown twice for django register form
I am making django register form, but it shows the password twice. (three times including password conformation) Does anyone figure out the reason> These are source code below. register.html {% extends "defapp/base.html" %} {% block title %}User Register{% endblock %} {% block content %} <form method="POST" class="form-group"> {% csrf_token %} {{ form.as_p }} <button type="submit" class="btn btn-success">Register</button> </form> {% endblock %} RegisterView Class class RegisterView(CreateView): form_class = f.RegisterForm template_name = "defapp/register.html" success_url = reverse_lazy("top") def form_valid(self, form): user = form.save() login(self.request, user) self.object = user return HttpResponseRedirect(self.get_success_url()) class Login(LoginView): form_class = f.LoginForm template_name = 'defapp/login.html' class Logout(LoginRequiredMixin, LogoutView): template_name = 'defapp/login.html' RegisterForm is here. from django.contrib.auth.forms import AuthenticationForm,UserCreationForm from django.contrib.auth.models import User class LoginForm(AuthenticationForm): def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) for field in self.fields.values(): field.widget.attrs['class'] = 'form-control' field.widget.attrs['placeholder'] = field.label class RegisterForm(UserCreationForm): class Meta: model = User fields = ["username", "password", "email"] -
How to take the data (in for loop) that is output in the terminal and show it on a web page?
I want to make a page where text is entered, and then a function that outputs synonyms of words from this text. My view.py is: def home_view(request): if request.method == "POST": text = request.POST["translate"] print(text) translator = Translator() translate_text = translator.translate(text, src='auto', dest='en') print(translate_text.text) Text = translate_text.text.lower().replace('.', '') word_list = Text.split() # print(word_list) for word in word_list: synonyms = get_some_word_synonyms(word) kk_word = translator.translate(word, src='auto', dest='en') kk_word = kk_word.text if synonyms: print( kk_word, 's synonym is:') for synonym in synonyms: # print(synonym) translate_text = translator.translate(synonym, src='auto', dest='en') print(" ", translate_text.text) return render(request,'index.html') I have this output in terminal. Wanna make web page were you can see something like this. Procedures and systems for identifying and eliminating malfunctions and malfunctions of equipment, networks and systems procedures s synonym is: procedure process systems s synonym is: system identifying s synonym is: identify place eliminating s synonym is: extinguish eliminate get rid of do away with malfunctions s synonym is: malfunction malfunctions s synonym is: malfunction networks s synonym is: network web systems s synonym is: system -
Django REST framework Query Throughput on AWS
I've trying to run a simple django server on amazon lightsail. The server is supposed to be a backend that serves game state to twitch viewers via an extension. I'm currently trying to have each viewer poll my backend every second. Trying a very bear bones read to start I'm essentially storing the game state in memory using django's cache (there's only one tracked 'player' for now) and serving it back to users via the django REST framework. Given that my requests and responses are quite small I'd expect to easily serve at least a few hundred users but I seem to top out of the sustainable CPU usage at around 50 users. Is this expected for this setup? Are there optimizations I can make or obvious bottlenecks? Here's my backend that gets polled every second https://github.com/boardengineer/extension Normal backend reads come in at about 800 bytes. I tried returning empty responses to test if the response size should be optimized but it only made a small difference. I thought of removing header content to further reduce response size but I don't think i found a way to do so correctly. I also tried removing some of my middleware hoping to … -
How to pass change_password.html to replace Django Admin Password Reset
Currently in my urls.py I have the following links for user to reset their password app_name = 'users' .............. path('login/', MyLoginView.as_view(redirect_authenticated_user=True,template_name='users/login.html'), name='login'), path('password/', user_views.change_password, name='change_password'), ............................. ............................. ............................... path('password-reset-complete/', auth_views.PasswordResetCompleteView.as_view(template_name='users/password_reset_complete.html'),name='password_reset_complete'), After the user receives the reset email and clicks on the link to reset password it goes to the Django Admin Style page to reset password. How can I pass the template that I have change_password.html and how can I redirect afterwards to the login page to login -
Form shows wrong date format while changing element in Django
I need the date format dd-mm-yyyy and I changed it everywhere. The date in the list of elements shows correctly. The database also has a requirement to enter the date in this format. However, when I try to modify an existing element, the form shows a date in the format yyyy-mm-dd and I have to change the date to dd-mm-yyyy each time to make changes to the element, otherwise an error occurs. How can I make the date displayed in the format dd-mm-yyyy by default when editing an element? forms.py class CaseRequestForm(forms.ModelForm): class Meta: model = CaseRequest fields = ('name', 'datebirth') widgets = { 'name': forms.TextInput(attrs={'class': 'form-control'}), 'datebirth': forms.TextInput(attrs={'class': 'form-control'}), } Models.py class CaseRequest(models.Model): name = models.CharField('Put full name',max_length=255) datebirth = models.DateField('Put date in dd.mm.yy format') def __str__(self): return self.name def get_absolute_url(self): return reverse('caserequest') @property def case_exists(self): return Case.objects.filter(name=self.name, datebirth=self.datebirth).exists() Views.py class UpdateCaseRequestView(UpdateView): model = CaseRequest form_class = CaseRequestForm template_name = 'add_caserequest.html' update_caserequest.py <div> <form method="POST"> {% csrf_token %} {{form.as_p}} <button class="btn btn-secondary">Send</button> </form> </div> In settings.py I already added DATE_INPUT_FORMATS = ["%d.%m.%Y"] USE_L10N = False -
Update score model field using JavaScript in Django
I have created a math game using Django and I use JavaScript in the backend to run the game without a page refresh. I need to update the score field after the game ends. I can't seem to get that to work. The score updates on the frontend but not in the database so when the detail form displays the score is always zero. JavaScript: `window.addEventListener('load', function () { let number1; let number2; operator = document.getElementById('operator').innerHTML; max = Number(document.getElementById('max').innerHTML); if (operator == '+') { number1 = Math.floor((Math.random() * max) + 1); number2 = Math.floor((Math.random() * max) + 1); } else if (operator == '-') { number1 = Math.floor((Math.random() * max) + 1); number2 = Math.floor((Math.random() * max) + 1); if (number2 > number1) { number2 = number1 number1 = number2 } } else if (operator == '*') { number1 = Math.floor((Math.random() * max) + 1); number2 = Math.floor((Math.random() * max) + 1); } else { number2 = Math.floor((Math.random() * max) + 1); numberx = Math.floor((Math.random() * max) + 1); number1 = number2 * numberx } document.getElementById('number1').innerHTML=number1; document.getElementById('number2').innerHTML=number2; document.getElementById('tbInput').focus(); window.addEventListener("keydown", function(e) { if (e.key === 'Enter' || e.keycode === 13) { if (operator == '+') { answer = number1 + number2; … -
Django TabularInline override admin temaplate
I have a class that inherits from TabularInline. I have overridden the template, how do I pass data to this template to output it? class commercial_proposal_productadmin(SortableTabularInline): model = commercial_proposal_product extra = 0 template = "admin/tabular.html" i tried to use the change_view function, but the world value is not displayed in the template def change_view(self, request, object_id, form_url='', extra_context=None): extra_context = {'world':'hello'} return super().change_view(request, object_id, form_url, extra_context=extra_context) -
How to get the IP address of incoming connection in custom PAM module
I am using PAM authentication to authenticate with my linux server. I have created a view on my website through Apache2 where I can use python to manually validate each login through a web shell with facial recognition and two factor authentication. This is working, but I can't seem to recover the IP address of the incoming connection. I need a way to find the IP address of my connection to the server before SSH is connected, in the PAM module which is running Python. I would like to use bash for this. I am trying to execute commands to recover the IP address, I tried using "who" and other commands to see incoming SSH connections to no avail. I also tried using "echo $PAM_RHOST" and "$SSH_CLIENT" and "$SSH_CONNECTION" with no success. -
Django - creating automatically database in postgresql for tests, and deleting it after it
I wonder if there is a possibility to trigger somehow automatic creation of database directly from application's code, only for tests purpose. In the perfect scenario, it should look like: Run the tests in Django Database being automatically created and fulfilled (postgresql) After tests pass, whole database should be deleted. For now what I have, is only fulfilling database with tables, and dropping it after tests, but I can't figure out if there is a possibility to trigger creation of database, so user won't be force to do it manually. I was looking for solution, but couldn't find any proper answer for it. I was trying to find a solution for it in documentation in Django, or postgresql but couldn't find any similar problem. -
Django: convert CharField primary key to IntegerField
I have a model (devices) with a CharField primary key containing integers that I would like to convert to an IntegerField. The problem is the devices are also used as a foreign key in another tables meaning when I change the field in my models.py and run the makemigrations/migrate I keep getting an error prompting me to drop the dependent objects first. How can I change the device primary key to an IntegerField without dropping the dependent objects? models.py class Device(models.Model): id = models.CharField(primary_key=True, unique=True, max_length=255) date_created = models.DateField() class Station(models.Model): id = models.AutoField(primary_key=True) device = models.ForeignKey('Device', on_delete=models.PROTECT) error when running the migration constraint api_station_device_id_117642ec_fk_api_device_id on table api_station depends on index api_device_pkey HINT: Use DROP ... CASCADE to drop the dependent objects too. -
How do I know if my Django project is ready to be deployed?
I already finished my project that I made with django, and I want to upload it. I already bought the domain, and they are about to host it for me.. once they give me the host, I just upload it and that's it? Or are there more steps to do within the code? What do I have to do?. that is, once everything is uploaded to the host, will everything be seen? And the Admin will continue to work, when in the search engine put /admin/ ???. that is, I wonder what are all the steps to follow so that once I host my page everything can be seen. that is, what things would have to be configured in the congif.py, and other things. I would appreciate a lot if you give me advice/tips/solutions.. What I know is that I have to change the debug to DEBUG=False ... And I don't know anything else, once they pass me the port and other host information, I simply upload the files of my project to the host and that's it, nothing more? Isn't it necessary to write more code to show it? Excuse me, I have never displayed a page -
How can I trigger function in django while reading it's output without impacting that functions execution time?
I've been trying to find a solution to my issue for some time now, but I haven't come across anything that seems intuitive enough that it seems like the "right" solution. I'm building an electron app that uses django as the backend. The backend is responsible for running some long processes that are time critical. For example, I have a loop that continuously takes data for about 5 seconds. When I run that function standalone, it takes a data point about every 10 ms, however, when I run it through django it takes a data point anywhere from 10 ms to 70 ms or even longer. This makes sense to me intuitively because django is sharing thread time to keep responding to the frontend. However, this is unacceptable for my application. The delays seem to be related to returning data to the frontend. Basically, there's a static variable in the view class that's a container for the result data, then the measurement is triggered from the front end and the measurement populates that static variable with data. When the measurement is running, the front end queries django once a second for updated data so it can plot it for the … -
How to display a specific color depending on the values of a variable in Django?
For example, if the application.status is "rejected", then background: gray; color: lightgrey. If "accepted" - green and lightgreen. If "in progress", then blue and light blue. <div> {% for application in object_list %} <div style="background: ???; color: ???;"> <span>{{ application.status }}</span> </div> </div> {% endfor %} </div> -
TypeError ... not JSON serializable in Django with no reference to my code in the traceback
Notice that my code is not listed. It is all libraries. Traceback (most recent call last): File "/root/env/lib/python3.9/site-packages/django/core/handlers/exception.py", line 55, in inner response = get_response(request) File "/root/env/lib/python3.9/site-packages/django/utils/deprecation.py", line 138, in __call__ response = self.process_response(request, response) File "/root/env/lib/python3.9/site-packages/django/contrib/sessions/middleware.py", line 59, in process_response request.session.save() File "/root/env/lib/python3.9/site-packages/django/contrib/sessions/backends/db.py", line 82, in save obj = self.create_model_instance(data) File "/root/env/lib/python3.9/site-packages/django/contrib/sessions/backends/db.py", line 69, in create_model_instance session_data=self.encode(data), File "/root/env/lib/python3.9/site-packages/django/contrib/sessions/backends/base.py", line 94, in encode return signing.dumps( File "/root/env/lib/python3.9/site-packages/django/core/signing.py", line 150, in dumps return TimestampSigner(key, salt=salt).sign_object( File "/root/env/lib/python3.9/site-packages/django/core/signing.py", line 228, in sign_object data = serializer().dumps(obj) File "/root/env/lib/python3.9/site-packages/django/core/signing.py", line 125, in dumps return json.dumps(obj, separators=(",", ":")).encode("latin-1") File "/usr/lib/python3.9/json/__init__.py", line 234, in dumps return cls( File "/usr/lib/python3.9/json/encoder.py", line 199, in encode chunks = self.iterencode(o, _one_shot=True) File "/usr/lib/python3.9/json/encoder.py", line 257, in iterencode return _iterencode(o, 0) File "/usr/lib/python3.9/json/encoder.py", line 179, in default raise TypeError(f'Object of type {o.__class__.__name__} ' Exception Type: TypeError at /financialreconciliation/ Exception Value: Object of type AllCompany is not JSON serializable I knew the offending view via the URL. I did a binary search in the view to try and find the line where it occurred using print statements but I did not find it. I got all the way to the return with print statements and they all showed. Then I did … -
How to I make this If statement work on my Django project?
The if statement looks correct to me but when i save and execute the server, the printed out information is incorrect. Its almost like the information is not being picked up. Am i missing something in my model or view? Or is there anything else that i have to add to the if statement to allow it to see the data i'm trying to have it post? Can someone point out what i'm missing here?? HTML code: {% if leads.lead_status == "Active Deal" %} {% for lead in leads %} <tr> <td data-href="{% url 'leads:lead-detail' lead.pk %}"><i class="far fa-paper-plane"></i> {{ lead.id }}</td> <td>{{ lead.first_name|title }} {{ lead.last_name|title }}</td> <td>{{ lead.city|title }}</td> <td>{{ lead.state|upper }}</td> <td data-href="tel:{{ lead.phone }}">{{ lead.phone }} <i class="fas fa-phone-square"></i> </td> <td>$34,567.89</td> <td> {% if lead.contract_out == "" %} --/--/---- {% else %} {{ lead.contract_out }} {% endif %} </td> <td> {% if lead.contract_back == "" %} --/--/---- {% else %} {{ lead.contract_back }} {% endif %} </td> <td> {% if lead.hearing_date == "" %} --/--/---- {% else %} {{ lead.hearing_date }} {% endif %} </td> </tr> {% endfor %} {% endif %} views.py class DashboardPageView(LoginRequiredMixin, ListView): template_name = 'dashboard.html' context_object_name = "leads" def get_queryset(self): user = … -
Set up DRF Browsable API Root with all api urls
In my urls.py I have many rest framework urls: path( "api/", include([ path("users/", api_views.users, name="users"), path("proposals/", api_views.Proposals.as_view(), name="proposals"), path("requests/", api_views.Requests.as_view(), name="requests"), #... ]) ) I can visit the individual endpoints in the browser and access the browsable API, but I want to set up a browsable API Root where I can see all the available endpoints. The DRF tutorial has an example in which they list the urls they want in the root, but I have a lot of urls and I want all of them to show up. Is there a way to include all the urls in my "api/" path? -
django cloud run custom domain redirecting to login
During development I an able to login and logout just fine. I have deployed the Django app to Google cloud run. I am also able to login with the Service URL which has the syntax https://example-service-xxxxxxx-ey.a.run.app. Furthermore, I have also connected a custom domain via Firebase to the cloud run service and everything works well apart when I signin in which case I am redirected back to the login page. -
Websocket connection to ws://localhost:8000/ws/jobs/<job_id> failed
I am trying to connect to the websocket using django and I'm still getting same connection error. I've checked the documents and using the same code from the tutorial. const jobSocket = new WebSocket( "ws{% if request.get_host != 'localhost:8000' %}s{% endif %}://" + window.location.host + "/ws/jobs/{{ job.id }}/" ); // Execute this function whenever this page receives an event from Job Consumer via WebSocket jobSocket.onmessage = function (e) { var data = JSON.parse(e.data); var job = data.job; console.log(job); l've tried using routing.py and asgi.py to access the path but the error is still the same "raise ValueError("No route found for path %r." % path) ValueError: No route found for path 'ws/jobs/c5d1cc51-c2ad-458e-9cc7-f62520009112/'." I've tried different url patterns, different regrex esspresion and no luck. I tried this create a wair function to see if the websocket would open but it never does. function waitForSocketConnection(socket, callback){ setTimeout( function () { if (socket.readyState === 1) { console.log("Connection is made") if (callback != null){ callback(); } } else { console.log("wait for connection...") waitForSocketConnection(socket, callback); } }, 10); // wait 5 milisecond for the connection... } function updateCourierPosition(map) { let url = `ws://${window.location.host}/ws/jobs/{{ job.id }}/` const jobSocket = new WebSocket(url) waitForSocketConnection(jobSocket,function() { jobSocket.onopen = function(event){ jobSocket.send("connect") … -
Introspecting Django queryset field lookups
I'm building a querybuilder in Django for something similar to an issues dashboard, which allows users to query and save dashboards for custom subsets of the issues in our database (e.g., all issues assigned to team A, created by client X, and created or updated in the current quarter). The frontend would allow the user to interact with the issues API to generate the list of issues they're looking for, and to save the filter criteria so they can visit the page and see an updated list of issues that match the filter criteria. I'm thinking of saving the filter criteria as a dictionary in a JSONField, which I'd pass to the Model.objects.filter and the Q APIs. I'd like to provide the Frontend a list of all eligible Field lookups (e.g., exact, iexact, contains, icontains, in, gt, etc.). Is there a class I can introspect to programmatically get a list of these lookups? I read through the Field Lookup Docs tried looking through the Django source code, but couldn't find something similar to Model._meta.get_fields() for introspecting the fields on a model, as listed in the Model _meta API docs. -
HINT: Update the relation to point at 'settings.AUTH_USER_MODEL'
Hello I had to rewrite my user model for add some filed, I used AbstractUser My models: It's on blog app: class Article(models.Model): author = models.ForeignKey(User , null=True, on_delete=models.SET_NULL , related_name='articles' , verbose_name='نویسنده')... it's on account app: `from django.db import models from django.utils import timezone from django.contrib.auth.models import AbstractUser class User(AbstractUser): is_authour = models.BooleanField(default=False, verbose_name="وضعیت نویسندگی") special_user = models.DateTimeField(default=timezone.now, verbose_name="کاربر ویژه تا") def is_special_user(self): if self.special_user > timezone.now(): return True else: return False is_special_user.boolean = True is_special_user.short_description = "وضغیت کاربر ویژه"` I imported my User view in this way: from account.models import User And I added this to my setting: AUTH_USER_MODEL = 'account.User' I seatched my error but I can't find my solution