Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django Modle: ValidationError at / ['ManagementForm data is missing or has been tampered with']
I'm new to Django, when i'm trying to upload multi image to server, i'm getting below error message, ValidationError at / ['ManagementForm data is missing or has been tampered with'] Below is my sample code: models.py class Upload(models.Model): title = models.CharField(max_length=50) img = models.FileField(upload_to='images') def __str__(self): self.title forms.py class UploadForm(forms.ModelForm): title = forms.CharField(max_length=50) img = forms.FileField( widget=forms.ClearableFileInput(attrs={'multiple': True}) ) class Meta: model = Upload fields = '__all__' views.py def index_views(request): msg = str form = UploadForm() ImageFormSet = modelformset_factory(Upload, form=UploadForm, extra=3) if request.method == 'POST': formset = ImageFormSet(request.POST, request.FILES, queryset=Upload.objects.none()) if formset.is_valid(): for form in formset.cleaned_data: if form: img = form['img'] photo = Upload(title=request.cleaned_data['title'], img=img) photo.save() msg = 'Success' content ={ 'form': form, 'msg': msg } return render(request, 'index.html', content) Can any one please help me on the same. -
can't use reverse url function in django
tests.py from django.test import TestCase from django.urls import reverse from rest_framework import status from .models import User class UserCreateAPIViewTestCase(APITestCase): def setUp(self): super().setUp() self.url = reverse("admins") def test_user_creating(self): user_data = {} response = self.client.post(self.url, user_data, format="json") self.assertEqual(response.status_code, status.HTTP_403_FORBIDDEN) 2.urls.py from django.urls import path from django.conf.urls import include from rest_framework_nested.routers import SimpleRouter from apps.users.views import ( CreateProviderViewSet, LoginViewSet, UserViewSet, ProviderViewSet, ClientViewSet, LoginAsViewSet ) app_name = 'users' router = SimpleRouter(trailing_slash=False) router.register("admins", UserViewSet, base_name='admins') router.register("providers", ProviderViewSet, base_name='providers') router.register("clients", ClientViewSet, base_name='clients') router.register("login", LoginViewSet, base_name='auth') router.register("login-as", LoginAsViewSet) urlpatterns = [ path('', include(router.urls)), ] when I run python .\manage.py test apps.users.tests This error occurs ERROR: test_user_creating (apps.users.tests.UserCreateAPIViewTestCase) ---------------------------------------------------------------------- Traceback (most recent call last): File "C:\Users\vu.tran\Desktop\kona-server\apps\users\tests.py", line 19, in setUp self.url = reverse("admins") File "C:\Users\vu.tran\Desktop\kona-server\env\lib\site-packages\django\urls\base.py", line 90, in reverse return iri_to_uri(resolver._reverse_with_prefix(view, prefix, *args, **kwargs)) File "C:\Users\vu.tran\Desktop\kona-server\env\lib\site-packages\django\urls\resolvers.py", line 668, in _reverse_with_prefix raise NoReverseMatch(msg) django.urls.exceptions.NoReverseMatch: Reverse for 'admins' not found. 'admins' is not a valid view function or pattern name. my structure folders like this my folders I wonder why cannot get reverse("admins") Do you have any idea? -
How to calculate duration between two time using datatables?
Currently, I already retrieve some data from a database using data tables, for example, the entered time and left time. But, I want to calculate the duration between these two time. Seems this time is in their format, so it can't be calculated, right? Below are the codes. If you noticed, I already try to subtract the left with the entered time but, it's not working at all. Or should I make the calculation at the backend of python/Django? $(function () { var currentDate = new Date() var day = currentDate.getDate() var month = currentDate.getMonth() + 1 var year = currentDate.getFullYear() var d = day + "-" + month + "-" + year; // Datatables intialisation jQdtRpt = $('#dtBasicExample').DataTable({ columns: [ {title: "Tag", data: "tag.name"}, {title: "Name", data: "tag.alternate_name"}, {title: "Station", data: "station.name"}, {title: "Entered Time", data: "entered", render:function(data){ return moment(data).format('MM/DD/YYYY h:mm:ss a'); }}, {title: "Left Time", data: "left", render:function(data){ return moment(data).format('MM/DD/YYYY h:mm:ss a'); }}, {title: "Duration", data: "left - entered", render:function(data){ return moment(data).format('h:mm:ss'); }}, ], dom: 'lfrtipB<"clear">', buttons: [ { extend: 'copy', exportOptions: { format: { header: dtBtnExpOptFmtHdr } } }, { extend: 'csv', title: 'report_user_history_' + d, exportOptions: { format: { header: dtBtnExpOptFmtHdr } } } ], }); … -
Can't access admin portal after logging in via DRF with Djoser Token Authentication
I am implementing a TokenAuthentication using Djoser djoser.urls.authtoken via /api/auth/token/login/. I can login just fine but when I go to /admin/ it redirects me to Django's admin login page and requires me to login again. I then realized /admin/ and /api/auth/token/login/ are different things. How can I access the admin portal or tell Django to allow me to open /admin/ when I login via this DRF? -
Getting an AttributeError on posting the data to database having foriegnkey relation in django?
I am having a users and furniture table I want to store the furniture id selected by the user in the users table through the form the furniture field is having the foreign key relationship with the furniture table while posting I am getting this error My models.py is: class furniture(models.Model): id=models.IntegerField(primary_key=True) phrase=models.CharField(max_length=60,default='111111') class users(models.Model): email=models.CharField(max_length=50,default='0000000') password=models.CharField(max_length=50,default='0000000') room = models.ForeignKey(rooms,on_delete=models.CASCADE) goal = models.ManyToManyField(goals) style = models.ManyToManyField(designs) furniture = models.ForeignKey(furniture,on_delete=models.CASCADE) My views.py : def user_register(request): if request.method == 'POST': username=request.POST["username"] email = request.POST['email'] password = request.POST['password'] room = request.POST['room'] g=goal=request.POST['goal'] g = g.split(',') s=style=request.POST['style'] s=s.split(',') furniture=request.POST['furniture'] user = users(password=password,email=email) user.room=rooms.objects.get(pk=room) goal = goals.objects.filter(pk__in=g) style = designs.objects.filter(pk__in=s) request.encoding = 'koi8-r' user.furniture = furniture.objects.all() user.save() user.goal.add(*goal) user.style.add(*style) return render(request,'home.html') My form.html is: <div class="card-body"> <form action="{% url 'car:user_register' %}" method="POST" > {% csrf_token %} <div class="form-group"> <label for="username">Username</label> <input type="text" name="username" class="form-control" required> </div> <div class="form-group"> <input type="text" name="room" id="name" value=" "> </div> <div class="form-group" > <input type="text" name="goal" id="goal" value=" "> </div> <div class="form-group" > <input type="text" name="style" id="style" value=" "> </div> <div class="form-group" > <input type="number" name="furniture" id="furniture" value=" "> </div> <div class="form-group"> <label for="email">Email</label> <input type="text" name="email" class="form-control" required> </div> <div class="form-group"> <label for="password2">Password</label> <input type="password" name="password" class="form-control" required> </div> … -
Django set settings from a non module directory
I'm using Django 2.2 My directory structure is / |- docs |- scripts |- src |- app |- settings |- __init__.py |- local.py |- development.py |- wsgi.py |- other_modules |- templates |- manage.py |- Pipfile |- Pipfile.lock All the Django application is inside src directory (src is not a module). I use pipenv to run the application from root directory as pipnev run python src/manage.py runserver I want to setup DJANGO_SETTINGS_MODULE DJANGO_SETTINGS_MODULE=app.settings.development But it gives ModuleNotFoundError:. How can I set module from src directory, which is a non-module directory. -
Best practice to manage persistent Django migrations files in kubernetes volumes
I need to store in some kubernetes volume the migrations files in order to do not miss the history. On docker compose you can mount a persistent volume but I didn't undestand how i can achieve this on Kubernetes volumes and how i can set the migration path on the pod deployment .yml file apiVersion: apps/v1 kind: Deployment metadata: name: cc-d spec: selector: matchLabels: app: cc replicas: 2 template: metadata: labels: app: cc spec: containers: - name: cc image: user/myimage:latest imagePullPolicy: Always ports: - containerPort: 8000 command: ["gunicorn", "cc.wsgi:application", "--timeout", "300", "-w", "2", "-b", "0.0.0.0:8000"] volumeMounts: - ? -
TypeError at /api/chart/data/ expected string or bytes-like object
im currently facing an issue where i am getting this error and i do not know why. TypeError at /api/chart/data/ expected string or bytes-like object My code is : class ChartData(APIView): authentication_classes = [SessionAuthentication, BasicAuthentication] permission_classes = [IsAuthenticated] def get(self, request, format=None): current_user = request.user completed_tasks_per_month = Sales_taskings.objects.filter(sales_extras = current_user.id).filter(date_time = date.today().year).filter(status = 'p4').annotate(month=ExtractMonth('date_time')).values('month') data ={ "taskings":completed_tasks_per_month, } return Response(data) here is my tasking models: class Sales_tasking_comments(models.Model): comment_id = models.AutoField(primary_key=True) sales_extras = models.ForeignKey('sales.Sales_extras',on_delete=models.CASCADE) sales_taskings= models.ForeignKey('sales.Sales_taskings',on_delete=models.CASCADE) comment = models.TextField(max_length=200 , default='your notes') date_time = models.DateTimeField(auto_now=True) so far i have been searching online for answers and have tried adding a __in at sales_extras , doing so will resolve the TypeError at /api/chart/data/ expected string or bytes-like object error but will results in a TypeError at /api/chart/data/ 'int' object is not iterable removing all my chain queries will also resolve my issue but i would like to filter my results through my view. Your help will be greatly appreciated! -
What technologies should I use to create my own real time database and backend for a social media Android app without using Firebase?
I am developing a Instagram-like android app for educational purposes.I want to host it in my own computer and create my own back-end service. I want like to have a guided map detailed in relevant order on how I should achieve the below context. " How I can create my own database for user authentication, storing profile data etc? How would I store images(categorized by profiles) in directories and use the code to access them? What should i use to host the database and connect it to the app(any rest api technologies) What technologies should I learn to do so(eg: django, SQL, apache HTTP client or anything relevant)? " I want to do all of the above without the use of any thirdparty service like AWS, Firebase. -
Django, using JavaScript to create and download a file with href
I am attempting to have a button call a JavaScript script to create file and an href element then click itself to download the file. The file is created by calling a function via a model object, {{ graph.create_png_location }}. Here is what I have so far: <input type="submit" id="plot_down" value="Download Plot" class="downloader" onclick="download()"> <script> function download() { {{ graph.create_png_location }} var ele = document.getElementById('plot_down'); ele.style.background-color = #17408B; //creating an invisible element var element = document.createElement('a'); element.setAttribute('href', '{% static 'analyze/images/your_plot.png' %}'); element.setAttribute('download', 'plot.png'); //the above code is equivalent to // <a href="path of file" download="file name"> document.body.appendChild(element); //onClick property element.click(); document.body.removeChild(element); } </script> The code for my create_png_location essentially just creates a plot in the static folder. This part is working as the plot is showing up in my file explorer. Also for some reason the background color does not seem to be changing at all for the var ele = document.getElementById('plot_down'); I created. Does it matter if it takes a bit of time to create the plot first? def create_png_location(self): csv_path = os.path.join(os.getcwd(), 'analyze', 'static', 'analyze', 'data', 'my_csv.csv') df = Api.get_existing_data_frame(csv_path=csv_path, logger=logging.getLogger(__name__)) outlier_count = 5 save_path = os.path.join(os.getcwd(), 'analyze', 'static', 'analyze', 'images', 'plot.png') plot_path, _, _ = Api.create_scatter_plot_with_trend_line(x_key=self.x_key.__str__(), y_key=self.y_key.__str__(), … -
How to display field values from ManyToMany through model
I have the following models with a ManyToMany through relationship. from django.db import models class Person(models.Model): name = models.CharField(max_length=50) class Group(models.Model): name = models.CharField(max_length=128) members = models.ManyToManyField( Person, through='Membership', through_fields=('group', 'person'), ) class Membership(models.Model): group = models.ForeignKey(Group, on_delete=models.CASCADE) person = models.ForeignKey(Person, on_delete=models.CASCADE) inviter = models.ForeignKey( Person, on_delete=models.CASCADE, related_name="membership_invites", ) invite_reason = models.CharField(max_length=64) When displaying a DetailView for Group to print the person.name I can use: {% for person in group.person.all %} {{ person.name }} {% endfor %} How can I add a reference to print invite_reason in this for loop? -
Django template integer value iteration
I have the following model class Table(models.Model): # Some not important attrs rows = IntegerField(etc) cols = IntegerField(etc) Then I have my view where I'm rendering objects of this model. And I need to build some HTML tables based on the quantity of each objects' rows and cols quantity. I'm trying to do something like: {% for table in tables %} <table> <thead> <tr> {% for col in table.cols %} <th>column label here</th> {% endfor %} </tr> </thead> <tbody> {% for row in table.rows %} <tr>my row</tr> {% endfor %} </tbody> </table> {% endfor %} I know it is possible to loop for key in dict. But the values cols and rows are integers. How can I achieve this on a Django template? -
Fail to launch Django project on localhost
I tried to open the project from GitHub https://github.com/konradgalczynski07/vinciu I used Pycharm to open the whole coding file . When I run the web app with localhost , it fails and show the below errors : >Watching for file changes with StatReloader > Performing system checks... > > System check identified no issues (0 silenced). > Exception in thread django-main-thread: > Traceback (most recent call last): > File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\base\base.py", > line 220, in ensure_connection > self.connect() > File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\asyncio.py", > line 26, in inner > return func(*args, **kwargs) > File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\base\base.py", > line 197, in connect > self.connection = self.get_new_connection(conn_params) > File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\django\utils\asyncio.py", > line 26, in inner > return func(*args, **kwargs) > File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\backends\postgresql\base.py", > line 185, in get_new_connection > connection = Database.connect(**conn_params) > File "C:\Users\User\AppData\Local\Programs\Python\Python38\lib\site-packages\psycopg2\__init__.py", > line 126, in connect > conn = _connect(dsn, connection_factory=connection_factory, **kwasync) > psycopg2.OperationalError: could not connect to server: Connection refused (0x0000274D/10061) > Is the server running on host "localhost" (::1) and accepting > TCP/IP connections on port 5432? > could not connect to server: Connection refused (0x0000274D/10061) > Is the server running on host "localhost" (127.0.0.1) and accepting > TCP/IP connections on port 5432? > > > The above exception was the direct … -
Django how to save a part of model object (one attribute each time ) using ajax in views
I want to save an object in Django models using Ajax. But I've faced a problem in views because I have a little complicated models (as saving). The problem is when I want to save an attribute of a model I don't know how to save the next attribute in the same model because Ajax call the view function each time we submit the form , so how to create that view function to save the attribute. these are my models and I hope you can help me because it is very important to me: ( when the user click on the "period" field he will fill his data and he will hit submit, so I need to save each time one attribute of the timetable class in the database using view function so I can save the whole timetable model) class Period (models.Model): module = models.ForeignKey(Module, on_delete=models.CASCADE, related_name='modules') teacher = models.ForeignKey(Teacher, on_delete=models.CASCADE,related_name='teachers') classroom = models.ForeignKey(Classroom, on_delete=models.CASCADE, related_name='classrooms') // I didn't put the other classes "Module","Teacher","Classroom" here class TimeTable(models.Model): // this class represent a time table for school first_first = models.ManyToManyField(Period, blank=True, related_name='peride_one') first_second = models.ManyToManyField(Period, blank=True, related_name='perides_two') first_third = models.ManyToManyField(Period, blank=True, related_name='perides_three') first_forth = models.ManyToManyField(Period, blank=True, related_name='perides_four') first_fifth = … -
I want to know how to set up a summer note download folder for a django project
The current download folder is set by two lines: settings.py MEDIA_ROOT = os.path.join(BASE_DIR,'_media') models.py image = models.ImageField(upload_to='wm/%y%m%d', blank=True) The storage folder for summer note images is another folder as the image below. I want to make sure that images saved as summer notes are also saved in the _media folder. But I don't know how to set it I would appreciate it if you could tell me about this. -
Database structure for storing unique! messages
I have a test task: develop a service that simulates the sending of messages into 3 instant messengers. It is also necessary to exclude the possibility of multiple sending the same messages (with the same content) to one user. I use Django and Celery with Redis as a backend and broker. My question is which database and structure is best for this task. Celery backend writes results to a simple table (redis in my case), and so far it works well, but I understand that this is a terrible approach in terms of optimization for the future, especially if it is assumed that several users will use the service. After all, before sending each message, I need to go through the entire database to check whether such a message has already been sent. It is clear that in this case it is an abstract local test task, but what should be done in a real project? I assume that 4 parameters will be included in my structure: User id. Instant messenger name. Recipient id. Message text. I can create a relational database/database with a table/collection for each user, but this approach also seems to me wrong, from the point of … -
Django Update Method for Viewset returning 415 even after overwritting it
Right now I am learning to create REST API with Django, but am struggling to implement the Update method. My tests always fail and I am not sure if it is because of the serializer or something else. Would appreciate some quick feedback for my code! class Company(models.Model): owner = models.ForeignKey(User, on_delete=models.CASCADE) name = models.CharField(max_length=50) class JobPost(models.Model): id = models.UUIDField(primary_key=True, default=uuid.uuid4, editable=False) company = models.ForeignKey(Company, on_delete=models.CASCADE, related_name='guest_posts') heading = models.CharField(max_length=100, default="") class CompanySerializer(serializers.ModelSerializer): class Meta: model = Company fields = ('name') class JobPostSerializer(serializers.ModelSerializer): company = CompanySerializer(read_only=True, required=False) class Meta: model = GuestPost fields = ('id', 'heading', 'company') def create(self, validated_data): request = self.context.get('request') company = Company.objects.get(title=request.data.get('company_name')) return GuestPost.objects.create(owner=request.user, heading=validated_data.get('heading'), company=company) def update(self, instance, validated_data): instance.heading = validated_data.pop('heading') instance.save() return instance class JobPostViewSet(viewsets.ViewSet, viewsets.generics.ListCreateAPIView, viewsets.mixins.UpdateModelMixin, viewsets.mixins.RetrieveModelMixin): permission_classes = (JobPostPermissions,) serializer_class = JobPostSerializer queryset = JobPost.objects.all() I then test this code, all my tests for the other operations (create, get, list) work but I get an error 415 when testing the update using the following method: class Test(TestCase): def setUp(self): self.user = User.objects.create(username="elon") self.factory = RequestFactory() self.request_url = '/api/job-post/' self.boring_company = Company.objects.create(owner=self.user, title="Boring Company") self.job_post = JobPost.objects.create(company=self.boring_company, heading="Looking for boring person") self.sample_uuid = self.job_post.id def test_update_post(self): data = { 'id': self.sample_uuid, 'heading': … -
No Module name 'encodings', deploying Django on a Linux Apache2
I try to deploy my Django Project on a Debian OS. I use the Anaconda 3 environment for the project that I've made. Here is the configuration of my Apache2 Alias /static /home/mydef/django_project/static <Directory /home/mydef/django_project/static> Require all granted </Directory> <Directory /home/mydef/django_project/django_project> <Files wsgi.py> Require all granted </Files> </Directory> WSGIScriptAlias / /home/mydef/django_project/django_project/wsgi.py WSGIDaemonProcess django_project python-path=/home/mydef/django_project python-home=/home/mydef/venv WSGIProcessGroup django_project Then Reload the Apache 2 (already enable my own apache2 conf file) Then I try to visit it localhost. But it didn't show any response (loading only). Then I check the error log then I see this error. Current thread 0x00007f4d175f1040 (most recent call first): [Thu Jan 02 05:58:14.571867 2020] [core:notice] [pid 9737:tid 139969081315392] AH00051: child pid 10145 exit signal Aborted (6), possible coredump in /etc/apache2 Fatal Python error: Py_Initialize: Unable to get the locale encoding ImportError: No module named 'encodings I also try Searching but still not solved -
No module named 'xx.xx'
I'm working on django and my directory is now i'm working on main directory's(learningUsers) url file and want to import views.py file from basic_app, but when i can't basic_app in main urls file and when trying to import like;from learningUsers.basic_app import views, its showing an error of No module named 'learningUsers.basic_app' -
subclassing listview to for referencing multiple views to one template django
Let's say in a website there is a profile page for users and it is a blog website. So every user has some blogs that they have written. So I want the profile page to be like: It will show the detailed stuffs about that user, like username, email. And also all the blogs they have written should be listed there. Now I have two views here, one for the detailed profile stuffs and another is for listing blogs written by the user. #view for detailed profile stuffs class ProfileDetailView(DetailView): model = User #view for listing blogs written by user class UserPostListView(ListView): model = Post paginate_by = 5 Now as you can see one view inherits from ListView and another inherits from DetailView. In order to use these two views to render what I am wanting, I can't pass two views to one template. So I need to subclass one of them.Now, as I want to keep pagination, I should subclass UserPostListView and maybe override get_context_data(). So how can I do this? I can't find any satisfactory answer. Also I am very new to django. Any help will be much appreciated. -
How can i get in choices=max_guest by room_id when I create django.models?
I have model like this: class KeyTransfer(Model): key_out_data = DateTimeField(null=True, blank=True) key_in_data = DateTimeField(null=True, blank=True) room_id = ForeignKey(Room, blank=True, null=True, on_delete=CASCADE) guests = IntegerField(choices=[(x, str(x)) for x in range(Room.objects.get(number=room_id).max_guests)], blank=True, null=True) notes = CharField(max_length=256, blank=True) person_id = ForeignKey(Person, null=True, blank=True, on_delete=SET_NULL) and i understand that i can`t save some value in column "guests" with argument "choices=" as you can see above. In a consequence I have gotten error: ...django.core.exceptions.AppRegistryNotReady: Models aren't loaded yet. ... and i see what this error means. The question is: can I realise some similar condition for "choices" in "guests" do not using django.forms? -
Django best practice for common class
I would like to make class like common.py and access from each application's views.py or management/commands For now my structure is like this myproj/myproj /myapplication/views.py /management/commands/mycommand.py then I add my orivinal class and call from each files like this. However , where should I put common.py and how to import??? For example making newfolder ?? but it might be confusing for application name?? myproj/myproj /myapplication/views.py /management/commands/mycommand.py /commonlib/common.py How is the best practice for this purpose?? -
How to deploy Django app from local machine on 'Django: certified by Bitnami' on AWS?
I have created a Django app which works well on my computer. I want to deploy it on AWS EC2 (on t2.micro). (There is an official guide for AWS Beanstalk (but it doesn't come under free tier) I have an EC2 instance running which has Django certified by Bitnami stack on it, it shows the successful installation screen: There isn't much documentation on it and no detailed tutorials available, since not many people are using it . How can I deploy the django app from my local machine (which has the database in it, currently having hundreds of rows) onto this EC2 instance? -
Django static files not being found
I moved around my folders in my project to better organize them a couple weeks ago but did not realize that this threw an HTTP error until today. The files which need to be found are Django admin static files which are included in the Django lib folder. The file links are: <script src="{% url 'admin:jsi18n' %}" type="text/javascript"></script> <script src="/static/admin/js/jquery.min.js" type="text/javascript"></script> <script src="/static/admin/js/jquery.init.js" type="text/javascript"></script> The first file path is throwing a 302 error: "GET /admin/jsi18n/ HTTP/1.1" 302 0 While this one is throwing a HTTP 404 error: "GET /static/admin/js/jquery.min.js HTTP/1.1" 404 1695 This is happening in both development and production environments. My static dir settings: STATIC_DIR = os.path.join(BASE_DIR, 'static') STATIC_URL = '/static/' STATICFILES_DIRS = [STATIC_DIR, ] Project directory structure: project └───apps └───[apps are here] └───config └───settings.py └───media └───static └───css └───js └───bg └───venv I have tried copying the admin folder from the Django lib and putting it directly in the static folder but this does not work so I am wondering why Django is not looking in the static or lib folders when it used to. -
Difference between admin.site.register and makemigrations in django
I'm beginner to django and got quite confused that what is the difference between register out models by admin.site.register and makemigrations in both cases we're mapping our tables to database, if i'm wrong kindly correct me. thank you