Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How do I fix this error ?? "Exception Value: range() integer end argument expected, got float. "
I couldn't find out the solution of the given error: Exception Type: TypeError Exception Value: range() integer end argument expected, got float. Code is given below: views.py file from django.shortcuts import render from .models import Product from math import ceil from django.http import HttpResponse def index(request): products = Product.objects.all() print(products) n = len(products) nSlides=n//4 + ceil((n/4)-(n//4)) params = {'no_of_slides':nSlides, 'range':range(1,nSlides), 'product': products} return render(request, 'shop/index.html', params) def about(request): return render(request, 'shop/about.html') -
How to accelerate template display with multiple heavy ModelChoiceFields?
Through a django form, I want to display quite a big number of ModelChoiceFields. These fields are identical (showing the same list of people). But, the thing is I have a lot of entry for those fields. The more fields I have, the more time it takes to load the template, even if I thought the queryset (identical for every fields) would be evaluated only once. Hypothesis and issue My hypothesis is that the queryset is evaluated as many times as the number of required fields. If that is what's happening, I have no idea how to optimize the way my fields are being initialised. What I want and what I don't I am not looking for a live search solution (ajax kinda), number of entries is acceptable when there is only one field (I've got a search field to filter people), the issue is really happening when I have more and more fields to display, even if the queryset is the same for each one. My code from django import forms from . import exceptions from django.contrib.auth.models import Group, User class MyForm(forms.Form): # defining a dict here, and using it in __init__ to define multiple fields within a loop … -
Django custom exception log to corresponding app log
I would like to have a different log file for all my applications in the project. Since they are based on celery I use the celery get_task_logger, but this is based on the standard python logger, therefore should not make a big difference. So far this works by using a logger with_ logger = get_task_logger(__package__) this will log to the different files defined in the settings.py with: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'filters': { 'require_debug_false': { '()': 'django.utils.log.RequireDebugFalse' } }, 'handlers': { 'project.app': { 'class': 'logging.handlers.RotatingFileHandler', 'filename': LOG_DIR + '/app.log', 'maxBytes': 1024 * 1024 * 10, 'backupCount': 3, 'formatter': 'standard', }, 'project.app2': { 'class': 'logging.handlers.RotatingFileHandler', 'filename': LOG_DIR + '/app2.log', 'maxBytes': 1024 * 1024 * 10, 'backupCount': 3, 'formatter': 'standard', }, }, 'loggers': { 'project.app': { 'handlers': ['project.app'], }, 'project.app2': { 'handlers': ['project.app2'], }, } } since I have a common area, that also contains a common exception handling I would like to log the exceptions to the corresponding file. The project structure looks like: app1 app2 common custom_exception how can I achieve to log the app to the corresponding app/task corresponding logfile, without having to pass the logger manually to the exception handler? -
React redux authentication with django not working
I am building a django react-redux based application. I am using Django rest framework's token authentication for authentication and using react-redux. My login is working perfect, after a user log's in his token is saved in the local storage. So if a user reloads his page or comes again, he doesn't need to login again. My login is working perfectly. But the saved auth token check method is not working. As per code after AUTH_TOKEN_CHECK_START, it should dispatch AUTH_TOKEN_CHECK_SUCCESS or AUTH_TOKEN_CHECK_FAIL but nothing is happening Check the below image, to understand more Actions.js export const authTokenCheckStart = () => { return { type: actionTypes.AUTH_TOKEN_CHECK_START, payload: { loading: true, isAuthenticated: false, token: null, } } }; export const authFail = (type:string) => { return { type: type, payload: { loading: false, isAuthenticated: false, token: null, user: null, error: null } } }; export const authTokenCheck = (token:string) => (dispatch:any) => { dispatch(authTokenCheckStart()); Axios.get(authSignupAPI, { headers:{ Authorization: `Token ${token}` } }).then((res)=>{ console.log(actionTypes.AUTH_LOGIN_SUCCESS); dispatch({ type:actionTypes.AUTH_TOKEN_CHECK_SUCCESS, payload:{ token: token, loading: false, isAuthenticated:true, user:res.data, error: null, } }) }).catch((error)=>{ localStorage.removeItem('Token'); dispatch(authFail(actionTypes.AUTH_TOKEN_CHECK_FAIL)) }) }; Reducer.js const authReducer = (state=initialState, action:any) =>{ switch (action.type) { case actionTypes.AUTH_LOGIN_START: return { ...state, loading: action.payload.loading, isAuthenticated: action.payload.isAuthenticated, token: action.payload.token, error: … -
Field 'id' expected a number but got 'natsu' django
I want to create a user_posts view that has all the posts related to a particular user let's say there is/are blog posts written by a user 'Natsu' then a logged-in user let's say 'Testuser' will be able to see all posts by that user i.e. all posts of user 'Natsu'. blog models.py class Post(models.Model): title = models.CharField(max_length=250) slug = models.SlugField(max_length=250, unique_for_date='publish') author = models.ForeignKey(User, on_delete=models.CASCADE, related_name='blog_posts') body = models.TextField() user models.py class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) image = models.ImageField(upload_to='profile_pic', default='default.jpg') def __str__(self): return f'{ self.user.username } Profile' views.py def user_posts(request, username): posts = Post.objects.filter(author=username) return render(request, 'blog/user_posts.html', {'posts':posts}) user_posts.html {% for post in posts %} <a href="{% url 'user-posts' post.author.username %}" class="mr-2">{{ post.author }}</a> <h2><a href="{% url 'post-detail' post.pk %}">{{ post.title }}</a></h2> {{ post.body|truncatewords:30 }} {% endfor %} urls.py path('user/<str:username>/', views.user_posts, name='user-posts'), but when I go to that url it shows me error Field 'id' expected a number but got 'admin'. full traceback is here: Internal Server Error: /user/natsu/ Traceback (most recent call last): File "C:\Users\Sheraram Prajapat\AppData\Local\Programs\Python\Python38\lib\site-packages\django\db\models\fields\__init__.py", line 1772, in get_prep_value return int(value) ValueError: invalid literal for int() with base 10: 'natsu' The above exception was the direct cause of the following exception: Traceback (most recent call last): … -
My django didnt work(I'm studying in tutorial)
I'm very new to django. So I'm studying using tutorial site. I think type perfectly same on site, but it's not work. so plz give me advice. mysite/urls.py [enter image description here][1] mysite/polls/urls.py [enter image description here][1] mysite/polls/templates/polls/detail.html [enter image description here][2] part of def vote in mysite/polls/views.py [enter image description here][1] error [enter image description here][1] sorry guys, i dont know how to highlight in stackoverflow... so I had to capture. anyway, I guess vote url isnt work. maybe something wrong. but i dont know exact anwser. My googling power is useless.. help me. -
JQGrid Steps To use in Python Django Project
I need help in using a JQGrid I have a list from the database using mysql. This list should use JQGrid · Make sure the list of vacations is paginated. · The JQGrid will load the data via a JSON format Framework used: Django Language: Python -
What is Next.js and does it remove the need for having a backend framework like Django for example?
So basically I am building a website that will be a generic e-commerce website to take in orders from customers and then send an email verification that their order number has been generated and has been successfully dispatched etc. Currently, I have built all of this in ReactJS with no backcend database right now. Someone has recommended that I use Next.js instead of using Django as my backend as that would be a better option but I have not understood the concept of Next.js and how it works. What is its purpose and would it remove any need for a backend framework? The database and all? Thank you for your input everyone, I would be grateful for helpful answers. -
Model with relationship to Django user model, imposing requirement that all users be assigned instance of that model
I have a model which I am trying to link to Django user accounts. My relevant parts of my models.py are: class Customer(models.Model): first_name = models.CharField(max_length=200) last_name = models.CharField(max_length=200) customer_email = models.EmailField(max_length = 254) username = models.OneToOneField(settings.AUTH_USER_MODEL, on_delete=models.CASCADE, null=True) @receiver(post_save, sender=User) def create_customer(sender, instance, created, **kwargs): if created: Customer.objects.create(user=instance) @receiver(post_save, sender=User) def save_customer(sender, instance, **kwargs): instance.customer.save() This seemed to be working fine. While I was logged in to django-admin I was able to see and assign a Djanog user to a customer object. However after logging out and attempting to login again to the django admin panel, I get the error that: RelatedObjectDoesNotExist at /admin/login/ User has no customer. This seems to imply that every user needs to have an associated customer object, which is not what I want at all. Admin users for example, should not have a customer object assigned to them. Have I made a mistake in how I have formed the relationship in my Customer model? Why would all user objects require a customer model? What is a solution that allows my customer model to be linked to a django user account without requiring all django users to have an assigned customer object? -
Django makes redirect after ajax request
I want to make a school site, where you must enter your invite code before you can registrate. I want to make validation of this code with ajax post request, but when I try to make request to validate view, it's redirecting to the page with JSON code. My AJAX: {%extends "base.html"%} {%block content%} <script> $('#code_form').on('submit', function(evt){ evt.preventDefault(); let form = evt.target $.ajax({ url: form.action, type: "POST", data: {'code': $('input[name="code"]')}, headers: {'X-CSRFToken': "{{csrf_token}}"}, success: function(data){ window.location.href = data.url; let status = JSON.parse(data)['ok'] if(status){ console.log('Good code');//This not executing }else{ console.log('Bad code');//this too } } }) }); </script> <form method = "POST" id = "code_form" action="{%url 'reg:submit'%}"> {%csrf_token%} Enter your invite code: {{form.code}}<br> <button id = "submit">Continue</button> </form> {%endblock%} Views.py: from .forms import StartF #form for code (contains only one field) from django.http import JsonResponse from django.core.exceptions import ObjectDoesNotExist #here must be one more view, but it works fine def submit(request): code = request.POST.get('code') data = {} try: user = Unregistered.objects.all().get(pk = code) except ObjectDoesNotExist: data['ok'] = False else: data['ok'] = True return JsonResponse(data, content_type = 'text/json') My urls.py: from django.urls import path from . import views from django.conf.urls import url app_name = 'reg' urlpatterns = [ url(r'^$', views.start, name='start'), #that one … -
Add operation to save method of abstract save method of parent model in Django
I create base model and inherit that in all of my models. This is my BaseModel: class BaseModel(models.Model): create_date = models.DateTimeField(auto_now_add=True) update_date = models.DateTimeField(auto_now=True) created_by = models.ForeignKey('UserManager.User', default=1, on_delete=models.SET_DEFAULT,related_name='created_%(class)ss') updated_by = models.ForeignKey('UserManager.User', default=1, on_delete=models.SET_DEFAULT,related_name='updated_%(class)ss') class Meta: abstract = True ordering = ['create_date'] def save(self, *args, **kwargs): self.user = kwargs.pop('user', None) if self.user: if self.user.pk is None: self.created_by = self.user self.updated_by = self.user super(BaseModel, self).save(*args, **kwargs) Now, I want to add some operations to save method of one of child models like this: class Child(BaseModel): # Some fields go here. def save(self, *args, **kwargs): # Some operations must run here. But save method of child model does n't run anymore! How can I use save method of child model with save method of abastract=True model? -
Django Rest Framewor Axios Session Authentication
I'm trying to use DRF session authentication for a web app (no mobile) using axios but I'm not able to get it work. Login works fine at first, logout CSRF token error 403, trying to login again but same error... I couldn't get my head around it... I have 2 class-based views for login and logout as I need to some stuff in there (unrelated to the login/logout process). Here is my setup: # settings.py REST_FRAMEWORK = { "DEFAULT_AUTHENTICATION_CLASSES": ( "rest_framework.authentication.SessionAuthentication", ), "TEST_REQUEST_DEFAULT_FORMAT": "json", } CSRF_COOKIE_HTTPONLY = True if not DEBUG: SESSION_COOKIE_SECURE = True SESSION_COOKIE_NAME = "uid" Login/Logout views: # auth_session.py from django.contrib.auth import login, logout, authenticate from rest_framework.permissions import AllowAny, IsAuthenticated from rest_framework.response import Response class LoginUserView(APIView): permission_classes = (AllowAny,) @method_decorator(ensure_csrf_cookie) def post(self, request, *args, **kwargs): email = request.data.get("email") password = request.data.get("password") user = authenticate(email=email, password=password) # ... unrelated login stuff login(request, user) # ... more unrelated login stuff attrs = { "email": user.email, "user": full_name, "last_login": last_login, } return Response(attrs, status.HTTP_200_OK) class LogoutUserView(APIView): # I tried with and without IsAuthenticated permission_classes = (IsAuthenticated,) # Same with csrf_protect @method_decorator(csrf_protect) def post(self, request, *args, **kwargs): # ... Unrelated logout stuff logout(request) return Response({"detail": "User logged out"}, status.HTTP_200_OK) finally my axios … -
Django 3.1+: (fields.E180) SQLite does not support JSONFields
I have created a Django project with the new JSONField announced in Django 3.1, which supports all databases. I have successfully used this field on a linux machine, but running python manage.py migrate with the same project on Windows fails with the following message: (fields.E180) SQLite does not support JSONFields. The same versions of Python and Django are used in both PCs. -
Django join viewin 3 models
I have 3 Models like this: class ServiceType(models.Model): service_type = models.CharField(max_length=1000) is_renewable = models.BooleanField(default=True) class Customer(models.Model): name = models.CharField(max_length=1000) service_type = models.ForeignKey(ServiceType, on_delete=models.CASCADE) class Renewals(models.Model): customer = models.ForeignKey(Customer, on_delete=models.CASCADE) renewal_date = models.DateTimeField(default=timezone.now()) payment = models.DecimalField(decimal_places=2, max_digits=5) now I want to view in template that list of Customer name which service is renewable and renewal information. How I can do this? like this: Customer(if service is renewal) | Renewal Date | Renewal Amount A | 2020-06-29 | $250 -
How to populate choices in second dropdown on the basis of selected value from first dropdown in Django using ModelChoiceFields for both dropdown
I have two dropdown: Category Sub Category Both needs to be populated dynamically Here I want to populate choices in sub_category on the basic of selected value from category field. So i don't need to save the whole form. class AddProductForm(forms.Form): category = forms.ModelChoiceField( widget=forms.Select(attrs={ 'class': 'form-control' }), queryset=Category.objects.all(), to_field_name="category") sub_category = forms.ModelChoiceField( widget=forms.Select(attrs={ 'class': 'form-control' })) -
Django database migration: delete doesn't work properly
I am using Django 2.22 and psql 10.12 in Ubuntu 18.04. At migration I am trying to remove some rows in database table auth_permission. from django.db import migrations from django.core.exceptions import ObjectDoesNotExist from django.db.models import Q def remove_rows_at_migrate(apps, schema_editor): try: permission_model = apps.get_model("auth", "Permission") db_alias = schema_editor.connection.alias permissions = permission_model.objects.using(db_alias).filter(Q(name='Can do X') | Q(name='Can do Y')) for perm in permissions: print("deleting: {}".format(perm.name)) perm.delete() except (ObjectDoesNotExist, ValueError): pass class Migration(migrations.Migration): dependencies = [ ('abc', 'xxx'), ] operations = [ migrations.RunPython(remove_rows_at_migrate) ] when I migrate, migration is applied and result is [OK] but when I check table auth_persmission "Can do X" and "Can do Y" is still in the table with a new "id". I can delete rows from same table in manage.py shell_plus without any problems with the following: >>> permissions = Permission.objects.filter(Q(name='Can do X') |Q(name='Can do Y')) >>> permissions.delete() What could cause this behavior? -
No module named 'settings' when run django command with manage.py
I'm tring to run a command with Django command. My project stucture is like below: # working dir ├── work │ └──conf │ ├── settings.py │ └── wsgi.ini │ └──logs # project dir ├── code │ ├── project │ │ ├── api │ │ ├── admin.py │ │ ├── apps.py │ │ ├── filters.py │ │ ├── __init__.py │ │ ├── management │ │ │ └── commands │ │ │ ├── schedule_task_a.py │ │ │ ├── schedule_task_b.py │ │ ├── models.py ├── project │ ├── __init__.py │ ├── settings.py │ ├── urls.py │ └── wsgi.py ├── manage.py And when I run python /code/project/manage.py schedule_task_a --pythonpath /work/conf --settings settings I got error like : ModuleNotFoundError: No module named 'settings' How can I run the task as expected? -
How to store multiple files under the same model attribute in Django?
I want to store multiple files in the same Django model attribute. The attribute I currently have: class Request_tab(models.Model): attachments= models.FileField(blank=True,upload_to=get_upload_path) def get_upload_path(instance,filename): return "{procurement_id}/{file}".format(procurement_id=instance.procurement_id,file=filename) I am using Postman to test my APIs and using serializers for JSON data conversion and MySQL as database. Is there a way to do this without the serializers generating a problem? -
upload multiple images without forms in django
This is my models.py class Upload(models.Model): images = models.ImageField(upload_to='image/') serializers.py class UploadSerializer(serializers.ModelSerializer): class Meta: model = Upload fields = '__all__' views.py class UploadViewSet(viewsets.ModelViewSet): queryset = Upload.objects.all() permission_classes = [ permissions.AllowAny ] serializer_class = UploadSerializer I can successfully upload single image, however django model is not recieving multiple images at once. How to upload multiple images? what should i change in serializers.py or models.py or views.py? any related response is appreciable. Thank you. -
Django 'Model matching query does not exist.' error
I have a three simple models. User, Restaurant, Menu. A single user can have many restaurants, and each restaurant can have many Menus. I am using the generic Django CreateView for the Posting of the Restaurants and Menus to their respective models. This works for The restaurants, But fails for the Menus and I get a "Restaurant matching query does not exist" ERROR. I feel that it is a URL issue because I can reach the template if I input it manually, but fails when i use the button. VIEWS.py @login_required def profile(request, pk): user = CustomUser.objects.get(pk=pk) if not user.id == request.user.pk: raise PermissionDenied() else: context = { 'user': user, 'rests': Restaurant.objects.filter(account=request.user).order_by('-date'), 'countRests': Restaurant.objects.filter(account=request.user).count(), } return render(request, 'restaurants/profile.html',context) class RestCreateView(LoginRequiredMixin, CreateView): template_name = 'restaurants/makeRestaurant.html' form_class = RestCreateForm def form_valid(self, form): form.instance.account = self.request.user return super().form_valid(form) def RestMenus(request, pk, name): rest = Restaurant.objects.get(name=name) user = CustomUser.objects.get(pk=pk) if not user.id == request.user.pk: raise PermissionDenied() else: context = { 'rest': rest, 'user': user, 'menus': Menu.objects.filter(restaurant=rest).order_by('-uploadDate'), 'countMenus': Menu.objects.filter(restaurant=rest).count(), } return render(request, 'restaurants/menus.html',context) class MenuCreateView(LoginRequiredMixin, CreateView): template_name = 'restaurants/makeMenu.html' form_class = MenuCreateForm def form_valid(self, form): form.instance.restaurant = self.request.restaurant return super().form_valid(form) URLS.py urlpatterns = [ path('', home, name='home'), path('profile/<int:pk>/',profile, name='profile'), path('profile/<int:pk>/createRest/', RestCreateView.as_view(), name='createRest'), path('profile/<int:pk>/restaurant/<str:name>',RestMenus, name='RestDetail'), path('profile/<int:pk>/restaurant/<str:name>/createMenu/', … -
500 Internal Server Error Exception inside application
I make this instruction: https://stackoverflow.com/a/52314952/12303095, but i get the same error: if DEBUG=True website works fine, but when i change DEBUG to False, i get this internal server error on some links, when i add data in database in users i get the error if no data no error. error in console looks like this: 2020-06-29T11:07:00.579637+00:00 app[web.1]: 2020-06-29 15:07:00,579 INFO "10.30.127.176" - - [02/Jan/1970:20:25:54 +0000] "GET /specialists HTTP/1.1" 500 453 "https://itwork-heroku.herokuapp.com/vacancies" "Mozilla/5.0 (Windows NT 10.0; Win64; x64) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/83.0.4103.116 Safari/537.36" -
Allow specific users to see specific files - Django
I'm building a system to manage documents using Django, so I want to allow specific users (based on their ID o email) to read specific documents (uploaded by the same user or shared with another one specified by the file creator). How can I build this feature? -
Django project database
i have created a project using Django . how can i view stored data in database of my project ? i have tried below command in cmd >***python manage.py dbshell*** ***sqlite>** *.tables* auth_group django_admin_log auth_group_permissions django_content_type auth_permission django_migrations auth_user django_session auth_user_groups poll_poll auth_user_user_permissions **sqlite>** *.header on* **sqlite>** *.mode column* **sqlite>** *pragma table_info('auth_user');* cid name type notnull dflt_value pk ---------- ---------- ---------- ---------- ---------- ---------- 0 id integer 1 1 1 password varchar(12 1 0 2 last_login datetime 0 0 3 is_superus bool 1 0 4 username varchar(15 1 0 5 first_name varchar(30 1 0 6 email varchar(25 1 0 7 is_staff bool 1 0 8 is_active bool 1 0 9 date_joine datetime 1 0 10 last_name varchar(15 1 0 it is giving above info but i am not able to view actual data stored by users in database how to view that ? -
How to Make For Loop Django template. i was makeing a pagination in django
{% for i in paginated_queryset.num_pages %} {{ i }} {% endfor%} paginated_quertser.num_pages = 9 I want to output like this 1 2 3 4 5 6 7 8 9 I also read django pagination document but in the document not given example like this and I am beginner in django -
Access to XMLHttpRequest blocked by CORS policy at same domain
I'm using Django/Python with a third party software that has its own js which accesses the service. Access to XMLHttpRequest at 'wss://editordev.science.net/cache/files/filename=Editor.bin' from origin 'https://editordev.science.net' has been blocked by CORS policy: Cross origin requests are only supported for protocol schemes: http, data, chrome, chrome-extension, https. Is the same domain, I don't understand the error.