Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
when I want to see my admin penal in django it give me error not only admin in some ursl it give me in some not this happen when I put to live db
this is my admin.py admin.site.register(models.User) admin.site.register(models.Teacher) admin.site.register(models.Student) admin.site.register(models.CourseCategory) admin.site.register(models.Course) admin.site.register(models.Chapter) admin.site.register(models.Section) admin.site.register(models.StudentCourseEnrollment) admin.site.register(models.CourseRating) this is my settings.py DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'LMSAPI', 'USER':'admin', 'PASSWORD':'12341234', 'HOST':'mydb.cvijitliru7b.ap-northeast-1.rds.amazonaws.com', 'PORT':'3306', 'CHARSET': 'utf8', } and this is the error enter image description here -
Git ignores all files
My gitignore file looks straighforward: env/ .idea *.pyc __pycache__ *.env /environment db.sqlite3 *.log When I do git add . from my root project folder and then check status - I see there is no files tracked. When I do git status --ignored, I see that all folders are ignored: .flake8 .gitignore .idea/ Procfile env/ requirements.txt runtime.txt src/ So it somehow ignores all the folders and files. I tried to comment everything in gitignore - and the result is the same. I tried to reinitialize the git by: rm -rf .git git init And the result is the same. How can I add my files, without git add --force? I want files that are added in gitignore to be ignored, but still to commit other files. -
django-friendship API
I Think there's nothing much to explain over here of what I am trying to achieve using Django-Friendship API. but it doesnt work and always shows the Unfollow btn. {% if user.id not in request.user.following %} <a class='btn btn-success' href="{% url 'addFollowing' user.id %}">Follow @{{user.username}} </a> {% else %} <a class='btn btn-danger' href="{% url 'removeFollowing' user.id %}">Unfollow</a> {% endif %} -
Django ORM Group By with Foreign Keys
user is a foreign key on tournament. select u.id, u.display_name, count(t.id) from tournament t join "user" u on t.user_id = u.id where date(t.start_date)> '2022-07-01' group by u.display_name, u.id How can I make the above SQL query work with django's ORM? -
Can't Get Image from Django Api To React Native
Hello Friends I Can't Get Image From Django To React Native Here My Code Fetch APi const [add, setStudents] = useState([{}]) async function getAllStudent() { try { const add = await axios.get('http://192.168.1.77:19000/api/add/') method:'GET', setStudents(add.data) } catch (error) { console.log(error) } } getAllStudent(); FlatList : <FlatList data={add} renderItem={({item})=> <Image style={{width:200,height:200, backgroundColor:'green',}} source={{uri:item.image}} /> } /> Django Code Is Here Views class addpost(viewsets.ViewSet): def list(self,request): postadd1 = postadd.objects.all() postaddserial1 = postaddserial(postadd1,many=True) return Response(postaddserial1.data) def create(self,request): postaddserial1 = postaddserial(data=request.data) if postaddserial1.is_valid(): postaddserial1.save() return Response(postaddserial1.data, status=status.HTTP_201_CREATED) return Response(postaddserial1.errors, status=status.HTTP_400_BAD_REQUEST ) def retrieve(self,request,pk=None): queryset = postadd.objects.all() contact = get_object_or_404(queryset,pk=pk) postaddserial1 = postaddserial(contact) return Response(postaddserial1.data) def update(self,request,pk=None): contact = postadd.objects.get(pk=pk) postaddserial1 = postaddserial(contact,data=request.data) if postaddserial1.is_valid(): postaddserial1.save() return Response(postaddserial1.data,status=status.HTTP_201_CREATED) return Response(postaddserial1.errors,status=status.HTTP_400_BAD_REQUEST) def destroy(self, request, pk=None): postadd1 = postadd.objects.get(pk=pk) postadd1.delete() return Response(status=status.HTTP_204_NO_CONTENT) Serializer class postaddserial(serializers.ModelSerializer): class Meta: model = postadd fields ='__all__' Model class postadd(models.Model): city=models.CharField(max_length=122) carinfo=models.CharField(max_length=122) milage=models.CharField(max_length=122) price=models.CharField(max_length=122) company=models.CharField(max_length=122) image = models.ImageField(upload_to ='static/Images', height_field=None, width_field=None, max_length=100,) engine=models.CharField(max_length=122) contact=models.CharField(max_length=122) I make django Api to add product in react native. i show image from post man . but cant get image in react native from api i am making application where i can add product from django rest framework and show it on react native through api i get … -
Not able to install mysqlclient in Django project
Not able to install mysqlclient in Django project. While running pip giving error as "Microsoft Visual C++ 14.0 Is Required Error". Tried downloading Microsoft C++ Build Tools -
How to create a visible route/path on leaflet map?
I have an app which allows a user to see a route between his location and the place they want to get to, and im having difficulties showing the route however the 2 markers show up. //Passing lat and lon value from a django template variable const latitude = document.getElementById('lat').textContent; const longtitude = document.getElementById('lon').textContent; // Creating map options let mapOptions = { center: [latitude, longtitude], zoom: 18, zoomControl: true, zoomAnimation: true, } // Creating a map object guessing if there's an error it could be down here... var map = new L.map('map', mapOptions); var layer = new L.TileLayer('http://{s}.tile.openstreetmap.org/{z}/{x}/{y}.png', { attribution: '© OpenStreetMap contributors' }); map.addLayer(layer); L.marker([latitude,longtitude]).addTo(map); const btn = document.getElementById('create_route'); btn.addEventListener("click",function create_route(e){ function success(pos) { const crd = pos.coords; let crdLat = crd.latitude, crdLon = crd.longitude; L.Routing.control({ waypoints: [ L.latLng(latitude,longtitude), L.latLng(crdLat,crdLon) ], autoRoute: true, routeWhileDragging: true }).addTo(map); } //get user location navigator.geolocation.getCurrentPosition(success); }) Also i get this error in my console leaflet-routing-machine.js:15868 Routing error: {message: 'HTTP request failed: undefined', url: 'https://router.project-osrm.org/route/v1/driving/-…erview=false&alternatives=true&steps=true&hints=;', status: -1, target: XMLHttpRequest} Any help will be much appreciated, I'am open to other alternatives also...As long as it gets the job done. -
Django puts slug between parentheses, then stops doing that
I have an issue similar to this one. My error message is something like this: Reverse for 'detail' with arguments '('some-slug',)' not found. 1 pattern(s) tried: ['users/(?P<username>[^/]+)/$'] I intend to use some-slug and not ('some-slug',) for URL reversal. When I follow Saifeddin's suggestion of using <str:slug>, it works. I then switch back to <slug:slug>, it also works. The problem simply vanishes. Could someone explain to me why Django (4.1.2) behave this way? I am at a loss. -
why is starting a celery worker showing what appears to be random print statements
When I start a celery worker I get the following. The >>> bla bla <<< print statements are in various scripts having nothing to do with celery or beat. After that the worker does not show any activity when I save a task in beat admin pages. > celery -A mysite worker -l info --pool=solo -n worker3 XXXXXXXXXXXXXXXXX correlator views IndexView XXXXXXXXXXXXXXXXXXXXXXX >>>>>>>>>>>>>>>>>>> Reviews.views.IndexView <<<<<<<<<<<<<<<<<<<<<<<<<<<< >>>>>>>>>>>>>>>>>>> Reviews.views.DetailView <<<<<<<<<<<<<<<<<<<<<<<<<<<< >> correlator/urls.py << XXXXXXXXXXXXXXXXX parameters/views.py ParametersIndexView XXXXXXXXXXXXXXXXXXXXXXX QuestionsViewSet correlator/urls.py -------------- celery@worker3 v5.1.2 (sun-harmonics) --- ***** ----- -- ******* ---- Windows-10-10.0.19041-SP0 2022-11-01 12:33:52 - *** --- * --- - ** ---------- [config] - ** ---------- .> app: mysite:0x18cc6d60208 - ** ---------- .> transport: amqp://guest:**@localhost:5672// - ** ---------- .> results: - *** --- * --- .> concurrency: 12 (solo) -- ******* ---- .> task events: OFF (enable -E to monitor tasks in this worker) --- ***** ----- -------------- [queues] .> celery exchange=celery(direct) key=celery [tasks] . correlator.tasks.add . correlator.tasks.mul . iris.tasks.add . iris.tasks.mul . mysite.celery.debug_task . mysite.celery.hello_world . reviews.tasks.add . reviews.tasks.mul . reviews.tasks.rename_widget [2022-11-01 12:33:52,901: INFO/MainProcess] Connected to amqp://guest:**@127.0.0.1:5672// [2022-11-01 12:33:52,906: INFO/MainProcess] mingle: searching for neighbors [2022-11-01 12:33:53,946: INFO/MainProcess] mingle: all alone ings.DEBUG leads to a memorARNING/MainProcy thub\correlator leak, never useelery\fixups\dj this setting in productionsing … -
Django ArrayField of Floats: Can't seem to input floats in a list into Django Admin
These are basically cartesian coordinates that I am storing, of y values only. I am unsure how to store them other than an "list of floats", but unable to make it to an arrayfield of floats in django as shown above. I am not sure how to fix this. I understand I could store it all as a string, but if I am doing a lot of operations, and my arrays can go up to lengths of hundreds of thousands, getting that as a string and converting to float arrays could become very expensive. (or would it not be?) -
Celery unexpectedly closes TCP connection
I'm using RabbitMQ 3.8.2 with Erlang 22.2.7 and having a problem while consuming tasks. My configuration is django-celery-rabbitmq. While publishing messages in a queue everything goes ok until the length of the queue reaches 1200 messages. After this point RabbitMQ starts to close AMQP connection with following errors: ... 2022-11-01 09:35:25.327 [info] <0.20608.9> accepting AMQP connection <0.20608.9> (185.121.83.107:60447 -> 185.121.83.116:5672) 2022-11-01 09:35:25.483 [info] <0.20608.9> connection <0.20608.9> (185.121.83.107:60447 -> 185.121.83.116:5672): user 'rabbit_admin' authenticated and granted access to vhost '/' ... 2022-11-01 09:36:59.129 [warning] <0.19994.9> closing AMQP connection <0.19994.9> (185.121.83.108:36149 -> 185.121.83.116:5672, vhost: '/', user: 'rabbit_admin'): client unexpectedly closed TCP connection ... [error] <0.11162.9> closing AMQP connection <0.11162.9> (185.121.83.108:57631 -> 185.121.83.116:5672): {writer,send_failed,{error,enotconn}} ... 2022-11-01 09:35:48.256 [error] <0.20201.9> closing AMQP connection <0.20201.9> (185.121.83.108:50058 -> 185.121.83.116:5672): {inet_error,enotconn} ... Then the django-celery consumer disappears from queue list, messages become "ready" and celery pods are unable to ack the message after the job is finished with the following error: ERROR: [2022-11-01 09:20:23] /usr/src/app/project/celery.py:114 handle_message Error while handling Rabbit task: [Errno 104] Connection reset by peer Traceback (most recent call last): File "/usr/local/lib/python3.10/site-packages/amqp/connection.py", line 514, in channel return self.channels[channel_id] KeyError: None During handling of the above exception, another exception occurred: Traceback (most recent call last): File "/usr/src/app/project/celery.py", … -
django.urls.exceptions.NoReverseMatch: 'user' is not a registered namespace
I am trying to create a Log in and Registration for a Django Rest Framework but I keep getting django.urls.exceptions.NoReverseMatch: 'user' is not a registered namespace not sure what is the reason for getting this error and how to fix it? Here is the serializers.py: class UserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ["id", "first_name", "last_name", "username"] class RegisterSerializer(serializers.ModelSerializer): email = serializers.EmailField( required=True, validators=[UniqueValidator(queryset=User.objects.all())] ) password = serializers.CharField( write_only=True, required=True, validators=[validate_password]) password2 = serializers.CharField(write_only=True, required=True) class Meta: model = User fields = ('username', 'password', 'password2', 'email', 'first_name', 'last_name') extra_kwargs = { 'first_name': {'required': True}, 'last_name': {'required': True} } def validate(self, attrs): if attrs['password'] != attrs['password2']: raise serializers.ValidationError( {"password": "Password fields didn't match."}) return attrs def create(self, validated_data): user = User.objects.create( username=validated_data['username'], email=validated_data['email'], first_name=validated_data['first_name'], last_name=validated_data['last_name'] ) user.set_password(validated_data['password']) user.save() return user Here is the views.py: class UserDetailAPI(APIView): authentication_classes = (TokenAuthentication,) permission_classes = (AllowAny,) def get(self,request,*args,**kwargs): user = User.objects.get(id=request.user.id) serializer = UserSerializer(user) return Response(serializer.data) class RegisterUserAPIView(generics.CreateAPIView): permission_classes = (AllowAny,) serializer_class = RegisterSerializer Here is the urls.py path('get-details/', UserDetailAPI.as_view()), path('register', RegisterUserAPIView.as_view()), Here is the traceback: Traceback (most recent call last): File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\exception.py", line 55, in inne r response = get_response(request) File "C:\Users\User\Desktop\Project\venv\lib\site-packages\django\core\handlers\base.py", line 197, in _get_res ponse response = wrapped_callback(request, *callback_args, **callback_kwargs) File … -
Django - Why Sweetify is not working. SweetAlert2
I'm followed the documentation from Atrox, and then still not working on my project. Any Idea ? I write the code like below. 1. home/views.py from django.shortcuts import redirect from django.views.generic import FormView from attendance.models import Graduates from home.forms import TicketForm from django.utils import timezone from django.urls import reverse import sweetify class HomeView(FormView): template_name = 'home/index.html' form_class = TicketForm def form_valid(self, form): getId = form.cleaned_data['nomor_ticket'] try: graduate = Graduates.objects.get(ticket_id=getId) message_success = 'Congratulations' if graduate: graduate.attendance = timezone.now() graduate.status = True graduate.save() sweetify.success(self.request, message_success, text='Cool', persistent='Thanks', timer='3000') return (redirect('attendance:index', graduate.ticket_id)) except Graduates.DoesNotExist: print('ticket not found') return redirect('home:index') 2. templates/base.html ... <body> {% block contents %}{% endblock contents %} <script src="https://unpkg.com/flowbite@1.5.3/dist/flowbite.js"></script> {% load sweetify %} {% sweetify %} </body> ... 3. core/settings.py INSTALLED_APPS = [ ... 'sweetify' ... ] SWEETIFY_SWEETALERT_LIBRARY = 'sweetalert2' -
How to effectively iterate by many foreignkey objects with Django ORM?
Let's say that I have model like: class User(AbstractUser): ... seller = models.ForeignKey(Seller, related_name="user", on_delete=models.SET_NULL, null=True) ... And I trying to get seller email address using this code: from app.models import User from django_print_sql import print_sql with print_sql(count_only=False): users = User.objects.filter(is_active=True, seller_id__isnull=False).select_related().only('seller__email') for u in users.iterator(): email = u.seller.email send_email(email) In this case I can see SQL queries like: SELECT `user`.`id`, `user`.`seller_id` FROM `user` WHERE (`user`.`is_active` AND `user`.`seller_id` IS NOT NULL) ... SELECT `seller`.`id`, ... `seller`.`email`, ... FROM `seller` WHERE `seller`.`id` = 1 ... The problem is Django ORM accessing DB at every iteration (Select seller... where seller.id = ...). So that will be too many queries (== DB connections) if we have many sellers. In other way it is possible to replace only with values: from app.models import User from django_print_sql import print_sql with print_sql(count_only=False): users = User.objects.filter(is_active=True, seller_id__isnull=False).select_related().values('seller__email') for u in users.iterator(): email = u['seller__email'] send_email(email) And I can see SQL query like: SELECT `seller`.`email` FROM `user` INNER JOIN `seller` ON (`user`.`seller_id` = `seller`.`id`) WHERE (`user`.`is_active` AND `user`.`seller_id` IS NOT NULL) It is little bit better and we able to get emails by single DB query, but iterator is useless here because we load all emails once inside … -
AttributeError: module 'django.core.serializers' has no attribute 'ModelSerializer'
I had this error: "AttributeError: module 'django.core.serializers' has no attribute 'ModelSerializer'" before running makemigrations Though I have imported serializers from rest_framework, and I have added rest_framework to my installed app, it still did not work -
How to edit my get_queryset method Django Rest to acept authenticated users and authenticated user
I have this CourseViewSet which is using mixins to create,list, retrieve and update courses. Right now only authenticated users can list and retrieve courses and adminUsers can create, update courses. The get_queryset method has been overwritten to list the courses that users have bought and all the courses. It looks like this: courses/views.py def get_queryset(self): qs = Course.objects.filter(is_active=True, level=0) active_levels_prefetch = Prefetch( "levels", queryset=Level.objects.filter(is_active=True).order_by("is_special"), ) qs = qs.prefetch_related("children", active_levels_prefetch) # Add purchased courses amount qs = CourseQuerySet._add_purchase_amount_to_qs(qs) if self.request.user.is_student(): self._set_geolocation_params() qs = CourseQuerySet.list(qs, self.country) print(qs) return qs In my util, I have this file permissions.py, to verify if users are students: class IsStudent(BasePermission): """Verify is user is student.""" def has_permission(self, request, view): # Anonymous user aren't allowed if isinstance(request.user, AnonymousUser): return False return request.user.is_student() I also edited the get_permissions method to accept unauthenticated users to get a list of the courses: def get_permissions(self): """ Instantiates and returns the list of permissions that this view requires. """ if self.request.method == 'GET': permission_classes = [AllowAny] else: permission_classes = [IsAdmin] return [permission() for permission in permission_classes] When I tried to get all the courses without authentication, I get the next error: AttributeError: 'AnonymousUser' object has no attribute 'is_student', which is obvious because in … -
Django Rest Framework returns {'detail': 'Not found.'} when tested although it is showing Data in URL
I have the following django project with the following views.py: @api_view(['GET']) @permission_classes([AllowAny]) def getItem(request, **kwargs): user = get_object_or_404(User, username=request.user) items=Item.objects.filter(user=user) serializer = ItemSerializer(items, many=True) return Response(serializer.data) Here is the serializer.py class ItemSerializer(serializers.ModelSerializer): user = serializers.CharField(source="user.username", read_only=True) class Meta: model= Workout fields = '__all__' Here is the outcome in the Django Rest Framework URL: Get Workout GET /api/Shiko/items/ HTTP 200 OK Allow: GET, OPTIONS Content-Type: application/json Vary: Accept [ { "id": 1, "user": "Shiko", "active": false, "name": "Item 1", "slug": null } ] Test using Jupyter to check for data availablity: import requests data = requests.get(URL) json_data = data.json() print (json_data) My question: What could be wrong in my settings that needs changed to return valid data in my test code knowing that there is data in Json but returning not found when testing. Also I have used IsAuthenticated which returned {'detail': 'Authentication credentials were not provided.'} which means that the test code is valid. What am I doing wrong and how should I fix? -
How to filter in HTML using a field from model?
I want to implement a page with check boxes from university's subjects and the user can select which ones are already completed, I code a for loop that displays in the page all subjects from that course, but I want to separate the subjects by semester in a div, but in the same page, can I do this with a custom template tag or filter? I have tried using .filter on the query, but in this case only returned one specified semester. -
Django to AWS deterministic=True requires SQLite 3.8.3 or higher
I have deployed my AWS application, but am receiving the error when I navigate to it's EC instance URL: deterministic=True requires SQLite 3.8.3 or higher I have tried the solution here, but when I run eb deploy and eb ssh and vi /var/app/venv/staging-LQM1lest/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py , but the file still says from sqlite3 import dbapi2 as Database rather than from pysqlite3 import dbapi2 as Database However, in /var/app/current/venv/lib/python3.8/site-packages/django/db/backends/sqlite3/base.py it correctly says from pysqlite3 import dbapi2 as Database Any ideas how I can solve this issue? -
reversing admin "change" url
I´m trying to find some example of how to use change url of modelAdmin and what exactly result it gives. Sincerly I do not understand the part from docs: "This will find the first registered instance of the admin application (whatever the instance name), and resolve to the view for changing poll.Choice instances in that instance." -
When to use web socket or http
In a social media app development, when should I use web sockets? I know I have to use them to get the real time things, like messaging, and notification. But should I use web sockets in features like "Like", "Retweet", etc? Currently, I have one websocket for each of those resources, it's working great but I'm not sure it is the best approach. Inside those web socket connections, I have a function that notifies users in real time. But then I thought, "Man i dont think I need web socket for like function, I could just use Http and use web socket only for the notification"? So I have this doubt -
heroku Response times
I am deploying my django web app to heroku I am not using free tier, but my application is soo slow how can I make it faster, this is the error I am having now : Active Alerts: Response times have been above your 1000ms threshold for an hour. probably because I am using images and database from aws. I tried upgrading web dyno type to standard -
How to make simple filtration with django-filter
I faced with a problem. I have a simple drf project with car-entrance permits application. views.py ` class PermitViewSet(ModelViewSet): queryset = Permit.objects.filter() serializer_class = PermitSerializer filter_backends = [DjangoFilterBackend] filter_fields = ['car_number'] serializers.py ` class PermitSerializer(serializers.ModelSerializer): class Meta: model = Permit fields = ['car_number', 'is_active'] models.py ` class Permit(models.Model): car_number = models.CharField(max_length=15) customer = models.ForeignKey(User, on_delete=models.CASCADE) created = models.DateTimeField(auto_now_add=True) is_active = models.BooleanField(default=True) urls.py router = SimpleRouter() router.register(r'permit', PermitViewSet) urlpatterns = [ path('admin/', admin.site.urls), ] urlpatterns += router.urls ` i type in my browser http://127.0.0.1:8000/api/v1/permits/?car_number=555 and i recieve full list of cars ` [{"car_number":"555","is_active":true},{"car_number":"666","is_active":true},{"car_number":"777","is_active":true}] ` It doesn't work, what's the problem? -
Supervisor shutsdown when I have multiple services in the .conf file
I have a Linux server running ubuntu 22.10 with digital ocean where I plan to host multiple virtualenv to run isolated Django applications. Using gunicorn to serve the application and nginx as the reverse proxy. The supervisor to control the processes. I started with one django application and everything was working fine. on adding the second .conf file for the second application, the supervisor shuts down and subsequent supervisorctl commands return this error unix:///var/run/supervisor.sock refused connection this is my supervisor configuration [program:brotherstech] command=/home/webapps/brotherstech/bin/gunicorn_start user=ops autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/webapps/brotherstech/logs/gunicorn-error.log [program:officebook] command=/home/webapps/officebook/bin/gunicorn_start user=ops autostart=true autorestart=true redirect_stderr=true stdout_logfile=/home/webapps/officebook/logs/gunicorn-error.log -
Django Graphene hiding a model field (or return null) based on user preference in ManyToMany
assume we have the following Django Models: class Person(models.Model): name = models.CharField(max_length=255) personal_field = models.CharField(max_length=255) class Group(models.Model): name = models.CharField(max_length=255) participants = models.ManyToManyField( "Person", through="GroupPersonOption", through_fields=('group', 'person') ) class GroupPersonOption(models.Model): person = models.ForeignKey("Person", on_delete=models.CASCADE) event = models.ForeignKey("Event", on_delete=models.CASCADE) hide_personal_field = models.BooleanField(default=False) Example: Based on the group a user is in, they can choose to hide their personal_field, so that instead of its regular value, None or Null is returned. The Person can set this in the ManyToMany Model called GroupPersonOption Where it gets tricky: How do I change its value to None in my DjangoObjectTypes? When I try to add a resolve function for the personal_field in PersonObjectType, I don't know if the user wanted to hide this info. Graphene Code: { peopleByGroup(name: "DjangoIsAwesome") { person { name personal_field } } } I have waited a few days in the Django Subreddit but the only solution one person came up with was just to ignore setting the personal_field to None based on some value and then hide it in the frontend, however that is not an acceptable solution, as this would expose user data. I have also tried adding a resolve_person function to the PersonEventOptionType, but that broke a lot …