Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to remove all permissions from a group in Django
In Django authentication permissions, how to remove all permissions granted to a group? -
Override django admin action
I have a base admin model which I managed to override some fields like inlines, fields, etc but for some reason I cannot override the actions, what am I missing? class BaseOrderAdmin(admin.ModelAdmin): actions = ['some_action'] class OrderAdmin(BaseOrderAdmin): actions = ['some_new_action'] Order model should only have "some_new_action" action but it only has the base admin action 'some_action' so isnt overriden. -
djstripe customer subscription deletion webhook event not working properly
I have configured the djstripe webhook subscription deletion webhook to save subscriptions with cancel status. from djstripe import webhooks import djstripe.model @webhooks.handler("customer.subscription.deleted") def subscription_deletion_handler(event, **kwargs): data = event.data.get("object", {}) djstripe_subs_status = data.get('status') djstripe_subs_id = data.get('id') djstripe_subscription = djstripe.models.Subscription.objects.get(id=djstripe_subs_id) djstripe_subscription.status = djstripe_subs_status djstripe_subscription.save() But while getting subscription object it throws djstripe.models.billing.subscription.DoesNotExist exception and automatically deleted object from database. Please correct me and let me know if there is any issue in the above code. -
I am trying to import my database values, but the results are not being displayed, even though the table structure is correct
Table creation here at views.py def products(request): if request.method=='POST': form = ProductForm(request.POST) if form.is_valid(): try: form.save() return redirect('show') except: pass else: form = ProductForm() return render(request,'show.html',{'form':form}) This is the content from show.html file. <tbody> {% for items in products %} <tr> <td>{{ items.pid }}</td> <td>{{ items.pname }}</td> <td>{{ items.pprice }}</td> <td> <a href="/edit/{{ items.id }}"><span class="glyphicon glyphicon-pencil" >Edit</span></a> <a href="/delete/{{ items.id }}">&nbsp;&nbsp;<span class="glyphicon glyphicon-remove">Delete</span></a> </td> </tr> {% endfor %} </tbody> The database value isn't being displayed on the webpage. -
How does Post Request Work with Django Testing Tools
I am quite new to Django and Django Rest Framework Testing Tools and am a bit confuse on how sending a Post Request works on uploading a file. Here is the APITestCase I have to upload a file: (The file is an xml of a ZAP report) class UploadTest(APITestCase): c = APIClient() def test_file_upload_ZAP(self): self.c.force_authenticate(UserFactory.create()) with open(path.join('VMA', 'test', 'Test.xml'), "rb") as fp: self.c.post('/upload/TestZAPXML.xml', {'filename': 'name', 'attachment': fp}) The issue is the code keeps breaking due to an XML Parsing Error. I have no issue when sending a POST Request through Postman or httpie - the XML Parser works as intended. [The only difference I noticed between the Django Post request to Postman is: I change the Body in Postman to send as binary] To find why it is breaking: I decided to run a file.read() in the my fileHandler(file) method. The file prints out: b'--BoUnDaRyStRiNg\r\nContent-Disposition: form-data; name="filename"\r\n\r\nname\r\n--BoUnDaRyStRiNg\r\nContent-Disposition: form-data; name="format"; filename="Test.xml"\r\nContent-Type: application/xml\r\n\r\n The XML Parser doesn't like this and therefore throws an exception. file.read() should print out like this: <?xml version="1.0" encoding="UTF-8"?><OWASPZAPReport generated="Fri, 29 Mar 2019 21:02:52" version="2.3.1"> Which is what prints out when I am using Postman. This is also the actual XML file. What am I doing wrong in … -
send context data in django rest framework
I created a calendar in my django app for which I had to pass queryset in the context. Here's the code: def event(request): all_events = Quiz.objects.filter(owner_id=request.user, status="Assigned") context = {"events": all_events, "get_event_types": all_events, } return render(request, 'classroom/teachers/calendar.html', context) Both events and get_events_types are then used in the Django templates. Now I want to do the same in django rest framework. So I did this: Views.py class calendareventsview(viewsets.ModelViewSet): serializer_class = CalendarSerializer queryset = Quiz.objects.all() def list(self, request, *args, **kwargs): queryset = self.filter_queryset(self.get_queryset()) queryset = queryset.filter(owner_id=request.user, status="Assigned") serializer = self.get_serializer(queryset, many=True) print("serializer data is", serializer.data) return Response(serializer.data) serializer.py class CalendarSerializer(serializers.ModelSerializer): class Meta: model = Quiz fields = "__all__" Now this sends me the queryset in the data form but Can I get them against "events" or "get_event_types"? so that I can use them ? -
How to call remote API in django from views.py?
I m new to Django, I got stuck while calling remote API from views.py. from django.http import HttpResponse if request.method == 'post': r = requests.post('domain_name/api/test/', d=request.POST) And it is giving me error What is the proper way to to call API? Please Help !!!! -
How to aggregate sum of all data in django restframe work and it should filter by date
I am trying to filter data by daterange and i am able to do this but i have question how to create summary of table and filter by date also i am also attached code that you can see and help me out Actual api look like this { "count": 4, "next": null, "previous": null, "results": [ { "pk": 1, "bikeid": "425432", "milage": 12, "movingtime": "5hr 12min", "averagespeed": 14, "kgtrasported": 234, "co2": 180, "additionalbox": 4, "nouser": 8, "too": "2019-09-23", "fromm": "2019-09-23" }, { "pk": 2, "bikeid": "425433", "milage": 11, "movingtime": "5hr 12min", "averagespeed": 13, "kgtrasported": 134, "co2": 170, "additionalbox": 7, "nouser": 4, "too": "2019-09-23", "fromm": "2019-09-23" }, But i want that my data will be look like this and it will filter by date also all sum value { "count": 4, "next": null, "previous": null, "total_milage":23, "total_co2":350, "total_additionbox":4, "total_user":12 "results": [ { "pk": 1, "bikeid": "425432", "milage": 12, "movingtime": "5hr 12min", "averagespeed": 14, "kgtrasported": 234, "co2": 180, "additionalbox": 4, "nouser": 8, "too": "2019-09-23", "fromm": "2019-09-23" }, { "pk": 2, "bikeid": "425433", "milage": 11, "movingtime": "5hr 12min", "averagespeed": 13, "kgtrasported": 134, "co2": 170, "additionalbox": 7, "nouser": 4, "too": "2019-09-23", "fromm": "2019-09-23" }, Here is Views.py # Electric Bike Add class Ebike(generics.ListCreateAPIView): … -
How to let user fetch only those objects they are related to (by many-to-many relationship)?
I have a project in which there are workspaces, and each workspace can have any number of users. Users can also belong to multiple workspaces, so there's a many-to-many relationship between them. Now, I have workspace creation and membership working, but I'm having trouble setting the permissions so that only the workspace members can see the workspace. I've tried with a custom object-level permission, but it doesn't seem to work. The workspace model looks like this: class Workspace(models.Model): name = models.CharField(max_length=100) users = models.ManyToManyField(User, related_name='workspaces') The view looks like this: class WorkspaceViewSet(viewsets.ModelViewSet): queryset = Workspace.objects.all().order_by('name') serializer_class = WorkspaceSerializer permission_classes = [permissions.IsAuthenticated|BelongsInWorkspace] The serializer is like this: class WorkspaceSerializer(serializers.ModelSerializer): class Meta: model = Workspace fields = ('name', 'users') def create(self, validated_data): instance = super(WorkspaceSerializer, self) instance.users.add(self.context['request'].user) return instance And finally, the custom permission I'm trying to use here: class BelongsInWorkspace(BasePermission): def has_permission(self, request, view): return True def has_object_permission(self, request, view, obj): return obj.users.filter(pk=request.user).exists() -
How to call postgresql stored procedure using sqlalchemy?
I have developed stored procedure in postgresql which accepting 2 parameters & I am calling it using sqlalchemy using below code but getting syntax error. I have tried sqlalchemy online tutorials. connection.execute('stored_proce_name ?, ?', para_1, para_2 ) Getting error like :ProgrammingError('(psycopg2.errors.SyntaxError) syntax error at or near "stored_proce_name "\nLINE 1: stored_proce_name ?, ?\n ^\n') -
Will we write all the code in views python file?
I'm just learning Django. My English is not good, I apologize in advance. Can't I create separate files for each view, such as Codeigniter or Laravel? Do I have to write the codes of all pages in a single file? This is very difficult and complicated for me. There will be thousands of lines of code. Is there a good way? -
How to read LDAP Tree with Django
Been Searching for a week now, only found backends for Django that can use LDAP Auth, but I don't need auth I just need to read the tree and view it in Django application. I've tried to use this great package but it reads nothing. here is how I used it in my code : for sure installed it first using pip: pip install django-ldapdb then I added this lines to settings.py: DATABASES = { 'ldap': { 'ENGINE': 'ldapdb.backends.ldap', 'NAME': 'server_name', 'USER': 'user', 'PASSWORD': 'password', 'HOST': 'ip_of_host', 'PORT': '389', }, 'default': { 'ENGINE': 'django.db.backends.sqlite3', 'NAME': os.path.join(BASE_DIR, 'db.sqlite3'), }, } DATABASE_ROUTERS = ['ldapdb.router.Router'] I expected to read the tree using the command : python manage.py inspectdb But it simply reads nothing! -
How to convert nan to NULL in database table using Pandas
In my CSV some columns are empty but when I'm inserting CSV data so in the place of the empty column nun is coming but I want NULL in the table file = request.FILES['csvfile'] df = pd.DataFrame(data, columns=['company’]) if not df.loc[i]['company'] == 'NaN': company = df.loc[i]['company'] else: company = None Company.objects.update_or_create(company_name=company) I want Null in the database table when the column is empty But when I'm using the above code that giving me nun in the place of the empty column -
Pyinstaller / Django - pkg_resources.DistributionNotFound: The 'django-oauth-toolkit' distribution was not found
Creating an .exe build for a Django Project with PyInstaller, Project is using django-oauth-toolkit I have used the PyInstaller Hooks as well for django-oauth-toolkit. My hook file is like below: Hooks/hook-django-oauth-toolkit.py from PyInstaller.utils.hooks import copy_metadata, collect_data_files datas = copy_metadata('django-oauth-toolkit') datas += collect_data_files('oauth2_provider') Included in settings.py INSTALLED_APPS = [ 'oauth2_provider', Included in urls.py url(r'^o/', include('oauth2_provider.urls', namespace='oauth2_provider')), PyInstaller Command: pyinstaller D:\djangoProject\manage.py --additional-hooks-dir=D:\djangoProject\Hooks After that: djangoProject.exe runserver localhost:8000 Got the following error: File "site-packages\oauth2_provider__init__.py", line 4, in File "site-packages\pkg_resources__init__.py", line 900, in require File "site-packages\pkg_resources__init__.py", line 786, in resolve pkg_resources.DistributionNotFound: The 'django-oauth-toolkit' distribution was not found and is required by the application What should I do further? -
Django Applications with Apache and mod_wsgi on Ubuntu(aws)
not able to upload my project on apache server.i am getting this error and the server is not working but i can run the server in virtualenv. please help me out myprojectenv) ubuntu@ip-172-31-30-51:~/autobot$ tail -f /var/log/apache2/error.log [Tue Sep 24 09:16:36.552922 2019] [mpm_prefork:notice] [pid 8130] AH00169: caught SIGTERM, shutting down [Tue Sep 24 09:16:37.432345 2019] [wsgi:warn] [pid 26849] mod_wsgi: Compiled for Python/2.7.11. [Tue Sep 24 09:16:37.432374 2019] [wsgi:warn] [pid 26849] mod_wsgi: Runtime using Python/2.7.12. [Tue Sep 24 09:16:37.435410 2019] [mpm_prefork:notice] [pid 26849] AH00163: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal operations [Tue Sep 24 09:16:37.435425 2019] [core:notice] [pid 26849] AH00094: Command line: '/usr/sbin/apache2' [Tue Sep 24 09:22:32.100910 2019] [mpm_prefork:notice] [pid 26849] AH00169: caught SIGTERM, shutting down [Tue Sep 24 09:22:33.171471 2019] [wsgi:warn] [pid 28383] mod_wsgi: Compiled for Python/2.7.11. [Tue Sep 24 09:22:33.171498 2019] [wsgi:warn] [pid 28383] mod_wsgi: Runtime using Python/2.7.12. [Tue Sep 24 09:22:33.174493 2019] [mpm_prefork:notice] [pid 28383] AH00163: Apache/2.4.18 (Ubuntu) mod_wsgi/4.3.0 Python/2.7.12 configured -- resuming normal operations [Tue Sep 24 09:22:33.190552 2019] [core:notice] [pid 28383] AH00094: Command line: '/usr/sbin/apache2' -
How To integrate (Benefit Payment Gateway) via Python Code
Documentation is not so clear How To integrate via Python Code I Tried Many Things But No One Works Nothing Found -
Why does Django drop the SQL DEFAULT constraint when adding a new column?
In the latest Django (2.2), when I add a new field to a model like this: new_field= models.BooleanField(default=False) Django runs the following commands for MySQL: ALTER TABLE `app_mymodel` ADD COLUMN `new_field` bool DEFAULT b'0' NOT NULL; ALTER TABLE `app_mymodel` ALTER COLUMN `new_field` DROP DEFAULT; COMMIT; While this works when everything is updated, this is very problematic because old versions of the application can no longer create models after this migration is run (they do not know about new_field). Why not just keep the DEFAULTconstraint? -
NoReverse MAtch at /
I have developed my blog following https://tutorial.djangogirls.org/en. The website runs on localhost, but it shows NoReverse Match at / error in pythonanywhere.com This error is shown when the view is not specified. however I have given code snippets to show the views. 1)my views.py from django.utils import timezone from .models import Post # Create your views here. def post_list(request): posts = Post.objects.filter(published_date__lte=timezone.now()).order_by('published_date') return render(request, 'blog/post_list.html', {'posts': posts}) def post_detail(request, pk): post = get_object_or_404(Post, pk=pk) return render(request, 'blog/post_detail.html', {'post': post}) 2)post_detail.html {% block content %} <div class="post"> {% if post.published_date %} <div class="date"> {{ post.published_date }} </div> {% endif %} <h2>{{ post.title }}</h2> <p>{{ post.text|linebreaksbr }}</p> </div> {% endblock %} 3)post_list.html {% block content %} {% for post in posts %} <div class="post"> <div class="date"> <p>published: {{ post.published_date }}</p> </div> <h2><a href="{% url 'post_detail' pk=post.pk %}">{{ post.title }}</a></h2> <p>{{ post.text|linebreaksbr }}</p> </div> {% endfor %} {% endblock %} 4)and base.html <html> <head> <title>Krishna's blog</title> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap.min.css"> <link rel="stylesheet" href="//maxcdn.bootstrapcdn.com/bootstrap/3.2.0/css/bootstrap-theme.min.css"> <link href="//fonts.googleapis.com/css?family=Lobster&subset=latin,latin-ext" rel="stylesheet" type="text/css"> <link rel="stylesheet" href="{% static 'css/blog.css' %}"> </head> <body> <div class="page-header"> <h1><a href="/">Django Girls Blog</a></h1> </div> <div class="content container"> <div class="row"> <div class="col-md-8"> {% block content %} {% endblock %} </div> </div> </div> </body> </html> 1)the error that … -
Form always invalid when running in pytest
I'm having an issue trying to get valid form in pytest. I am testing data changes through a Django Admin action. No matter what data I post to the form, form.is_valid() will always return False. Passing a dictionary to the form directly works, however I would like to be able to test through the action to make sure that the action filters out the locked records. # test_admin.py @pytest.mark.django_db class BaseTestCase(TestCase): """Base TestCase with utilites to create user and login client.""" def setUp(self): """Class setup.""" self.index_url = '/' self.login() self.django_db_setup() def create_user(self): """Create user and returns username, password tuple.""" username, password = 'testadmin', 'password123' user = User.objects.create_superuser( username, 'admin@test.com', password, first_name='Admin', last_name='Account', ) self.user = user return (username, password) def login(self): """Log in client session.""" username, password = self.create_user() self.client.login(username=username, password=password) @staticmethod def django_db_setup(): call_command('loaddata', 'fixtures/fixture.json') class AdminTestCase(BaseTestCase): def test_responsible_list(self): products = Product.objects.filter(pk__in=[230005, 229724]) form_data = { 'action': 'set_product_class', 'apply': 'Submit', 'product_class': '1', ACTION_CHECKBOX_NAME: products.values_list('pk', flat=True), } self.client.post('/admin/store/product/', form_data, follow=True) # Assert product_classes have changed # actions.py def set_product_class(modeladmin, request, queryset): # Exclude products that are locked queryset = queryset.exclude(is_locked=True) form = None if 'apply' in request.POST: form = SetProductClassForm(data=request.POST) if form.is_valid(): # action code # forms.py class SetProductClassForm(forms.Form): _selected_action … -
The function login(request, user) successfully logs the user in. But after redirection, request.user.is_authenticated is False. What am I doing wrong?
At Checkpoint 1, request.user is available and is_authenticated is True. def login_view(request): if request.user.is_authenticated: return redirect('publicusers:dashboard', permanent=True) else: # POST if request.method == "POST": login_form = LoginForm(request.POST) context["login_form"] = login_form if login_form.is_valid(): username = login_form.cleaned_data['username'] password = login_form.cleaned_data['password'] user = None try: user = authenticate(request, username=username, password=password) except: context["error_message"] = "There was an error authenticating." return render(request, "login.html", context) if user is not None: if user.is_active: login(request, user, backend='publicusers.backends') # Checkpoint 1 print('User:', type(user), request.user, request.user.is_authenticated, request.session) return redirect(reverse('publicusers:dashboard'), context) At Checkpoint 2, request.user.is_authenticated is False; but request.session is available and prints the same result in both the functions. def dashboard_view(request): # Checkpoint 2 print('Dashboard:', request.user.is_authenticated, request.session) if not request.user.is_authenticated: return redirect('publicusers:login', permanent=True) context = { "head_title": "Dashboard", "page_title": "Dashboard Page", "content": "Dashboard Content", } return render(request, "dashboard.html", context) Any assistance would be greatly appreciated. -
Do I have to manage Database concurrency in django?
I came across this article https://medium.com/@hakibenita/how-to-manage-concurrency-in-django-models-b240fed4ee2 Which describes how a request can change a record that another request is currently working with. Now this article is from 2017 and I haven't found anything about django cobcurrency since. Also manage.py is single threaded. Does this mean the issue is now managed by django internally or do I have to manage concurrency manually still when I deploy it with apache? -
Celery: why are there seconds of time gap from when a task is accepted and when it starts to execute?
I have a celery task: @app.task(bind=True, soft_time_limit=FreeSWITCHConstants.EXECUTE_ATTEMPTS_LOCAL_SOFT_TIME_LIMIT) def execute_attempt_local(self, attempt_id, provider_id, **kwargs): ... that is processed by a (remote) worker with the following config: celery -A mycompany.web.taskapp worker n -Q execute_attempts-2 --autoscale=4,60 This task gets spawned thousands at a time and has historically completed in 1-3s (it's a mostly I/O bound task). Recently as our app's overall usage has increased, this task's completion time has increased to 5-8s on average and I'm trying to understand what's taking up the extra time. I noticed that for many tasks taking 5-8 seconds, ~4s is taken in the in between the task being accepted by the thread and executing the first line of the task: [2019-09-24 13:15:16,627: DEBUG/MainProcess] Task accepted: mycompany.ivr.freeswitch.tasks.execute_attempt_local[d7585570-e0c9-4bbf-b3b1-63c8c5cd88cc] pid:7086 ... [2019-09-24 13:15:22,180: WARNING/ForkPoolWorker-60] PERF - entering execute_attempt_local What is happening in that 4s? I'm assuming I have a Celery config issue and somewhere there is a lack of resources for these tasks to process quicker. Any ideas what could be holding them back? -
Django views calls functions several times
I am creating a browser-based RPG where fighting mechanics are built into a model called "Battle". It performs actions on Hero, Monster and Item models according to some formulas. Each action adds a message to a "battle log". A player can issue a fight against another player or NPC in a form. When the form is submitted, it calls the same view, the Battle object is created, the characters are drafted and the game mechanics are run. For some reason, old "Battle" objects are still "selected" between runs of these views, as long as it's in the same web session. So even though I create a new object, the old battle log gets carried over to this new object. What am I doing wrong here? def battle_log(request): if request.session["last_battle"]: pk = request.session["last_battle"] b = Battle.objects.get(pk=pk) context_log = [] for l in b.messages: context_log.append(l) request.session["last_battle"] = "" context = { 'battle_log' : context_log, } return render(request, 'battle.html', context) else: return redirect('/game/monster') def fight_select_monster(request): row = [] form = SelectMonster() context = { 'form': form } if request.method=='POST': form = SelectMonster(request.POST) if form.is_valid(): monster = request.POST.get('monster') hero = request.POST.get('hero') hero = Hero.objects.get(pk=hero) monster = Monster.objects.get(pk=monster) hero.save() monster.fatigue = 0 b = Battle() … -
Fresh cookiecutter django project shows "Invalid syntax" at environ.py
I started my first project with cookiecutter using the cookiecutter-django template. When I tried to start it from PyCharm using the virtualenv, it gave me an error in a lib file: environ.py, telling me this: File "/home/madtyn/venvs/nana/lib/python3.6/site-packages/environ.py", line 114 raise ValueError, "No frame marked with %s." % fname ^ SyntaxError: invalid syntax After searching, I consulted somebody and I was recommended another way. I tried, as they told me, to make a new venv, activate it and run the server from command line but the same thing seems to happen. I don't think I did anything wrong. These are my specifications: Kubuntu (64bit arch) Python 3.6.8 (both the venv and the main one) cookiecutter 1.6.0 (installed through pip3) PyCharm 2019.2.2 -
How can I apply groupby on django queryset
I have a queryset say, a_query = <QuerySet [{'id': 1, 'user_id': 10, 'name': 'xyz'}, {'id': 2, 'user_id': 10, 'name': 'abc'},{'id': 3, 'user_id': 12, 'name': 'pqr'}]> So here I want to apply groupby on user_id so the result should be, [(10, [['xyz', 1], ['abc', 2]]), (12, ['pqr', 1])] I tried using itemgetter and groupby but that doesn't work.