Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django change __str__ depends on a field
I need to show a description in the field that depends on the "TYPE" in another field and look for an ID that is at the top level. Exemple: 3 types of accounts: P - TOP LEVL S - Syntetic A - Analitic Should show a dropdown just "A" and descriprion with up level of that. P: 1. Main S: 1.1 - base 1 A: 1.1.1 - value 1 - base 1 A: 1.1.2 - value 2 - base 1 S: 1.2 - base 2 A: 1.2.1 - value 1 - base - 2 My model and data: class Plano_Conta(models.Model): id = models.CharField(max_length=12, primary_key=True) descricao = models.CharField(max_length=100) tipo = models.CharField(max_length=1, choices=TIPO_CONTA) def __str__(self): return self.id + ' - ' + self.descricao class Meta: ordering = ('id',) class Lancamento(models.Model): user = models.ForeignKey(User, on_delete=models.CASCADE) plano_conta = models.ForeignKey(Plano_Conta, on_delete=models.CASCADE) no_documento = models.CharField(max_length=100) data = models.DateTimeField() descricao = models.CharField(max_length=100) valor = models.DecimalField(max_digits=7, decimal_places=2) tipo = models.CharField(max_length=1, choices=TIPO_OPERACAO) def __str__(self): return self.descricao class Meta: ordering = ('data',) database: id |descricao |tipo| -----+-----------------------+----+ 1 |Receita |P | 1.1 |Vendas Internas |S | 1.1.1|Escola |A | 1.1.2|Escritório |A | 1.2 |Vendas Externas |S | 1.2.1|Livro |A | 1.2.2|Brinquedos |A | 2 |Despesas |P | 2.1 |Fornecedores |S … -
I want to restrict multiple user logins but no previous answers are helping me?
I want to restrict multiple user logins like when a user tries to login again i want to give him a error saying you already have a active session This is how i am doing it right now my middleware.py class MySessionMiddleware: def __init__(self, get_response): self.get_response = get_response def __call__(self, request): response = self.get_response(request) print(request.user.is_authenticated) if request.user.is_authenticated: print('here2') try: user = LoggedInUser.objects.create(user=request.user) except: user = LoggedInUser.objects.filter(user=request.user).first() print(type(user)) if not request.session.session_key: request.session.save() prev_session_key = request.user.logged_in_user.session_key print(prev_session_key) if prev_session_key: print(prev_session_key) print(request.session.session_key) print('here5') #check whether old key is same as current print('here inside user.session_key') if prev_session_key != request.session.session_key: return JsonResponse("you already have a active session kindly logout from that", status=400, safe=False) user.session_key = request.session.session_key user.save() return response my models.py class LoggedInUser(models.Model): user = models.OneToOneField(User, related_name='logged_in_user', on_delete =models.CASCADE, null=True, blank=True) session_key = models.CharField(max_length=32, null=True, blank=True) But this approach is not working as previous session key always comes out to be None , please suggest changes in my approach , i tried many solutions but they didnt work -
How to get value of the field of a referenced model in django?
Say, I have defined two models like so My_CHOICE_SELECTION = ( ('Option_1', 'Option_1'), ('Option_2', 'Option_2'), ) class CustomUser(AbstractUser): user_field_1 = models.CharField(max_length=100, blank=True, null=True) user_field_2 = models.CharField(max_length=20, choices=My_CHOICE_SELECTION) class UserProfile(models.Model): user = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE) # Some Profile fields here profile_filed_1= models.CharField(max_length=100, blank=True, null=True) # Over-ride save method def save(self, *args, **kwargs): super(UserProfile, self).save(*args, **kwargs) # **** How do I get the value here for my if condition? **** if (<--Check for value in CustomUser.user_field_2 -->): # If true do something else: # Else do something else How do I get I check for value of user_field_2 of CustomUser model in my UserProfile model? I tried doing like so if CustomUser.objects.user_field_2 == 'required_value': # Do something I am getting the following error 'UserManager' object has no attribute 'user_field_2' -
How to transition from M2M created with 'through' to a M2M managed by Django
I'm working in a Project where there were multiple fields created as M2M using the through related model, however they were wrongly created by then and the related models have no additional fields, so I would like to use a regular M2M managed by Django. The existing models I have are: cass Student(models.Model): # ... other fields..." course = models.ManyToManyField( Course, related_name='students', through='StudentCourse' ) class StudentCourse(models.Model): student = models.ForeignKey(Student, on_delete=models.CASCADE) course = models.ForeignKey(Course, on_delete=models.CASCADE) cass Course(models.Model): # ... other fields..." And I would like to have: class Student(models.Model): # ... other fields..." course = models.ManyToManyField(Course, related_name='students') class Course(models.Model): # ... other fields..." I'm not able to find a way in Django to do this without losing the data that was already inserted. I was thinking of renaming the tables in the same way Django does and manipulate the Django migration metadata but it is an ugly way to solve it. Is there a Django way to solve this without losing the data (or creating backup tables)? -
How do not flush django session?
My django cart based on django session, when i log out django uses flush() def clear(self): # To avoid unnecessary persistent storage accesses, we set up the # internals directly (loading data wastes time, since we are going to # set it to an empty dict anyway). self._session_cache = {} self.accessed = True self.modified = True and cart is emptied. I dont want it. -
Django exclude url pattern
i have a basic django app and want to exclude a route from matching other routes with similar structure below is my urls.py from django.urls import path from . import views app_name = 'blogs' urlpatterns = [ path('', views.index, name = 'index'), path('<str:handle>', views.show, name = 'blogs'), ] i want path('create'), views.create, name = 'create') to go to the create blog page, and path('<str:handle>', views.show, name = 'blogs'), to go to the details page for a blog. i get a 404 blog not found error when i navigate to http://localhost:8000/blogs/create how do i exclude the create from matching the <str:handle> for a blog detail page? -
Django bug report, different foreign key as URL parameter will cause detailed view not executing
This bug is so subtle I couldn't really find a niche way to describe it, For example I have two apps, News and Blogs In blogs.py model I have something like this: class BlogType(models.Model): blog_type = CharField(max_length=20) def __str__(self): return self.blog_type class Blogs(models.Model): title = models.CharField(max_length=20) blog_author = models.ForeignKey(User, on_delete=models.CASCADE) blog_type = models.ForeignKey(BlogType, on_delete=models.DO_NOTHING) here a blog_type is a foreignkey defined inside the same models.py In blogs url.py from django.urls import path, re_path from . import views from .views import blogspage urlpatterns = [ path('', views.blogs, name='blogs'), re_path(r'(?P<blog_type>[\w-]+)/(?P<pk>[0-9]+)$', blogspage.as_view(), name='blogspage'), ] Here using the forignkey as a url parameter And in blogs views.py class blogspage(DetailView): model=Blogs template_name='blogs/blogspage.html' def get_context_data(self, **kwargs): context = super().get_context_data(**kwargs) print('Print the object if this is executed', self.get_object()) In Django template you would pass something like: <div><a href="{% url 'blogspage' b.blog_type b.id %}">{{b.title}}</a></div> Now the news model.py you have: class NewsType(models.Model): news_type = CharField(max_length=20) def __str__(self): return self.news_type class News(models.Model): title = models.CharField(max_length=20) news_author = models.ForeignKey(User, on_delete=models.CASCADE) news_type = models.ForeignKey(NewsType, on_delete=models.DO_NOTHING) The news views, news urls, news templates, are the exactly the same as blog except the name and template name, basically replacing every single "blogs" to "news" Then here is where the bug would occur, Only … -
AWS EB CLI Django
I have successfully managed to deploy my django project on aws eb using eb cli through pycharm terminal local project on windows pc, however I would like to accesss the project via eb instance on aws console to edit some files individually instead of deploying the whole project each time. I connected to the EC2 instance of my project enviornment on the aws EC2 instance connect and brings up the elastic beantalk ec2 message however I'm unable to find my project files within this console. Is there a way to access my already deployed project with aws console, if so how? Thanks in advance -
Why are my django validators not importing?
I have a basic django project (mysite), with a single app: my_app. The app has this in models.py: from django.db import models from mysite.validators import global_file_validator from .validators import local_file_validator class Test(models.Model): file = models.FileField(validators=[global_file_validator, local_file_validator]) It's defining a single FileField that must pass 2 validators. One of the validators (global_file_validator) is more generic, so it's defined under mysite.validators, where multiple apps can use it. The other validator is specific to this app, so it's defined in this app, under my_app/validators/local_file_validator.py. As far as I can tell, everything should work, but when I try to do a ./manage.py makemigrations, I get this: Traceback (most recent call last): File "./manage.py", line 22, in <module> main() File "./manage.py", line 18, in main execute_from_command_line(sys.argv) File "/home/tal/test_django_app/venv3/lib/python3.8/site-packages/django/core/management/__init__.py", line 419, in execute_from_command_line utility.execute() File "/home/tal/test_django_app/venv3/lib/python3.8/site-packages/django/core/management/__init__.py", line 413, in execute self.fetch_command(subcommand).run_from_argv(self.argv) File "/home/tal/test_django_app/venv3/lib/python3.8/site-packages/django/core/management/base.py", line 354, in run_from_argv self.execute(*args, **cmd_options) File "/home/tal/test_django_app/venv3/lib/python3.8/site-packages/django/core/management/base.py", line 398, in execute output = self.handle(*args, **options) File "/home/tal/test_django_app/venv3/lib/python3.8/site-packages/django/core/management/base.py", line 89, in wrapped res = handle_func(*args, **kwargs) File "/home/tal/test_django_app/venv3/lib/python3.8/site-packages/django/core/management/commands/makemigrations.py", line 88, in handle loader = MigrationLoader(None, ignore_no_migrations=True) File "/home/tal/test_django_app/venv3/lib/python3.8/site-packages/django/db/migrations/loader.py", line 53, in __init__ self.build_graph() File "/home/tal/test_django_app/venv3/lib/python3.8/site-packages/django/db/migrations/loader.py", line 214, in build_graph self.load_disk() File "/home/tal/test_django_app/venv3/lib/python3.8/site-packages/django/db/migrations/loader.py", line 116, in load_disk migration_module = import_module(migration_path) File "/usr/lib/python3.8/importlib/__init__.py", line 127, … -
Is it normal that manage.py runserver has better perfs than my gunicorn/nginx conf?
I have performance issues on my DRF API. The thing is that running manage.py runserver way better performance then my prod gunicorn/nginx server. I don't know if it's "normal" ? I didn't find a lot of resources to fully understand gunicorn/nginx to be able to realy optimize them correctly. I only found some medium articles like this one that talks mainly about threads and that didn't help me close that perf gap. I run : gunicorn --access-logfile /var/log/gunicorn/access.log --error-logfile /var/log/gunicorn/error.log --capture-output --log-level debug --timeout 12000 website.wsgi:application --workers 3 --threads 4 --reload & And I got this in my nginx : upstream django { server 127.0.0.1:8000; } limit_req_zone $binary_remote_addr zone=pretrainedlimit:50m rate=10r/s; server { listen 80; server_name api.ai-compare.com; # customize with your domain name client_max_body_size 20M; proxy_set_header X-Forwarded-Proto $scheme; proxy_connect_timeout 600; proxy_send_timeout 600; proxy_read_timeout 600; send_timeout 600; location / { proxy_pass http://django; } location /v1/pretrained/ { limit_req zone=pretrainedlimit burst=10; proxy_pass http://django; } } I test perfs with Apache Jmeter. Do you guys have good resource on the subjet ? -
I am getting no module name cleo when trying to do "poetry add"
I have completely uninstalled and re installed poetry using: POETRY_UNINSTALL=1 bash -c 'curl -sSL https://raw.githubusercontent.com/sdispater/poetry/master/get-poetry.py | python' then I re installed it using: curl -sSL https://raw.githubusercontent.com/python-poetry/poetry/master/get-poetry.py | python - but it did not fix the issue. and then I # for poetry config export PATH="$HOME/.poetry/bin:$PATH" -
How to start django server using wsgi.py, I'm trying to use gunicorn
I'm trying to deploy my server (no longer in development) but I cannot figure out how to deploy it. Documentation from django's website recommends using gunicorn, but it seems like it might be outdated. Either that or I was viewing the tutorial for the wrong version of django. How do I deploy the non-development server using wsgi.py? Earlier it was suggested to me to follow this link but it doesn't appear to actually describe how to go about using wsgi.py. Can someone explain to me how to deploy the server and if I need gunicorn? -
How to config DATETIME_INPUT_FORMATS to accept timestamp?
Is there anyway to accept timestamp as an input for DateField and DateTimeField fields by configuring DATETIME_INPUT_FORMATS? I can convert all my outputs to timestamp using : REST_FRAMEWORK = [ "DATETIME_FORMAT": "%s" ] But it seems having %s for inputs does not work: REST_FRAMEWORK = [ "DATETIME_FORMAT": "%s", "DATETIME_INPUT_FORMATS": ["%s"], ] It raises this validation error: { "my_field_name": [ "Date has wrong format. Use one of these formats instead: %s." ] } -
How do I use foreign key in django to have item sets?
Models.py from django.db import models # Create your models here. class Project_types(models.Model): project_type = models.CharField(max_length=200) def __str__(self): return self.project_type class Projects(models.Model): project_types = models.ForeignKey(Project_types, on_delete=models.CASCADE) project = models.CharField(max_length=200) def __str__(self): return self.project class SourceCode(models.Model): project = models.ForeignKey(Projects, on_delete=models.CASCADE) source_code = models.CharField(max_length=99999) def __str__(self): return self.source_code Views.py from django.shortcuts import render from .models import Project_types, Projects def homepage(response): data = Project_types.objects.all() return render(response, 'main/homepage.html', {'project_types': data}) def hacks(response): return render(response, 'main/hacks.html', {'hacking_projects':"n"}) def games(response): type = Project_types(project_type='games') t = type.projects_set.all() return render(response, 'main/games.html', {'gaming_projects': t}) main/games.html <!DOCTYPE html> <html> <head> <title>My Gaming Projects</title> </head> <body> <header>My Gaming Projects</header> <p>{{gaming_projects}}</p> </body> </html> The problem is when I go into my django admin I clearly have a project by the name of "gaming project" under the project type 'games'. However when displaying it on my site it just shows a empty query. -
Uploading a File from Django FileField to Nex.js public folder
Is there a way to upload a file in Django outside of the project directory? I am trying to upload a file/image from the front-end (Next.js) through a FileField in Django and save it in the public folder of the Next.js project directory as that's where all my images are served from. In this scenario, Django and Next are sibling folders on the server. If I try to upload anything above the Django project folder via FileField, I get the error: Detected path traversal attempt... I can use FileSystemStorage, but this is not supposed to be used in production. How can I upload a file through Django to a folder outside of the project directory and place it in the Next.js public folder successfully? -
Django: list_display accepts field but not list_filter
I have the following admin class: class AppointmentAdmin(admin.ModelAdmin): list_display = ('branch', 'date', 'timeslot', 'sold_to', 'unit', 'VIN') list_filter = ('branch', 'date', 'sold_to', 'unit', 'VIN') def VIN(self, obj): return obj.unit.vin I get the following error: <class 'catalog.admin.AppointmentAdmin'>: (admin.E116) The value of 'list_filter[4]' refers to 'VIN', which does not refer to a Field. If I remove VIN from list_filter, it executes fine. The list_display will show me the field VIN. What am I doing wrong? -
Running python 3 in sandbox with TensorFlow
I am currently trying to make a website which will run user submitted TensorFlow programs, I have the website ready along with the TensorFlow system, but as I do not have much experience with security, I am not sure how I should run user submitted TensorFlow programs securely. The website is written in Django and everything is currently running on a ubuntu virtual machine on a local server, what could be a good way to run the user submitted programs securely and also restrict the compute time of each script to ~ 1 second for each inference? -
Understanding Python UUID
I’m new to python and had been working with UUID mostly as an Android developer as identifiers to send for REST calls. In Java/Android I have never treated UUID as anything other than a character string, passed back and forth (in many cases to Django REST application) Now I am working with Python on my own Django app I recognized that UUID is an object with various methods attached. I am confused. My initial task was to convert the UUID to base 64 (request.user.id is UUID for me) and decode it at a later time. There seems to be a lot of answers here with various approach. It is starting to be more complex. I expected a character string. I would appreciate some clarity and help with understanding UUID object. -
Django: How render two or more FBV into one template
I'd like to direct more then one view to my file.html template. Unfortunly my second view function file_category doesn't render the context in my page. Is there a specific way to do so? Thanks VIEWS def file_view(request, file_id): file = File.objects.filter(pk=file_id) files_p = File.objects.filter(user=request.user.userprofile) context = { 'file': file, 'files_p': files_p , } return render(request, 'file.html', context) def file_category(request): cat = list(for num in range(0, 37)) context = { 'cat': cat } return render(request, 'file.html', context) URLS urlpatterns = [ path('show/<file_id>', views.file_view, name="file"), path('show/<file_id>', views.file_category), ] -
Using django form many to many relationship model
I am quite new to using Django, but basically I have two models: Student and Module class Student(models.Model): student_id = models.CharField(max_length=4, unique=True) name = models.CharField(max_length=150) birthday = models.DateField() class Module(models.Model): name = models.CharField(max_length=150) code = models.IntegerField() student = models.ManyToManyField(Student) Now my question is, basically if I am using a Django form to add new students to the DB, how do I get the list of Modules I have in the DB. I can add students to the module for adding a new module form, but not sure how to do it the other way And say if I want to list all the modules a student is taking in a page, how do I access the modules those students are access to aswell? Any help is much appreciated -
What should my API endpoint look like in production?
I might be blocked from stackoverflow for asking this but I really don't know what to do. I guess I have to take the odds. I have this web app. Frontend is written with VueJS, backend with Django rest framework, and I am using MongoDB with docker volumes. On the Home page of my web app, Frontend sends a GET request to backend on /api/skills endpoint. When I handle things locally, everything is fine. I dockerize the frontend, backend, MongoDB and they all talk to each other in the same Docker network. This is looking nice on local development. The part that does the fetching looks like this. fetchSkillData: function () { const localUrl = "http://0.0.0.0:8000/api/skills"; axios .get(localUrl) .then((values) => { values.data.forEach((data) => { this.technologies.push(data); this.hideSpinner(); }); }) .catch(console.error); this.hideSpinner(); } I am not getting a CORS issue or anything else. However, on production, I have some issues. This is the Dockerfile for frontend: # build stage FROM node:13-alpine as build-stage RUN mkdir -p /home/app COPY ./frontend /home/app WORKDIR /home/app RUN npm install RUN npm install --save ant-design-vue RUN npm install --save mavon-editor RUN npm install --save axios RUN npm install --save raw-loader RUN npm run build # production stage … -
Issue with displaying alerts after failed logins
I am implementing a website as my final project and I want to display a message for users that failed to log in more than 3 times prompting them to reset their passwords. I have already tried different solutions I found online, but nothing is helping. I am writing the backend in Django, but Django-axes also didn't work for me, so I am trying JS now. <script type="text/javascript"> var login_attempts = 3; function checkAttempts() { var failed_alert = document.querySelectorAll("a")[0].textContent; if (failed_alert === " Invalid username or password ") { login_attempts--; console.log(login_attempts); alert('failed login') if (login_attempts==0) { alert("Do you want to reset your password?"); } } else { console.log(login_attempts); return false; } } </script> This is the example I found on Stack Overflow. I think I am close to solving this problem, I am getting messages, but when printing "login_attemps" in a console at first I get 3 and then continuously 2, no matter how many times I write incorrect password. The function is called in form. I also tried to do it in body onload="" and onsubmit <form id="login-form" class="form" action="login" method="post" onsubmit="checkAttempts();"> The whole authentication is implemented in views.py django: def login(request): if request.user.is_authenticated: return redirect('/') else: if request.method … -
Django rest api how to response serialized queryset
I have 3 models: class Book_type(models.Model): type_name = models.CharField(max_length=40,unique=True) class Author(models.Model): author_id = models.AutoField(unique=True, primary_key=True) author_name = models.CharField(max_length=30, unique=True) class Book(models.Model): book_id = models.AutoField(unique=True, primary_key=True) book_type = models.ForeignKey(book_type, on_delete=models.CASCADE, to_field='type_name') book_value = models.PositiveIntegerField(default=0, verbose_name='book value') book_unit = models.CharField(max_length=100, blank=True, verbose_name='book unit') book_time = models.DateTimeField(auto_now=False, verbose_name='book time') author = models.ForeignKey(verbose_name='author', to='author', to_field='author_id', on_delete=models.CASCADE) Both Book_type and Author are foreign keys to Book. Now in the views.py I want to return the following aggregate statistics for each author: 1.mininum book value, grouped by author and book type 2.average book value, grouped by author and book type 3.And annotate each set of aggregate statistics with the author's ID and name. Code: from .serializers import BookSerializer,AuthorSerializer,Book_typeSerializer class AggregateListView(ListAPIView): """Custom queryset api view. Does not implement pagination""" queryset = author.objects.values('author_name', 'author_id')\ .annotate(min_value=Min('book__book_value'), distinct=True)\ .annotate(max_value=Max('book__book_value'), distinct=True)\ .annotate(avg_value=Avg('book__book_value'), distinct=True)\ .annotate(count=Count('book__book_id'), distinct=True)\ .annotate(earliest_time=Max('book__book_time'), distinct=True)\ .annotate(lastest_time=Min('book__book_time'), distinct=True) serializer = AuthorSerializer(queryset, many=True) data = serializer.data return data["json"] While coded here I totally no clew how to continue, any friend can help ? -
JSONDecodeError at /update_item/ Expecting value: line 1 column 1 (char 0)
I’m a beginner. I have tried everything in the Django E-commerce website course, but it does not work for me. I also tried documentation but I didn’t get any solution. I have this error when I go to /update_item/ and the data is not showing up in the terminal: Expecting value: line 1 column 1 (char 0) error screenshot tutorial link tutorial link https://youtu.be/woORrr3QNh8 cart.js var updateBtns = document.getElementsByClassName('update-cart') for (i = 0; i < updateBtns.length; i++) { updateBtns[i].addEventListener('click', function(){ var productId = this.dataset.product var action = this.dataset.action console.log('productId:', productId, 'Action:', action) console.log('USER:', user) }) } function updateUserOrder(productId, action){ console.log('User is authenticated, sending data...') var url = '/update_item/' fetch(url, { method:'POST', headers:{ 'Content-Type':'application/json', 'X-CSRFToken':csrftoken, }, body:JSON.stringify({'productId':productId, 'action':action}) }) .then((response) => { return response.json(); }) .then((data) => { location.reload() }); } views.py def updateItem(request): data = json.loads(request.body) productId = data['productId'] action = data['action'] print("Action",action) print("Pordutcs:",productId) customer = request.user.customer product = Product.objects.get(id=productId) order, created = Order.objects.get_or_create(customer=customer , complete=False) orderitem, created = Orderitem.objects.get_or_create(order= order,product=product) if action == 'add': orderitem.quantity = (orderitem.quantitiy +1) elif action == 'remove': orderitem.quantity = (orderitem.quantity -1) orderitem.save() if orderitem.quantity <= 0: orderitem.delete() return JsonResponse("Item was added", safe=False) store.html {% extends 'store/main.html' %} {% load static %} {% block content … -
How to get url params from the HttpRequest object
Suppose, we have a url path: path('something/<int:some_param>/test/', views.some_view) When a user hits this url, django makes an instance of HttpRequest, that will be passed to the some_view view. Is there a way to get the some_param url parameter from the request object outside the some_view code? (for instance, to do some processing that depends on some_param in a custom middleware). One possible solution is to parse the HttpRequest.path attribute, but is there any prebuilt way to do this?