Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to create several ContentType fields in a Django model?
My Django model uses a Function model, i.e. a generic function in the company (e.g. : CFO). In this model, I would like to have a field pointing to the default person who holds the function + another field pointing to a backup person in case of problem. Each of this field should be able to point to various models (both the user model + a model with people who have not signed in yet on the website) As long as I only point to one model, it is easy : class Function(models.Model): function_name = models.CharField(max_length=255, blank=True) # e.g. CFO main_user = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True, blank=True) backup_user = models.ForeignKey('auth.User', on_delete=models.SET_NULL, null=True, blank=True) But if I want each of the two fields to point to different models, I need to use ContentType, like : class Function(models.Model): functionname = models.CharField(max_length=255, blank=True) # e.g. CFO #GenericForeignKey: content_type = models.ForeignKey(ContentType, on_delete=models.SET_NULL) object_id = models.PositiveIntegerField() content_object = GenericForeignKey() How to have two GenericForeignKeys in one model ? (for the main_user and for the backup_user)? Thanks a lot for you help, I am confused on how to proceed -
GET Method Not Allowed: /api/banners in django rest framework
I try to use ListModelMixin while getting the list of a queryset. I know I can use ListAPIView, but just for the sake of understanding, I use ListModelMixin. I called the api but I get Get method is not allowed. My view: class BannersView(GenericAPIView, mixins.ListModelMixin): permission_classes = [AllowAny] queryset = Banners.objects.all().order_by('-id')[:1] serializer_class = BannersSerializer My url: path('api/banners',views.BannersView.as_view(),name='api-banners'), Isnt using Listmodelmixin with genericview same as using Listapiview?? -
Accidentlly dropped DB table in Django project. How to re-do migrations?
I've accidentally delated a table from the DB (model AboutUs). Usually I'll delete djando.migrations reccords for this migration (0063), delete the migration file and run makemigrations and migrate commands. First problem is that there are like 20 migrations after the one in question(0063) and in them there are fields modified, added, removed for the same model Seccond problem is that I'm not alone working on the project and it is shared in GitHub. If I delete the migration files there will be conflicts with the origin DB Is there a way to run migrations related only to specific model? Any other ideas how to fix this? -
I am getting order_by fields in the form of a list. I want to order_by by multiple fields with django orm. List is like below:
orderbyList = ['Day','Afternoon','Night'] I am writing a query is like: modelclassinstance.objects.all().order_by(shift_name=*orderbyList) shift_name is name of the column and 'Day','Afternoon','Night' are values in it my ultimate output should be like All day records first and then afternoon second and then night, not in alphabetical order. -
Using Django 3+ on older Postgres (9.4)
Similar to this post, I need to use a newer Django (v3.1) application on an older Postgres database (v9.4). The solutions in this article (upgrading, migrating data to new database) are the better advice, but for the short-term, I would prefer this work with these versions (even though Django 3 dropped support for 9.4). One issue at least is that ON CONFLICT, a newer feature in Postgres v9.5, is used by Django for manytomany management, so a simple .add() call includes this SQL. -
Where and how to set the LANGUAGE_CODE in a Django application?
I'm given a Django application and I need to set its application-wide language to the Turkish language. I've read the official Django documentation (which ise over 2000 pages) and there it talks about setting LANGUAGE_CODE variable e.g. LANGUAGE_CODE = 'tr-tr but it doesn't talk about exactly where and how to set it. It talks about a file called settings.py but it doesn't mention under which directory it resides I've searched the application's root directory for settings.py and those two files came up <root-dir>/contexts/settings.py <root-dir>/templatetags/settings.py But inside them were like: import logging from app.models import Setting logger = logging.getLogger('app.logger') # Make the SETTINGS object available to all templates def load(request=None): return {'SETTINGS': Setting.objects.first()} # Helper functions for libsass def theme(color): """Return a theme color from the currently selected theme""" try: <truncate> i.e. plain Python code so I haven't put a random LANGUAGE_CODE into any of those two settings.py files. I've created instead a settings.py under the root directory and put LANGUAGE_CODE = 'tr-tr into it and restarted the application but it didn't change the application-wide language at all. So where and how to set the LANGUAGE_CODE in this Django application to be able to set the application-wide language? -
How can I capture first_name from a form?
How would I be able to get the first_name into the context. class NewTeacherView(LoginRequiredMixin,CreateView): model = TeacherData form_class = TeachersForm template_name = 'new_teacher.html' #template_name = 'new_teacher.html' success_url = reverse_lazy('teachers') def get_context_data(self, *args, **kwargs): context = super(NewTeacherView,self).get_context_data(*args, **kwargs) context["user"] = User.objects.create_user( username=??????? password=???????) return context The form is below class TeachersForm(forms.ModelForm): class Meta: model = TeacherData fields = ("first_name","last_name") widgets = { "first_name":forms.TextInput(attrs={"class":'form-control'}), "last_name":forms.TextInput(attrs={"class":'form-control'}), } My interest and desire is to use the first_name for both username and password -
Django ASGI channels application not keeping track of multiple websocket clients (using redis and nginx)
I have Django with asgi channels hosted on a local vm, I am also using redis-channels and nginx. I am able to connect and use my application with one user however once creating a second connection, the old (original) client stops receiving web-socket information however it can still send it. My consumers.py receives all websocket data but thinks it's all from the newest connection. Meaning the the first ws connection does close but stops receiving information. Versions: Python = 3.9.2 Django = 3.1.7 Channels = 3.0.3 channels-redis = 3.2.0 redis = 5.0.3 I have been able to send websocket information from within consumers and outside for handling webhook responses, I just can't handle multiple connections on the consumer. Nginx Configuration: worker_processes 1; events { worker_connections 1024; } http { include mime.types; default_type application/octet-stream; sendfile on; keepalive_timeout 65; upstream websocket { server 127.0.0.1:8000; } server { listen 80; server_name localhost; location / { proxy_pass http://websocket; proxy_http_version 1.1; proxy_set_header Upgrade $http_upgrade; proxy_set_header Connection "upgrade"; proxy_redirect off; proxy_set_header Host $host; proxy_set_header X-Real-IP $remote_addr; proxy_set_header X-Forwarded-For $proxy_add_x_forwarded_for; proxy_set_header X-Formwarded-Host $server_name; } # end location } # end server } # end http Consumers (cut down): class ChatConsumer(AsyncWebsocketConsumer): async def connect(self): self.username = self.scope["session"]["tokenOwner"] await … -
Open and edit .CDR file in python django
I want to open user to uploaded .cdr file in using django. And allow user to make changes in that file from browser. Please suggest how can i achieve this problem. -
Does not update select materialize?
I'm using Django to create a select form, that's okay. So, I have a problem while changing select, lines do not change (using AJAX to replace). It happens only when I'm using materialize, If I'm not, it works. How can I refresh this select form to display my new? Here is screenshots, which I have. I added console.log to see that it works. [1]: https://i.stack.imgur.com/EcKDS.png [2]: https://i.stack.imgur.com/2iEQH.png $("#id_institution").change(function () { var url = $("#studentForm").attr("data-classrooms-url"); var classroomId = $(this).val(); $.ajax({ url: url, data: { 'classroom': classroomId }, success: function (data) { console.log(data); $("#id_classroom").html(data); } }); }); -
Show selected background color
I am building a BlogApp and I want user to pick background according to her/him. I successfully implement background feature from django admin BUT , I am trying to show it in the BlogPost Page. AND if user change then color should change. BUT i have no idea how i can i access background color in Browser which is selected from Admin . I am using django-colorfield. models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE,default='',unique=True) background_color = ColorField(default='#FF0000') I have also tried using <div style="background-image: url('{{ profile.background_color }}');"></div> BUT this is not showing the color. I also tried using :- {{ profiles.background_color }} BUT this also not showing the color. Any help would be Appreciated. Thank You in Advance. -
Connecting with onedrive in python
I'm using onedrivesdk_fork to connect with the onedrive. I've created the application in azure, click on the link to view the application detail application details I'm using the following code from the github: https://github.com/OneDrive/onedrive-sdk-python#download-an-item import onedrivesdk_fork as onedrivesdk from onedrivesdk_fork.helpers import GetAuthCodeServer from onedrivesdk_fork.helpers.resource_discovery import ResourceDiscoveryRequest redirect_uri = 'http://localhost:8080/' client_secret = 'your_app_secret' discovery_uri = 'https://api.office.com/discovery/' auth_server_url='https://login.microsoftonline.com/common/oauth2/authorize' auth_token_url='https://login.microsoftonline.com/common/oauth2/token' http = onedrivesdk.HttpProvider() auth = onedrivesdk.AuthProvider(http, client_id, auth_server_url=auth_server_url, auth_token_url=auth_token_url) auth_url = auth.get_auth_url(redirect_uri) code = GetAuthCodeServer.get_auth_code(auth_url, redirect_uri) I'm able to receive the code in the url. But after executing the below code: code = GetAuthCodeServer.get_auth_code(auth_url, redirect_uri) ternminal is just blocked and I'm not able to type anything on the terminal. So I decided to close the terminal and then executed the entire code again except the line which is used to get the code(Already received the code in the last execution) so after running this line: client.auth_provider.authenticate(code, redirect_uri, client_secret) I get the following error: init raise Exception(str(message["error"])) Exception: invalid_grant Please help me how can i stop the script not block the terminal and why I'm receiving the above error. -
Django nginx docker ssl not redirecting in some browser
I have installed ssl in my nginx server. It is working very well. Here you go for my conf. server { listen 443 ssl; server_name example.com www.example.com; ssl_protocols TLSv1.2 TLSv1.1 TLSv1; ssl_certificate /etc/certs/example_com.crt; ssl_certificate_key /etc/certs/definesys.key; location = /favicon.ico { access_log off; log_not_found off; } location / { proxy_pass http://backend:8000; proxy_set_header X-Forwarded-Proto $scheme; } } # Redirext https server { if ($host = example.com) { return 301 https://$host$request_uri; } # managed by ssl server_name example.com; listen 80; return 301 https://$host$request_uri; } It's working very well when i example.com, but i notice in mobile or macos chrome or some otheer browser, it is not working. why it is not redirecting to https in some browser? and this is only working urls: https://www.example.com with ssl, but if i type https://example.com it dont works? this is my django settings SECURE_PROXY_SSL_HEADER = ('HTTP_X_FORWARDED_PROTO', 'https') Also i have tested with this variables SECURE_SSL_REDIRECT = True but it redirects to proxy server, backend:8000 Can anyone help me to get it done? -
Django database issue
I would like to get information from my database, however, i am only able to get all the data. I understood that it is bcs I used objects.all(). I got (patient name, nric, address code and all of them). I am wondering what should I do in order to get, say, all the names in my database and not all the data in Json form. Thank you. view.py from django.http import HttpResponse, JsonResponse from django.views.decorators.csrf import csrf_exempt from rest_framework.parsers import JSONParser from rest_framework.decorators import api_view from rest_framework.response import Response from rest_framework import status from .models import PatientDetail from .serializer import PatientSerializer # Create your views here. @api_view(['Get', 'POST']) # @csrf_exempt def patient_list(request): if request.method == 'GET': patientdetails = PatientDetail.objects.all() # serialization serializer = PatientSerializer(patientdetails, many=True) # return Json return Response(serializer.data) elif request.method == 'POST': #data = JSONParser().parse(request) serializer = PatientSerializer(data=request.data) if serializer.is_valid(): serializer.save() return Response(serializer.data, status=status.HTTP_201_CREATED) return Response(serializer.errors, status=status.HTTP_400_BAD_REQUEST) @api_view(['Get', 'PUT','DELETE']) @csrf_exempt def patient_detail(request,patientNRIC): try: patientdetails = PatientDetail.objects.get(patientNRIC = patientNRIC) except PatientDetail.DoesNotExist: return HttpResponse(status=404) if request.method == "GET": # serialization, getting one data only serializer = PatientSerializer(patientdetails) # return Json return JsonResponse(serializer.data) elif request.method == "PUT": data = JSONParser().parse(request) serializer = PatientSerializer(patientdetails, data=data) if serializer.is_valid(): serializer.save() return JsonResponse(serializer.data) return JsonResponse(serializer.errors, … -
Django is always returning 404 while testing. "The requested resource was not found on this server."
I have an Django API that I build quickly, and now I want to add some tests to ensure is stable. The problem is that Django simply refuses to let me access any resource on the server. It can't find any URL. I have some models, but this test is with the User model. # auth/urls.py urlpatters = [ ... path( "user/<str:email>/", views.UserView.as_view(), name="public staff user", ), ... ] # auth/tests/tests.py (Folder workign as a submodule, tests.py is a temporary name) from django.test import TestCase from django.urls import reverse from rest_framework.test import APIClient, APITestCase from authentication.models import User import os # Create your tests here. class TestTestCase(APITestCase): def setUp(self): self.staff_user = User.objects.create( email="test@account.me", is_staff=True, is_active=True ) self.staff_user_password = "staff_password" self.staff_user.set_password(self.staff_user_password) def test_testing(self): print(User.objects.all()) url = reverse("public staff user", kwargs={"email": self.staff_user.email}) print(url) response = self.client.get( url, ) print(response.content) I have a few unused imports, but those don't matter. I create a User instance, and change it's password. Then, in the test, I try to retrieve it's data. I can confirm the user exists (the shell returns <QuerySet [<User: Employee#000>]>) and the url works (/api/user/test@account.me/ works with another email in the dev database). However, response.content returns the following: # Escaped for ease … -
How can I use a value in a models.Model?
I wondering to know how it is possible to pass a value into a model. For example, I'm tryng to get the supplier_id : class Question(models.Model): q = models.CharField(max_length=250, blank=True, null=True) def get_audited(self, *arg, **kwargs): bar_param = kwargs.get('pk') **bar_param** = 11 <-- supplier_id ? return AuditSupplier.objects.filter(question_id=self, supplier_id=**bar_param**) def __str__(self): return self.q -
Generating an encrypted file on a webpage daily
I have a python program that reads an encrypted file to extract the required settings and time. The encrypted file should be updated per each minute and should be accessed remotely by multiple users. Is there a way to generate that encrypted file on a webpage (with a fixed hyperlink; say www.website-name.com/log.txt) and replaces the older file at a specific time frame (for example, per minute, hourly, daily, etc). Then, I can access that file from its url. Is there a way to do that? -
Unable to solve thisReverse for 'read_post' with arguments '('',)' not found. 1 pattern(s) tried: ['read_post/(?P<id>[0-9]+)$']
I have a navbar in my template in which i am trying to add active class however whenever i do that get this error:NoReverseMatch at / Reverse for 'read_post' with arguments '('',)' not found. 1 pattern(s) tried: ['read_post/(?P[0-9]+)$'] Request Method: GET Request URL: http://127.0.0.1:8000/ Django Version: 3.1.7 Exception Type: NoReverseMatch Exception Value: Reverse for 'read_post' with arguments '('',)' not found. 1 pattern(s) tried: ['read_post/(?P[0-9]+)$'] Exception Location: C:\Users\Abdullah\AppData\Local\Programs\Python\Python39\lib\site-packages\django\urls\resolvers.py, line 685, in _reverse_with_prefix Python Executable: C:\Users\Abdullah\AppData\Local\Programs\Python\Python39\python.exe Python Version: 3.9.2 Python Path: ['C:\Users\Abdullah\Desktop\Blog\my_blog', 'C:\Users\Abdullah\AppData\Local\Programs\Python\Python39\python39.zip', 'C:\Users\Abdullah\AppData\Local\Programs\Python\Python39\DLLs', 'C:\Users\Abdullah\AppData\Local\Programs\Python\Python39\lib', 'C:\Users\Abdullah\AppData\Local\Programs\Python\Python39', 'C:\Users\Abdullah\AppData\Roaming\Python\Python39\site-packages', 'C:\Users\Abdullah\AppData\Local\Programs\Python\Python39\lib\site-packages'] Server time: Wed, 21 Apr 2021 09:38:37 +0000 my base.html: {% load static %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="UTF-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width, initial-scale=1.0"> <title>Document</title> </head> <link rel="stylesheet" href="{% static 'css/base.css' %}"> <link rel="stylesheet" href="{% static 'css/posts.css' %}"> {% url 'posts' as posts %} <nav> <ul> <li><a class="nav_a {% if request.path == posts %} active {% endif %}" href="{% url 'posts' %}">Blogs</a></li> {% if request.user.is_authenticated %} <li><a class="nav_a" href="{% url 'myposts' %}">Welcome {{ request.user }}</a></li> <li><a class="nav_a" href="{% url 'post' %}">Post</a></li> <li><a class="nav_a" href="{% url 'myposts' %}">My Posts</a></li> <li><a class="nav_a" href="{% url 'logout' %}">Logout</a></li> {% else %} <li><a class="nav_a" href="{% url 'signup' %}">Signup</a></li> <li><a class="nav_a" href="{% url 'login' %}">Login</a></li> {% … -
Disable prefers-color-scheme: dark in django admin
I have dark mode enabled on Mac but it's looks awkward in django admin panel with ckeditor. Is it any option to disable it in Chrome or Django admin? I've already tried themes and extensions - no success. -
Come posso impostare il valore del radio button in modo dinamico e salvarlo nel database?
Ciao a tutti, sto lavorando a un progetto Django e ho problemi a salvare i dati di un record scelto da una tabella json, nel mio database. in views.py --> creo la tabella json def upload_csv(request): df = pd.read_csv(os.path.join(settings.BASE_DIR,'Cooling-S1.csv')) # parsing the DataFrame in json format. json_records = df.reset_index().to_json(orient ='records') data = [] data = json.loads(json_records) context = {'d': data} return render(request, 'upload.html', context) in upload.html --> mostro la tabella e aggiungo un radio buttom in ogni riga {%include 'base.html' %} {% load static %} {% block content %} <form method="POST" name="form" action="{% url 'upload_servizio' %}"> {% csrf_token %} <h2 class="text-center"><u>Cooling S1</u></h2><br> <table class="table table-dark table-striped"> <thead> <tr> <th>Level</th> <th>Name</th> </tr> </thead> <tbody> <!-- jinja2 Technique --> {% if d %} {% for i in d %} <tr> <td>{{i.Level}}</td> <td>{{i.Name}}</td> <td> <input id= "risposta" name="risposta" type="radio" value= "{{i}}" > </td> </tr> {% endfor %} {% endif %} </tbody> </table> <button type="submit" class="btn btn-success">Save</button> </form> <p><a href="{% url 'home' %}">Return to home</a></p> {% endblock %} Ho inserito un radio buttom in ogni riga, ma non riesco a capire come passare i valori della riga scelta al mio modello per salvarli. il mio modello: class Upload(models.Model): level = models.CharField(max_length=40, help_text='Inserisci il nome … -
jquery function not registering changes
I have a jquery script in my django project that reads checkboxes and then submits them to a function when clicked. My problem is that this only works when I reload my page. is it possible to have the jquery script "listening" allt the time to the checkboxes? <script> $(document).ready(function() { var vals=[]; $.each($("input[name='checkb']:checked"), function() { vals.push($(this).attr('id')); }); console.log('calling function:',vals) $('.print').click(function() { console.log('print:',vals) $.get('eprint/ticked/',{marked: vals}) }) $('.delete').click(function() { console.log('delete:',vals) $.get('edelete/ticked/',{marked: vals}) }); }); </script> {% for l in object_list %} <tr> <td> <form> <label><input type="checkbox" id={{l.pk}} name="checkb"></label> <form> -
Sections in admin.py django became inline
Display, filter, and search fields float to the left. @admin.register(Comment) class CommentAdmin(admin.ModelAdmin): list_display = ('name', 'email', 'post', 'created', 'active') list_filter = ('active', 'created', 'updated') search_fields = ('name', 'email', 'body') -
method_descriptor object has no attribute 'now' - while returning in function encoded with strings [closed]
while running the below snippet the error is thrown on datetime.time.now() Error msg : method_descriptor object has no attribute 'now' from datetime import datetime def fileprocces(file_path, max_width=0, width=0, height=0): file_dir = _get_file_dir(file_path) file_name = _get_file_name(file_path) return f" {file_dir}/thumbnails/{max_width}/pro_pic{datetime.time.now()}.jpg" -
How do I include an oninvalid attribute while using django widget tweaks?
{% render_field form.field_1 class="form-control mb-2" type="text" onkeyup="empty_select_check(this)" oninvalid="this.setCustomValidity(' ')" %} I am currently using django widget tweaks to render my fields. However, on some fields that are required, if users do not fill up those fields, the default "Please field in this field" or "Please select a list" will appear. I have tried using the invalid attribute which was recommended by stackoverflow on another question. This attribute works fine when I use it on an input element but when I insert it into widget tweaks, I get the following error: Template Syntax Error: Could not parse the remainder: '"this.setCustomValidity('' from '"this.setCustomValidity('' I am unsure of how I can remove the pop-up without using the oninvalid attribute. Anyone has any other plausible suggestions? As seen below, i have attempted to replace the "pop-up" with my js way of checking the field. JS doesnt work and pop-up still shows up though. function empty_value_check(ele) { let value = ele.value; if (value === '') { $(ele).addClass('is-invalid'); } else { $(ele).removeClass('is-invalid'); } } function empty_value_all() { $('#field_1_id').each(empty_value_check(this)); return !($('.is-invalid').length > 0) } -
Set ordering in django to use language specific order
I have a Django app with the following models that have the ordering set with class Meta: class Akutsomatik(models.Model): bereichname = models.CharField(max_length=200) class Meta: ordering = ['bereichname'] def __str__(self): return self.name # This model is only included in the example for better understanding class Klinik(models.Model): name = models.CharField(max_length=200) akutsomatik = models.ManyToManyField(Akutsomatik, blank=True) def __str__(self): return self.name And my template: {% if klinik.akutsomatik.all %} <ul> {% for akutsomatik in klinik.akutsomatik.all %} <li>{{ akutsomatik }}</li> {% endfor %} </ul> {% endif %} The problem is that the data of my app is in German and the ordering is set to UTF-8. The output would look something like that: Augenchirurgie / Ophtalmologie Brustchirurgie Viszeralchirurgie Wiederherstellende Chirurgie Ästhetische Chirurgie but in German it should be like: Ästhetische Chirurgie Augenchirurgie / Ophtalmologie Brustchirurgie Viszeralchirurgie Wiederherstellende Chirurgie Note that the Ästhetische Chirurgie should come before Augenchirurgie / Ophtalmologie. Does anyone now if there is a way to set the collation in class Meta? I tried the following as decribed [here][1]: class Meta: ordering = [Func('bereichname', function='utf8_general_ci', template='(%(expressions)s) COLLATE "%(function)s"') ] But I get the following error: collation "utf8_general_ci" for encoding "UTF8" does not exist LINE 1: ...ER BY ("klinik_finder_akutsomatik"."bereichname") COLLATE "u... I also tried to set …