Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Files inside PersistentVolume cannot be overwritten
I have project in GCP using django and created a persistent volume for static files, everything was fine for months until recently a deployment failed because django couldn't overwrite old static files. OSError: [Errno 30] Read-only file system: '/static/admin/img/selector-icons.svg' For now I simply disabled manage.py collectstatic and use the old ones since they don't change very often. My pv.yaml looks like this: metadata: name: backend-pvc labels: type: pvc spec: storageClassName: gce-pd resources: requests: storage: 1Gi accessModes: - ReadWriteOnce - ReadOnlyMany backend.yaml: volumes: persistentVolumeClaim: claimName: backend-pvc and nginx.yaml: volumes: - name: static persistentVolumeClaim: claimName: backend-pvc readOnly: true Checked the pods and volumes are mounted correctly, rw for backend: static-volume: Type: PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace) ClaimName: backend-pvc ReadOnly: false and read only for nginx: static: Type: PersistentVolumeClaim (a reference to a PersistentVolumeClaim in the same namespace) ClaimName: backend-pvc ReadOnly: true Anyone has any suggestion how to fix it? Should I just delete PV and create it again? What might have caused this to happen? -
Django : How can I use the response returned by form_valid() of a CreateView on another model in a new template?
I am learning Django, and I am sure the solution is very simple but I can't find it; I have a model "profile" that needs to be filtered by a request. Requests and answers need to be kept in database. But I don't want the user to see all the profiles at any moment. So I wrote two models : the first one contains the requests (MyRequest), the second the potential answers (Profile). Profiles are created importing csv in Django admin. I wrote a code that is working fine BUT I can't figure how to send my response in a template to use all the customizations and securities as csrf_token. Currently it is showing the response in the same url than the request and I am blocked here I have tried to use get_succes_url with HttpResponseRedirect, usually I can do such things using (?P\d+)/$' in the success url but it doesn't work maybe because the two models don't share any key? I have tried to put and in success url but I think I did something wrong """Models""" class Profile(models.Model):#probgerme probpvt probservice probATCDpvt probATCDbmr probNB profname= models.CharField(max_length=20) bq = models.ForeignKey(Bq, on_delete=models.CASCADE)#, blank=True test1 = models.CharField(max_length=100) test2 = models.CharField(max_length=100) test3 = … -
django admin queryset display related objects in a field
def Ark(): li = Forti.objects.all(), Autre.objects.all() list1=list(li) return list1 class License(models.Model): assigne_a = models.CharField(default =Ark, max_length=25, verbose_name="assigné à l'equipement") categorie = models.TextField( max_length=15, choices=Cat_choice, verbose_name='Categorie generale', blank=True) cate = models.TextField( max_length=15, choices=Cat2_choice, verbose_name='Categorie Interne', blank=True) class Meta: verbose_name = 'License' """i want it to display related object in the field assigne_a in sort of list but it is diplaying it like this: [, ]>, ]""" -
cmd.exe is not recognized as an internal or external command when activatin virtual environment
I recently started learning Django and I am working on a small project. I successfully created a virtual environment but whenever I type "pipenv shell" I get this error in the command line which says "cmd.exe is not recognized as an internal or external command, operable programme or batch file" how do I fix it? -
Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' When MySql is in Docker
I have mysql running in docker container 0.0.0.0:32768->3306/tcp. I am trying to connect to it using following config: DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'USER': 'test', 'PASSWORD': 'test', 'HOST': 'localhost', 'PORT': '', 'OPTIONS': { 'init_command': "SET NAMES 'utf8'", }, 'TEST': { 'NAME': 'test-3944' } } } I am getting an error from my host ubuntu: django.db.utils.OperationalError: (2002, "Can't connect to local MySQL server through socket '/var/run/mysqld/mysqld.sock' (2)") What is wrong? How to fix this? -
Adding more than one instance of ArrayModelField item with Djongo
I am using djongo to add mongodb to my application. I have a model, say ModelA, that takes in an ArrayModelField of another model ModelB, which is an abstract model. I get a ModelForm for ModelA, but it shows fields for entry of only one ModelB. How can I get a functionality like an Add button, so that more ModelB fields can be added? -
TypeError: autodiscover_tasks() missing 1 required positional argument: 'packages'. Celery
I am taking the first steps to add Celery tasks in the background in my Django application. But I still receive the error. File "C:\Users\tymot\Desktop\send_sms_oferia\app_rama\app_rama\__init__.py", line 5, in <module> from .celery import app as celery_app File "C:\Users\tymot\Desktop\send_sms_oferia\app_rama\app_rama\celery.py", line 17, in <module> app.autodiscover_tasks() TypeError: autodiscover_tasks() missing 1 required positional argument: 'packages' Where can this error come from? How can I solve it? I try to perform my steps in accordance with this documentation, so my file looks like this: celery.py (in my project directory): from __future__ import absolute_import, unicode_literals import os from celery import Celery # set the default Django settings module for the 'celery' program. os.environ.setdefault('DJANGO_SETTINGS_MODULE', 'app_rama.settings') app = Celery('app_rama') # Using a string here means the worker doesn't have to serialize # the configuration object to child processes. # - namespace='CELERY' means all celery-related configuration keys # should have a `CELERY_` prefix. app.config_from_object('django.conf:settings') # Load task modules from all registered Django app configs. app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) My __init__.py file (in my project directory) from __future__ import absolute_import, unicode_literals # This will make sure the app is always imported when # Django starts so that shared_task will use this app. from .celery import app as celery_app __all__ … -
How to convert user entered datetime to milliseconds
I am trying to convert user entered datetime to milliseconds. Here i'm using template file for user to enter date time. And i'm extracting and stored in variable from and to.How to convert that into milliseconds. from = request.POST.get('from_date') to = request.POST.get('to_date') -
is it good idea to use micro services in django application?
we are developed django application in monolithic architecture so we have move to microservices architecture.Is it good idea? Please provide me any reference link -
Differentiate request from admin portal and from basic API - Django/REST
I was wondering if it was possible to differentiate a request from the Django administration portal from a request from the API ? For example, using permissions, a user would not be able to delete an instance with a basic API call. But the same user through the admin portal would be able to delete the instance. I tried to look at the parameters of the request object but didn't find anything that can be used. -
Authenticate function return none value so user cant login
from django.shortcuts import render, redirect, reverse from reg.models import Reg_page from django.contrib.auth.models import User,auth from django.contrib import messages from django.contrib import auth from django.contrib.auth import authenticate,login from django.http import HttpResponseRedirect from django.db.models import Q from django.core.exceptions import ObjectDoesNotExist from django.template import RequestContext def user_login(request): if request.method == 'POST': username = request.POST['username'] password = request.POST['password'] print("username", username) print("password", password) user=auth.authenticate(username=username, password=password) #user=User.objects.filter(username=username, password=password).exists() print("value",user) if user: auth.login(request, user) return redirect("/welcome") else: return render(request, "login.html", {'error': 'username and password incorrect'}) else: return render(request, "login.html") user can not login because autheticate function return none value it is not give any error so let me know how i can do this -
Exporting queryset data using Django without have to re-query data
I have set up a Django app that queries from a PostgreSQL database. Exporting all the data within a model seems relatively straight forward but what if I wanted to export only the data from a returned queryset. Currently I'm managing this by having a button on my page and changing the url when the user wishes to export data. The code within the view that I'm rendering is as follows. def export_data(request,pk): resource_class = MDPResource() queryset = MDP.objects.filter(mdp_id=pk) dataset = person_resource.export(queryset) response = HttpResponse(dataset.csv, content_type='text/csv') response['Content-Disposition'] = 'attachment; filename="mdpbasic.csv"' return response However, this means that I'm going to be making one query when the user initially opens the page and then a second query (in effect 2 extra) when the user wishes to export the data which I have already queried for in the previous view. Moreover, in a section of my page I'm also using Q models for complex filtering. The above method is not sufficient for exporting data in that case (I don't want to have to reconstruct the query). I also do not want to have to write the data to a file (if I can help it) because then that raises the issue of having … -
error when creating a new virtual environment in django
enter image description hereI get the error "OSError: [Errno 9] Bad file descriptor" whenever I try create a new virtual environment or when when I try torun server of my django project.I am using python 3.7.3 on windows 10. I have tried repairing,uninstalling and reinstalling python but it seems not to work still. -
Deleting mutiple selected objects at once in django [duplicate]
This question already has an answer here: How to delete a record in Django models? 4 answers I want to create something like in the django admin, where one can select objects you want to delete. I have the my model bellow . class People(models.Models): names=models.Charfield view.py def display(request): people=People.objects.all() context={'people':people} def delete_objs(request,id): # i am stock on how to implement a code that will delete selected objects In my django template {% for obj in people %} {{obj.name}} {% endfor %} In my django template and view , how to make it possible for user to select and delete selected objects.Thanks in advance -
When I put my django project on AWS ubuntu server mysqclient error
When i push my django project on AWS ubuntu server and run i got mysql client error below: django.core.exceptions.ImproperlyConfigured: Error loading MySQLdb module. Did you install mysqlclient? Then i run below command but same error: 1)sudo apt update 2)sudo apt install mysql-server 3)sudo systemctl status mysql but same erro -
AssertionError at /api/todo/ 'ToDOView' should either include a `serializer_class` attribute, or override the `get_serializer_class()` method
I'm developing a todo api with django. I am getting error as ToDoView(view class name) should include serializer_class but i already have it. Here is the code Router and url router = routers.DefaultRouter() # add this router.register(r'todo', views.ToDOView ,'todo') # add this urlpatterns = [ path('admin/', admin.site.urls), path('api/', include(router.urls)) # add this ] View: class ToDOView(viewsets.ModelViewSet): serializer_class: ToDOserializer queryset = ToDo.objects.all() serializers: class ToDOserializer(serializers.ModelSerializer): class Meta: model : ToDo fields : ('id','title','description','completed') id,title,description and completed are field of my model -
Can I run code every time an abstract class is inherited?
I need to connect a django signal to all classes which inherit from an abstract class. Is there a magic python method like __on_inherit__ which would allow me to run the signal connection code every time my abstract class is inherited? -
'HttpResponse' object has no attribute 'seek'
i want to export from data in excel and i try below code def exel_all_attendance(request,course_id): all_submit_attendance = SubmitedAttendance.objects.filter(course_id=course_id) response = HttpResponse(content_type='application/vnd.openxmlformats-officedocument.spreadsheetml.sheet') response['Content-Disposition'] = 'attachment; filename=course.xlsx' attendance_workbook = Workbook() attendance_worksheet = attendance_workbook.active attendance_worksheet.title = 'list_hozor_qiab' columns = [att.submit_time for att in all_submit_attendance.all()] row_num = 1 for col_num, column_title in enumerate(columns, 1): cell = attendance_worksheet.cell(row=row_num, column=col_num) cell.value = column_title attendance_workbook.save(response) return response but i give this error AttributeError: 'HttpResponse' object has no attribute 'seek' and i check where is from error attendance_workbook.save(response) any solution? -
How to write csv file in html?
I have read file of csv but I have a problem that how to read CSV file and save it in table.html? import csv html_about = '' names = [] with open('filo.csv') as data_file: csv_data = csv.reader(data_file) for line in csv_data: names.append(f'{line[0]}') html_output = '\n<ul>' for name in names: html_output += f'\n\t<li>{name}</li>' html_output += '\n</ul>' from prettytable import PrettyTable x = PrettyTable(line[0]) html_code = x.get_html_string() html_file = open('table.html','w') html_file = html_file.write(html_code) -
django "type object 'UserProfile' has no attribute 'DoesNotExist' "
I'm using django restapi framework and trying to do crud , I completed with insert ,update ,select operations but cant delete record. I'm little stuck with this ponit if anyone can tell which direction I should go to fix this I'ill be really glad ty. urls.py I try both url and path version path('user/profile/add', views.AddProfile.as_view(), name='user_profile_add'), # path('user/profile/delete/', views.DeleteProfile.as_view(), name='user_profile_delete'), url(r'^user/profile/(?P\d+)/delete/$', views.DeleteProfile.as_view(), name='user_profile_add'), views.py class DeleteProfile(APIView): permission_classes = (IsAuthenticated,) def get_object(self, pk): try: return UserPorfile.objects.get(pk=pk) except UserProfile.DoesNotExist: raise Http404 def delete(self, request, pk): userprofile = self.get_object_or_404(id=pk) userprofile.delete() return Response(status=status.HTTP_204_NO_CONTENT) serializers.py class UserProfileSerializer(serializers.ModelSerializer): class Meta: model = UserProfile fields = ('id', 'userid', 'accounttype') models.py from django.shortcuts import render, redirect, get_object_or_404, render_to_response from .models import UserProfile from rest_framework.permissions import IsAuthenticated from rest_framework.response import Response from rest_framework.views import APIView from rest_framework import serializers from rest_framework import status class UserProfile(models.Model): id = models.AutoField(primary_key=True, verbose_name='PID') userid = models.BigIntegerField(verbose_name='UID') accounttype = models.CharField(max_length=20, verbose_name='AccType') list_display = ('id', 'accounttype', 'userid') -
How to access to a Many to Many object to get another model property?
I'm coding a tooltip for a Django dashboard, so one of the scenarios says that when the user has not connected their Github account the repository link will be disabled. I already solved the problem but I didn't realized that it only works for the owner of the repo, so if I add somebody else as a collaborator, the link is going to work for them, because ofc, they are not the owners. I have this in my main model: owner = models.ForeignKey( TeamMember, related_name="github_repos", blank=True, null=True, on_delete=models.SET_NULL, ) members = models.ManyToManyField( TeamMember, related_name="new_projects", blank=True, through=ProjectMember, ) So basically how I solved the problem was this way: def html_message(self): pattern = re.compile("Github Repository", re.IGNORECASE) if self.project.owner.has_connected_github: git_connection = self.project.owner.django_user.socialaccount_set.filter( provider="github" ).first() if git_connection: html_message = pattern.sub( f"<a href='{self.project.html_url}'>Github Repository</a>", self.message ) else: html_message = pattern.sub( f"<a href='#' data-toggle='tooltip' title='Connect your Github account to access repository.'>Github Repository</a>", self.message ) That works but as I said before, only for the owner of the app, I need to know how to access to members, instead of owner, because as you can see is a Many to Many Field. And also here is how TeamMember model looks like: class TeamMember(models.Model): class Meta: unique_together = … -
MySql Old Version djang-mysql field incompatible
I was trying to add django-mysql app in my project https://django-mysql.readthedocs.io/en/latest/model_fields/json_field.html#jsonfields-in-forms It worked perfectly on my local system. But When I ran it into production, it created an error (django_mysql.E016) MySQL 5.7+ is required to use JSONField HINT: At least one of your DB connections should be to MySQL 5.7+ What can I do now? -
My css properties changes when I use bootstrap4 with django
I have two pages both in the same app sharing a common style.css - search.html and add.html. I have used bootstrap4 for forms in add.html and not with search.html. When I do this the image size in the add.html changes automatically and the css properties like font, div height changes. Can someone tell me how to fix it? search.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <head> <meta charset="UTF-8"> <title>Transport Portal - Search Page</title> </head> <body> <div class="headerbar"> <img src="{% static 'images/hpcl_logo.png' %}"> <h1>Transportation Portal</h1> </div> <div class="topnav"> <ul> <li><a href="">Home</a></li> <li><a class="active" href="">Search</a></li> <li><a href="">Add</a></li> </ul> </div> </body> </html> add.html {% load staticfiles %} <!DOCTYPE html> <html lang="en"> <link rel="stylesheet" type="text/css" href="{% static 'css/style.css' %}"> <head> <meta charset="UTF-8"> <title>Transport Portal - Search Page</title> <meta name="viewport" content="width=device-width, initial-scale=1, shrink-to-fit=no"> <link rel="stylesheet" href="https://stackpath.bootstrapcdn.com/bootstrap/4.1.3/css/bootstrap.min.css" integrity="sha384-MCw98/SFnGE8fJT3GXwEOngsV7Zt27NXFoaoApmYm81iuXoPkFOJwJ8ERdknLPMO" crossorigin="anonymous"> </head> <body> <div class="headerbar"> <img src="{% static 'images/hpcl_logo.png' %}"> <h1>Transportation Portal</h1> </div> <div class="topnav"> <ul> <li><a href="">Home</a></li> <li><a href="">Search</a></li> <li><a class="active" href="">Add</a></li> </ul> </div> </body> </html> style.css * { margin: 0px; padding: 0px; outline: none; border: 0px; } .headerbar { height: 70px; width: 100%; position: relative; margin-left: 0px; margin-right: 0px; padding-left: 0px; padding-right: 0px; border: none; background: #4b6cb7; … -
Django admin two step import from Excel with formset-validation on the second step
I have to import some SKU to Order from excel, but I have to show validation form with error-fields and make some changes for fields before save import results. All in Django admin. Here is 2-nd step mockup (in Russian only, sorry) I can not understand how to generate custom formset page in django admin, with working validation and using initial data. I am understanding how to create custom form pages in django-admin: context = { 'title': 'Import', 'app_label': self.model._meta.app_label, 'opts': self.model._meta, 'has_change_permission': self.has_change_permission(request), 'form': form, 'adminform': admin.helpers.AdminForm(form, list([(None, {'fields': form.base_fields})]), self.get_prepopulated_fields(request)) } return render(request, 'admin/orderscomposing/import.html', context) But it does not work for formsets -
django drag and drop ordering for with many to many relationship of table
ManyToMany admin.TabularInline to display related objects in the admin app, and it works great except I can't figure out what to set the "ordering" property to so it can sort by one of the cross-referenced field names. I used this module django-admin-ordering==0.9.0.