Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Is it possible to deploy Django Mayan-eds to Heroku?
I am not an experienced developer but I recently was able to deploy some small Django projects to Heroku free hosting service. Now, I am investigating mayan-edms for a project I have, that seems to provide many features I would need, but it seems a bit complicated to install in local computer and probably even more to deploy to the web. Given that I am more familiar with the heroku deployment process for django apps (than with the use of docker style deployments) my question is: Is it possible to deploy a django Mayan-edms system to Heroku? If so, is there a tutorial, how-to guide about this? -
Django: can't change language
I think the solution should be quite simple. But I can't understand it. If nothing works, I'll do it through context processors. settings.py: LANGUAGE_CODE = 'en' LANGUAGES = [ ('en', 'English'), ('ru', 'Русский'), ('uk', 'Українська') ] TIME_ZONE = 'UTC' USE_I18N = True MIDDLEWARE = [ 'django.middleware.security.SecurityMiddleware', 'django.contrib.sessions.middleware.SessionMiddleware', 'django.middleware.locale.LocaleMiddleware', 'django.middleware.common.CommonMiddleware', 'django.middleware.csrf.CsrfViewMiddleware', 'django.contrib.auth.middleware.AuthenticationMiddleware', 'django.contrib.messages.middleware.MessageMiddleware', 'django.middleware.clickjacking.XFrameOptionsMiddleware', ] urls.py: urlpatterns = [ path('', index, name='index'), path('set_lang/<lang>', set_lang, name='set_lang') ] and my views.py: def index(request): print('language after changing ', translation.get_language()) print(request.session.get(LANGUAGE_SESSION_KEY)) return render(request, 'project/index.html', locals()) def set_lang(request, lang): print('language before ', translation.get_language()) translation.activate(lang) print('language after activating', translation.get_language()) request.session[translation.LANGUAGE_SESSION_KEY] = lang return HttpResponseRedirect(request.META.get('HTTP_REFERER', 'index')) Every time I refer to this link(http://127.0.0.1:8000/set_lang/en)... The language never changes and always remains uk Console trace(prints) -
Using Websocket in Django View Not Working
Problem Summary I am sending data to a front-end (React component) using Django and web-sockets. When I run the app and send the data from my console everything works. When I use a button on the front-end to trigger a Django view that runs the same function, it does not work and generates a confusing error message. I want to be able to click a front-end button which begins sending the data to the websocket. I am new to Django, websockets and React and so respectfully ask you to be patient. Overview Django back-end and React front-end connected using Django Channels (web-sockets). User clicks button on front-end, which does fetch() on Django REST API end-point. [NOT WORKING] The above endpoint's view begins sending data through the web-socket. Front-end is updated with this value. Short Error Description The error Traceback is long, so it is included at the end of this post. It begins with: Internal Server Error: /api/run-create And ends with: ConnectionResetError: [WinError 10054] An existing connection was forcibly closed by the remote host What I've Tried Sending Data Outside The Django View The function below sends data to the web-socket. Works perfectly when I run it in my console … -
Error accediendo a Sendinblue (Hosting: Pythonanywhere)
¡Hola! He desplegado recientemente en Pythonanywhere un sitio web desarrollado en Django. La web esta integrada con Sendinblue, revise la Whitelisted y vi que está permitida la API para las cuentas free en Pythonanywhere. Les solicito ayuda porque todas las consultas a la API me dan errores como el que le muestro al final, en cambio fuera del hosting funciona todo bien. Les agradecería si pudieran indicarme que debo hacer para poder acceder a la API de Sendinblue. Muchas Gracias a todos. Saludos Error de las consultas: 2021-03-17 11:55:19,469: Retrying (Retry(total=0, connect=None, read=None, redirect=None, status=None)) after connection broken by 'NewConnectionError('<urllib3.connection.HTTPSConnection object at 0x7fb4274735d0>: Failed to establish a new connection: [Errno 101] Network is unreachable')': /v3/contacts?limit=5&offset=0 -
Creating a task (child) with restricted pool of projects (parent)
I'm trying to create a TODO app where you can create tasks and projects. Projects are used for collecting tasks. Tasks can be standalone tasks or a part of a project. I want user to be restricted when he creates a task so he can assign it only to projects which he created or he's a part of (participant1 field). For some reason my current code isn't really using custom perform_create I created. It even doesn't seems to execute code in else of perform_create models.py class Project(models.Model): title = models.CharField(max_length=100) project_owner = models.ForeignKey(User, on_delete=models.CASCADE ) created = models.DateTimeField(auto_now_add=True) completed = models.DateTimeField(blank=True, null=True) participant1 = models.ForeignKey(User, on_delete=models.CASCADE, related_name="participant", null=True, blank=True) deleted = models.BooleanField(default=False) class Task(models.Model): title = models.CharField(max_length=200) created = models.DateTimeField(auto_now_add=True) scheduled = models.DateTimeField(blank=True, null=True) completed = models.DateTimeField(blank=True, null=True) importance = models.BooleanField(default=False) task_owner = models.ForeignKey(User, on_delete=models.CASCADE) project_id = models.ForeignKey(Project, on_delete=models.CASCADE, related_name="tasks" , null=True, blank=True) deleted = models.BooleanField(default=False) serializers.py class TaskSerializer(serializers.ModelSerializer): project_id = serializers.PrimaryKeyRelatedField(queryset=Project.objects.all(), required=False) task_owner = serializers.ReadOnlyField(source='task_owner.username') class Meta: model = Task fields = '__all__' views.py class TaskList(generics.ListCreateAPIView): serializer_class = TaskSerializer permission_classes = [permissions.IsAuthenticated] def get_queryset(self): user = self.request.user project = Project.objects.filter(participant1=user).values_list('id', flat=True) return Task.objects.filter(Q(deleted=False) & (Q(completed = None) & Q(task_owner=user)) | Q(deleted=False) & (Q(project_id__in=project) & Q(completed = None))).order_by('-id') def perform_create(self, … -
drf: Search filter in function based views
Is it possible to make search filter in function based views in drf? i'v run the command pip install django-filter and added django_filters in INSTALLED_APP. I tried in class based views and it works fine. Here is my code: #@api_view(['GET']) #@permission_classes((IsAuthenticated,)) class SearchUser(ListAPIView): queryset = User.objects.all() serializer_class = SimpleUserSerializer filterset_fields = ['username'] settings.py: REST_FRAMEWORK = { 'DEFAULT_FILTER_BACKENDS':['django_filters.rest_framework.DjangoFilterBackend'], } but i want to do it in function based views. views.py: #from ?? import ?? @api_view(['GET']) @permission_classes((IsAuthenticated,)) def searchUser(request): queryset = User.objects.all() serializer = SimpleUserSerializer(queryset, many=True) # what next??? serializers.py: class SimpleUserSerializer(serializers.ModelSerializer): class Meta: model = User fields = ('id','first_name', 'last_name') And i'v another problem. If an object has an username called abcdef and then i search for cdef it should return that object(which username is abcdef). Is it possible in function/class based views? if so, how to do that? -
Integration testing DRF
I'm using Django with DRF as just an API--it doesn't serve any FE assets of any kind. I know the Django testing suite is built on the Python native unittest library and plan on using it for unit testing. When it comes to integration testing, is it sufficient or should something like Behave be used? If unittest is sufficient, should it be used in conjunction with some kind of faker? -
Efficient Multiple Row and Columns Lookup Django
I need an efficient query that can enable lookup on multiple table rows and different columns. I have the below model: class Vahala(models.Model): tourist = models.ForeignKey(User) name = models.CharField(max_length=100) can_visit = models.BooleanField(default=False) can_move_out = models.BooleanField(default=False) I need to confirm if Mr A who is a tourist can visit a location named 'bali' and can also move out of a location named 'cape_verde'. I want to believe the naive approach would be check_a = Vahala.objects.filter(name='bali', can_visit=True, tourist__email='mra@mail.com') check_b = Vahala.objects.filter(name='cape_verde', can_move_out=True, tourist__email='mra@mail.com') check_a and check_b must exists() before Mr A can complete the process. I need an efficient approach. I don't want to keep hitting the database multiple times. Is it possible to confirm the conditions via a single DB hit or at most two if the conditions are much? What am I missing? -
How to custom values for a many to many field in a create view in django
I want to just show published tags in a many to many field ( relation with tag model ) in a CreateView in django. my code for create view --> enter image description here and i want to just show published tags in many to many field. enter image description here -
Django query taking a long time to run
I have created a query in get_context of a Class Based View from which I generate a dict I send into a Django template to display alongside a formset. The number of records returned is about 40 and it takes about 5 seconds to run - which will translate to 30 or 40 seconds with a full set of data. Looking at Django Debug Toolbar SQL queries, it is continuing to run 40 additional queries despite adding what look like the correct select_related and prefetch_related for the reverse related table to my queryset. My models (simplified for this example): class Item(models.Model): name = models.CharField(max_length=20, primary_key=True) description = models.CharField(max_length=35, blank=True, null=True) def __str__(self): return f"{self.name}" class ItemLocSite(models.Model): name = models.CharField(max_length=10, primary_key=True) models.CharField(max_length=10) class Meta: def __str__(self): return f"{self.name}" class ItemLoc(AbstractAddArchive): item = models.ForeignKey(Item, on_delete=models.PROTECT) iloc = models.ForeignKey(ItemLocSite, on_delete=models.SET_NULL, null=True, blank=True, related_name='iloc') nloc = models.ForeignKey(ItemLocSite, on_delete=models.SET_NULL, null=True, blank=True, related_name='nloc') cp_date = models.DateField(null=True, blank=True) posted_by = models.ForeignKey(User, on_delete=models.PROTECT, max_length=10, null=True, blank=True) class Meta: def __str__(self): return f"{self.item}" class ItemInfo(AbstractAddArchive): item = models.ForeignKey(Item, on_delete=models.PROTECT) log_entry = models.ForeignKey(Log, on_delete=models.PROTECT, null=True, blank=True) c = models.CharField(max_length=2, blank=True, null=True) crec_log_entry = models.ForeignKey(InvLog, on_delete=models.PROTECT, related_name='crec_log_entry', blank=True, null=True) csts = models.ForeignKey(ItemSts, on_delete=models.PROTECT, null=True, blank=True) cfill = models.IntegerField(blank=True, null=True) comment1 = … -
How can I use python magic on Heroku as well as local windows machine?
My django project uses python-magic. In order to get magic working on my local windows machine, I've had to install python-magic-bin, otherwise I faced the error "ImportError: failed to find libmagic. Check your installation". But when I push this dependency to my Heroku (linux) server, my build fails with the error "Could not find a version that satisfies the requirement python-magic-bin==0.4.14. No matching distribution found for python-magic-bin==0.4.14." I'm importing magic as "import magic". I've seen another answer here on an old post which said the issue came from using "from magic import magic", but that's not the case here. What do I need to do to get python-magic working on both setups? I dont want to have to remember to keep python-magic-bin out of the requirements.txt for the remote server. -
Accessing current user location and showing all the users near it
I am building a BlogApp and I am stuck on a Problem. What i am trying to do :- I am trying to access user's current location and showing all the user that are nearby of the User. The Problem :- I don't know how to access the current location of user and show all the users near it. What i am using to access location :- I am using GeoDjango , GeoLocation , PostGis , gis to access location of user. All the requirements are successfully installed. models.py from django.contrib.gis.db import models from django.db.models import Manager as GeoManager class Location(models.Model): place_name = models.CharField(max_length = 80,default='') latitude = models.FloatField(null=True, blank=True) longitude = models.FloatField(null=True, blank=True) location = models.PointField(null=True, blank=True) objects = GeoManager() def __unicode__(self): return self.place_name def save(self, *args, **kwargs): if self.latitude and self.longitude: self.location = Point(self.longitude, self.latitude) super(Foo, self).save(*args, **kwargs) views.py from django.contrib.gis.geos import Point from django.contrib.gis.measure import Distance lat = 52.5 lng = 1.0 radius = 10 point = Point(lng, lat) def location(request): near_users = Location.objects.filter(location__distance_lt=(point, Distance(km=radius))) context = {'near_users':near_users} return render(request, 'mains/near_users.html', context) When i run the code in browser then it shows nothing. What have i tried I tried places = Loc.objects.distance(user_location).first() method but it didn't worked … -
Django prevent direct url access
lets say I have a "Success Page" view. .urls urlpatterns = [ path('success/', views.inquiry_success, name='inquiry-success') ] .views def success(request) return render(request, 'success_page.html', {}) I can access this view directly by typing mysite.com/success in the browser even without going through the subsequent process that should result in showing that page. How do I prevent that? -
Two Serializers.py import each other
I have 2 apps in my django project and I have to import their serializers on each other. app1.serializer.py import food.app1 import serializers app2.serializer.py import food.app2 import serializers I am getting the error related to the circular import issue. I there any way I can import the serializer? -
How to start Count from 0 in django annotation?
I have the following code to count tickets related to each event. class EventManager(models.Manager.from_queryset(EventQuerySet)): def get_queryset(self): attendees_count = Sum(Case( When(~Q(ticket__ticket_number=""), then=1), output_field=models.IntegerField() )) return super(EventManager, self).get_queryset().annotate(attendees_count=attendees_count) the When(~Q(ticket__ticket_number=""), then=1) part exculdes all tickets which do not have a ticket number. It works well for events where is more than one valid ticket (if 4, shows 4). However, when there is no ticket associated, it returns 1. Behaviour is like so; 0 related tickets - returns 1, 1 related ticket - 1, 2 related tickets - 2 etc. How to start counting from 0? so 0 related tickets - returns 0? -
Is it possible to allow a user to create a group and then add users to a group without the admin aspect?
Currently testing what i can do with django, I get that I'm able to query set users but Is it possible to allow users to add people to groups that they've created. Any group-related documentation I've found for django has been admin based. Does this require creating a new model for group? -
Django - How to send location info from template (that uses Maps Javascript api) to database
I have a simple django project that currently only displays a map with the users location that updates every 30 seconds. The location is found using googles Maps Javascript api within the template. What I need to do is send the location info to the database from the html template every time the location updates. Any answers I've seen to similar stuff use forms that require some sort of user interaction. What I need is for the info to be automatically sent to the database every time the location is updated without any user interaction. Basically, is there a way to continuously send a variable created in a templates javascript back to the database without user interaction? (The django project only has one page that only gets and shows the user location on a map so it is very basic at the moment.) -
Django - can we make a model inherit itself?
I wonder whether we can make a model that have a child inheriting the same class like: class A(models.Model): #something class B(models.Model): parent = models.ForeignKey(A, on_delete=models.CASCADE) #and some B will have class B as a child -
Django Update Session Variable with AJAX
I am making a restaurant application and I am making takeaway functionality.I currently have the basket quantity in a session variable that updates whenever the user adds an item to the basket. When they add to the basket, the whole page is refreshed. This is done by passing the FoodItem ID through the URL's via GET requests. I wish to implement AJAX in this scenario so that the session variable updates on the template and the whole page does not refresh. Current response when session variable updates: return HttpResponseRedirect("/takeaway_menu/") Url for updating the session variable: path('basket/update/<int:food_id>/', update_basket_view, name='update_basket'), Each food item form in template: <form method="get" action="{% url 'update_basket' food.id %}"> <label for="quantity">Quantity</label> <button id="increment" name="increment" type="button" onclick="decreaseQuantity(this)">-</button> <input class="quantity" id="quantity" name="quantity" type="number" value="1"> <button id="increment" name="increment" type="button" onclick="increaseQuantity(this)">+</button> <input type="submit" value="Add to Cart"> </form> how I am displaying session variable in template <a id="basket" href="{% url 'basket' %}">Basket: {{ request.session.item_quantities }} items <i class="fa fa-shopping-basket" aria-hidden="true"></i></a> Is it possible to do? I can't figure out a way to do this. -
foreign key linked field "Author" of a table "skills" is always empty in the database
I am building a web application where students can see the job posts posted by tutors. tutors can login into the site and post jobs. I created a "my post" page for tutors to see all their posts and Edit, Delete them. It seems that a foreign key field "author" comes empty in the database after posting a job which makes the post not to show up in my posts. Please help. Here is my models.py for Skills: class Skill(models.Model): author = models.ForeignKey(User, on_delete=models.CASCADE) teacher_name = models.CharField(max_length=50) skill_type = models.CharField( max_length=30, choices=SKILL_CHOICES, ) name = models.CharField(max_length=65) duration = models.IntegerField() cost = models.IntegerField() location = models.CharField(max_length=65) def __str__(self): return str(self.skill_type + " " + self.name) Here is my urls.py urlpatterns = [ path('', views.index, name='index'), path('home', views.index, name='home'), path('signup', views.signup, name='signup'), path('postskill', views.postskill, name='postskill'), path('profile', views.profile, name='profile'), path('post/<int:id>', views.post, name='post'), ] views.py for postskill and post(postskill is a modelform) @login_required def postskill(request): if request.method == 'POST': print(request.user.id) print(request.user.username) form = PostRecord(request.POST) if form.is_valid(): data = form.cleaned_data s = Skill( # author = request.user.id, teacher_name = request.user.username, skill_type = data.get('skill_type'), name = data.get('name'), duration = data.get('duration'), cost = data.get('cost'), location = data.get('location'), ) s.save() allskills = Skill.objects.all().order_by('name') return render(request, 'home.html', {'skills': allskills}) … -
Pending request to 3rd party API freezes all other django requests/endpoints
I use Django 2.2.6, python 3.7 and requests 2.25.1. Since I have started consuming a 3rd party APIs, I have noticed that if the request to this 3rd party API takes too long to respond, in the meanwhile all my Django endpoints are freezed, waiting for it. For instance, lets say I have these 2 endpoints in my Django: ENDPOINT A - GET a certain product (e.g. /product/{id}/): def get_product(request, id): product = Product.objects.get(pk=id) return JsonResponse(product) ENDPOINT B - POST a payment to a 3rd party API (e.g. /product/{id}/payment/): import requests def pay_for_product(request): payload = json.loads(request.body) response = session.post(url='https://api.paymentprocessorXPTO.com/pay/',data=payload) content = json.loads(response.content) return JsonResponse(content) For code simplicity reasons, I would like the ENDPOINT B to wait for the 3rd party API response syncronously and send it back to the user, as the code above. Thus I have not tried or wished for using a queue (e.g. celery / django-rq). The problem is: with the current code, if the session.post(...) in ENDPOINT B takes for example 20 seconds, all my Django endpoints are unavailable for 20 seconds. For instance, while a payment is being made by a client, all other client's GET product requests (ENDPOINT A) will take 20 seconds instead … -
How to instantiate a class just after starting Django server and access its members later in views.py
I want to define a class PacketCount in Django. class PacketCount: def __init__(): self.count_pkts = 0 def count_pkts(): #logic to count the number of packets I want to instantiate the object of PacketClass and continuously run the function count_pkts() just after starting starting the Django server using the command python manage.py runserver. views.py contains the following function: def index(request): # access PacketCountObj.count_pkts # return HttpResponse to display the value of PacketCountObj.count_pkts urls.py contains the following: urlpatterns = [ path('', views.index, name='index'), ] I am unable to figure out a way to automatically instantiate PacketCount class, call PacketCountObj.count_pkts() (possibly using a thread) on starting the Django server and then access PacketCountObj.count_pkts inside the views.py. I do not want to use databases, django sessions etc. -
Best free realtime database for android app
Hi am a novice user in android am plan to create a android app with realtime database, please some body refer which farmework/tool is best for develop android app and also refer Free realtime database. basically its a app with CRUD operation if anybody have sources please refer to me.. -
How to Configure Gunicorn - Heroku
I have deployed a Django application on Heroku. I am using ClearDB - MySQL as Database and trying to populate database with excel file containing data. I have succcessfully implemented and tested the webapp on localhost using phpmyadmin. The deployed application throws me an application error everytime I try to upload the excel file. Error Logs I have tried to update gunicorn configuration but have failed as I do not know how to do that I have tried reading the documentation and have tried running server but there is no effect whatsoever and I have a hunch that it is because something else to be done as it is deployed on heroku not a linux server independently. I need help on urgent basis. It will be highly appriciated if you can help me solve this issue or point me in the right direction. The actions I am performing is: reading a excel file in a dataframe cleaning and separating data into multiple tables. running df.to_sql() to upload multiple tables one by one to the MySQL database. No. of rows approximately ~ 400+ -
How do I do conditional rendering in Django Rest framework?
For example, if "localhost:8000/member/memberlist?wantjson=True" is returned in json format or If "localhost:8000/member/memberlist?wantexel=True", I want to write a code that returns to exel. How do I do it here? This is my code.. class MemberViewSet(XLSXFileMixin, ReadOnlyModelViewSet): def get_renderers(self): self.renderer_classes = [XLSXRenderer, JSONRenderer] for renderer in self.renderer_classes: print(renderer) return [renderer() for renderer in self.renderer_classes] @action(detail=False, methods=["get"], url_path="memberlist") def memberlist(self, request): result_json= request.data('wantjson') result_exel= request.data('wantexel') if result_json : self.renderer_classes= JSONRenderer elif result_exel: self.renderer_classes= XLSXRenderer resultList = Member.objects.all() serializer = MemberSerializer(resultList, many=True) return Response(serializer.data)