Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to use first variable from first loop for second variable in another for loop in django template
How I can use the first variable from the first loop in the second loop in a Django template like this {% for key in data %} {% for value in data.key %} <div>{{value}}</div> {% endfor %} {% endfor %} I have the data is a nested dict in python like this data = { 'Google_Suite': {'Google Sheet': <QuerySet [<Course: Google Sheet level 1>, <Course: Google Sheet level 2>, <Course: Google Sheet level 3>]>, 'Google Docs': <QuerySet [<Course: Google Doc level 1>, <Course: Google Doc level 2>, <Course: Google Doc level 3>]>, 'Google Slide': <QuerySet [<Course: Google Slide level 2>, <Course: Google Slide level 3>]>}, 'Language': {'English': <QuerySet [<Course: English level 1>]>}} I tried but it's nothing to show -
Terminal mail 'my/path/manage.py': [Errno 1] Operation not permitted
settings.py CRONJOBS=[ ('* * * * *', 'my_app.cron.my_scheduled_job') ] cron.py def my_scheduled_job(): Test.objects.create(name='tested',date_generated=datetime.datetime.now()) After running "python manage.py crontab add" and "python manage.py runserver", Not object is added into Test model and I get terminal mail error "Terminal mail 'my/path/manage.py': [Errno 1] Operation not permitted" -
Django - Questionnaire - ModelFormSet - Cannot assign
Alright, so I'm following a tutorial on creating a small questionnaire with Django. A User can create a survey with different multiple choice questions. Since they're multiple choice questions, users can also set the options for the questions. A "survey taker" can then start a survey, select his or her preferred questions and submit the form. I would like to only show a single question per page so I'm trying to work with modelformset_factory and implement pagination using the build in paginator. The form is rendered correctly and a user can submit an answer, however, the form fails before "formset.is_valid()", I just can't figure out why; ValueError at /surveys/1/submit/4/ Cannot assign "'2'": "Answer.option" must be a "Option" instance. So I can not save an integer and I somehow have to relate the integer with the id from the option model... But I can't access cleaned_data yet so I guess I'm missing something here. Did I forget something within the formset? I've been staring at this for a while now so any help is appreciated. #Views def submit(request, survey_pk, sub_pk): # Let's retrieve the survey which is created by the survey-taker try: survey = Survey.objects.prefetch_related("question_set__option_set").get( pk=survey_pk, is_active=True ) except Survey.DoesNotExist: raise … -
Pagination with graphql and django
I am using react(fe), django (be) and graphql. Currently I send request when I reach bottom of my page to fetch more "posts" to my infinitescrolling feed. In django-graphene this would work like Return Post.objects.all() [offset, offset+limit]. But what should I do if for example my return statement weren't as easy as just fetching all posts? What if I need to return the posts in a sorted way that they aren't already in the DB? Right now, I am doing it like Return custom_sort(Post.objects.all())[offset, offset+limit]. Still working, but I need to sort them on every request (I think, if django aren't cashing it). How would one do this so I only need to sort them once, and then save those values for say a minute so I doesn't need to sort everytime I request? -
Add button on Image ( JavaScript )
I am building a BlogApp and I am trying to add button on Image. I am showing image from django database in javascript (HTML). I am trying to add clickable button on Image. views.py def user_stories(request): posts = BlogPost.objects.filter(user=request.user) template.html <script> var currentSkin = getCurrentSkin(); var blogposts = new BlogPost('blogposts', { skin: currentSkin['name'], autoFullScreen: currentSkin['params']['autoFullScreen'], localStorage: true, stories: [ // {% for post in posts %} BlogPost.buildTimelineItem( '{{ post }}', '{{ user.profile.file.url }}', '{{ post.user }}', '{{post.id}}', timestamp(), [ [ '{{post.id }}-1', 'photo', 3, '{{ post.image.url }}', '', false, false, timestamp(), ], ] ), // {% endfor %} ], }); </script> {{ post.image.url }} is showing image, AND i am trying to add on it. I also tried by adding :- '{{ post.image.url }}<button type='submit' </button>', BUT it is not showing on image. I have no idea , how can i add button on image. Any help would be Appreciated. Any help would be Appreciated. -
Moving from function view to class based view
I have already running table with quite a lot of data. This table was designed years ago with not very clear assumption. Table contains list of "services" we own. There is column 'service_id' which points to given entity. This entity has many instances. In fact, each month, we add new row (new instance), with new data but same 'service_id' for given entity. Now, let's move to Django. I use generic class based views, like ListView, CreateView, DetailView, etc. For this only specific case I need to use function view. How to rewrite this function view to class based view? VIEW: def EsiDetailedView(request, requested_service_id): last_object=Esi.objects.filter(service_id=requested_service_id).aggregate(Max('id')) last_object_id=last_object.get("id__max") last_service=Esi.objects.get(id=last_object_id) args={} args['service'] = Esi.objects.filter(service_id=requested_service_id).order_by('-end_date') args['details'] = last_service #to show details of single service return render(request, 'esi/esi_details.html', args) URLS: urlpatterns = [ path('<int:requested_service_id>/', EsiDetailedView, name='esi-detail') ] -
How to handle emailserver exceptions in django-allauth eg ConnectionRefusedError?
I have implemented django-allauth ok in my django project . however if there is an issue with connecting to the mail server i get this ugly error. How can I handle these kind of exceptions for allauth so that the user gets friendly user error on the page. -
I am getting this error :-ERRORS: P: (corsheaders, E006) CORS ALLOWED ORIGINS should be a sequence of stringsg
I am getting this error :-ERRORS: P: (corsheaders, E006) CORS ALLOWED ORIGINS should be a sequence of stringsg How to solve this error... And move forward... -
Is there any way to create Custom management command to test a task in django framework?
I have to design a custom management command to test a task of loyalty point creation functionality available in tasks.py. This task takes arguments as csv_file_upload_id,csvfilename,orgid,groupid from api. task reads the csv file and validates data and save the data to DB. Now Ihave to design a custom management command to execute above task. any help is most valuable..... thankyou -
Config.js file in django-ckeditor not applying configurations
I have been trying to style Django-CKEditor by modifying the config.js file, all to no avail; my custom configuration in config.js is not working. I have gone as far as manually modifying the default CSS files, but all these modifications fail to work as well. Although when I use Chrome's developers tool to make some modifications, they all worked. My question is, is the config.js file not usable in Django? config.js CKEDITOR.editorConfig = function( config ) { // Define changes to default configuration here. For example: // config.language = 'fr'; // config.uiColor = '#AADC6E'; config.uiColor = '#000000'; config.enterMode = CKEDITOR.ENTER_BR; config.width = "100%"; config.height = "300"; config.extraPlugins = 'autogrow'; config.autoGrow_minHeight = 250; config.autoGrow_maxHeight = 600; }; settings.py CKEDITOR_UPLOAD_PATH = "images/avatar/" CKEDITOR_IMAGE_BACKEND = 'pillow' CKEDITOR_RESTRICT_BY_USER = True CKEDITOR_CONFIGS = { 'default': { 'skin': 'moono-lisa', 'toolbar_Basic': [ ['Source', '-', 'Bold', 'Italic'] ], 'toolbar_Custom': [ {'name': 'styles', 'items': ['Styles']}, {'name': 'basicstyles', 'items': ['Bold', 'Italic', 'Underline']}, {'name': 'colors', 'items': ['TextColor']}, {'name': 'links', 'items': ['Link', 'Unlink', 'Anchor']}, {'name': 'insert', 'items': ['Smiley']}, ], 'toolbar': 'Custom', }, } HTML <script type="text/javascript" src="{% static 'ckeditor/ckeditor/ckeditor.js' %}"></script> -
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 …