Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django rest framework TokenAuthentication custom `obtain_auth_token` view not authenticating user
Here is my situation: I am using the django rest framework with TokenAuthentication. Everything works as expected, except the login call, where the client sends credentials to authenticate, and receives the token.key value associated with the authenticating user. Every call to login a user returns status=400 content='{"non_field_errors":["Unable to log in with provided credentials."]}' This indicates that the call to django.conf.auth.authenticate() in the TokenAuthentication serializer returned None rather than a valid user. Pertinent details: I made a slight modification to the built-in ObtainAuthToken class, and the AuthTokenSerializer class to facilitate logging users in with email + password rather than username + password. I also changed the way User objects are created, so that passwords are not passed back to the client. I know it's a hashed value, and will be using SSL, but I still find it unnecessary. I suspect I am doing something wrong in the second modification, as I'm fairly certain the thing that isn't working the way I expect it to is the call to authenticate() in the AuthTokenSerializer. Any help would be greatly appreciated!! Here are the relevant files: Abbreviated settings.py INSTALLED_APPS = [ # included middleware 'django.contrib.admin', 'django.contrib.auth', 'django.contrib.contenttypes', 'django.contrib.sessions', 'django.contrib.messages', 'django.contrib.staticfiles', # extra middleware 'rest_framework', … -
Triggering 'chosen:updated' on Django Admin popup close
I'm using the Django Admin portal as my primary methodology for toying with models in the database for my application and I prefer using the Chosen Select plugin to represent the select elements on the page. By default, the Django Admin pages are configured to trigger select elements to update their options if you modify them via the change-related, add-related, or delete-related buttons next to the appropriate fields. However, this doesn't seem to trigger the change event for the select element... I have the following code in a custom JavaScript file tied to the admin pages: $(document).ready(function() { options = { no_results_text: "Entity not found...", placeholder_text_multiple: "Choose entities...", search_contains: true } $('select').chosen(options).change(function () { $(this).trigger('chosen:updated'); }); }); I know that this code does its job because the use of $('#select').change() in the browser's console will update the Chosen Select element accordingly, but this event isn't fired when the Admin popup window is closed and the select element's value is changed... In short, I need to know what what event is triggered when the select element's options are changed so I can update the Chosen Select box as well. I could in theory have an event fire when the button that's … -
How do I resolve access denied aws s3 files?
Im trying to make files on my s3 bucket (CSS JS files) accessible to a Django application running in heroku. I think I have the settings.py configured correctly. However when I try to make changes to permissions in the S3 bucket i get access denied. I added cors and bucket policy is set to public. Ultimately when I load the application from heroku Im getting 403 errors when trying to access the static files. Bucket policy: { "Version": "2012-10-17", "Statement": [ { "Sid": "AddPerm", "Effect": "Allow", "Principal": { "AWS": "*" }, "Action": "s3:*", "Resource": "arn:aws:s3:::NameOfBucket/*" } ] } CORs configuration: <?xml version="1.0" encoding="UTF-8"?> <CORSConfiguration xmlns="http://s3.amazonaws.com/doc/2006-03-01/"> <CORSRule> <AllowedOrigin>*</AllowedOrigin> <AllowedMethod>GET</AllowedMethod> <MaxAgeSeconds>3000</MaxAgeSeconds> <AllowedHeader>Authorization</AllowedHeader> </CORSRule> </CORSConfiguration> How can I get the permissions to make changes in the s3 bucket please? -
Start Django config app only once when using multiple Gunicorn workers
I'm using : python 3.6 django==2.1.1 gunicorn==19.9.0 i have done the following: created a django project called api created an apiapp (an app in my project) and i have this code in api_app's apps.py : from django.apps import AppConfig from api import settings class Apiapp(AppConfig): name = 'apiapp' verbose_name = "random_name" def ready(self): self.job() @classmethod def job(cls): ### doing whatever here for example : print(settings.SHARED_VARIABLE) and the following in api_app's __init__.py: import os default_app_config = 'linkedin.apps.LinkedinConfig' i'm creating an API so i am required to use multiple workers when deploying: gunicorn api.wsgi -w 10 now, my issue is that the function job which is called when the server is started, is getting called 10 times because i'm using 10 gunicorn workers, i would like to call it only once another thing that i would like to do is to have the settings.SHARED_VARIABLE variable, shared between the different workers. this variable will be updated only by the worker that will launch the app.py on server start. Thank you ! -
How do I resolve invalid literal for int() with base 10: 'arbitrary_username'?
I've read what I could manage to dig up in terms of UpdateView, test_func and get_object within the docs and on SO not to mention various articles. It has now been three days of grinding along and I'm out of ideas. Can someone explain test_func() to me like I'm five, please? :) The views.py is: class GalleryUpdateView(LoginRequiredMixin, UserPassesTestMixin, UpdateView): # form_class = GalleryUpdateForm model = Gallery slug_field = 'owner' slug_url_kwarg = 'username' success_url = '/' def form_valid(self, form): form.instance.owner = self.request.user return super().form_valid(form) def test_func(self): obj = self.get_object() if self.request.user == obj.owner: return True else: return False The models.py is: class Gallery(models.Model): class Meta: verbose_name = 'gallery' verbose_name_plural = 'galleries' owner = models.ForeignKey(User, on_delete=models.CASCADE) extra_img = models.ImageField(default='default.jpg', upload_to='images') def __str__(self): return self.owner.username def get_absolute_url(self): return reverse('account:view-profile', args=[str(self.owner.username)]) def save() Finally, the urls.py: urlpatterns = [ ... ... path('update-gallery/<str:username>/', GalleryUpdateView.as_view(), name='update-gallery'), ] I had it running without the fancy UserPassesTestMixin in a more simplified setup; it did what it was supposed to, but as soon as I try to implement specific users, I'm in trouble. I've tried a whole slew of permutations of the test_func variables, and I believe this is the closest I've come to an actual resolution. Here I … -
Django: from 2 functions to 1 class
I've 2 functions: 1 for creating the order, 1 for just for displaying records of a model. These are: cart_charge (works with request.POST) and cart_detail However, I also have 2 models that need to interact with them and need to be called between them. But since there are called inside the 2 different functions I wondering if it is ok to do so. How can I convert the 2 functions into 1 single class: This one creates the Order as order_details. order_details needs to be called in cart_details for creating the OrderItem. @csrf_exempt def cart_charge(request): culqipy.public_key = settings.CULQI_PUBLISHABLE_KEY culqipy.secret_key = settings.CULQI_SECRET_KEY amount = request.POST.get('amount') currency_code = request.POST.get('currency_code') email = request.POST.get('email') source_id = request.POST.get('source_id') last_four = request.POST.get('last_four') dir_charge = {"amount": int(amount), "currency_code": currency_code, "email": email, "source_id": source_id} charge = culqipy.Charge.create(dir_charge) transaction_amount = int(charge['amount'])/100 #Necesario dividir entre 100 para obtener el monto real, #Esto debido a cómo Culqi recibe los datos de los pagos transaction = Transactions.objects.create( charge_id = charge['id'], last_four = last_four, email = email, amount = transaction_amount, ) try: order_details = Order.objects.create( token = source_id, #nombre del token total = transaction_amount, emailAddress = email, billingName = billingName, billingAddress1= billingAddress1, billingCity= billingCity, billingPostCode = billingPostCode, billingCountry= billingCountry, shippingName= shippingName, shippingAddress1= shippingAddress1, … -
How can I know Django Models dependencies that avoid to delete an instance due to models.PROTECT setting
I have a Django model Reservation that is the root of a very complex structure, because it is the base for other models for different parts of the system, like reservation itinerary, operations, quotations, rates, etc., that have their own dependencies also. Some times we requiere to delete a reservation record, but we are unable due to dependencies. The problem is that the dependencies tree is so complex, that it is very time consuming to explore all the possible dependencies. Is there any way to know all the objects that reference a model object through foreign keys, so they can be reported to users so they can take of them and make the required changes to be able to delete the object? -
Is it possible to make free mezzanine cms themes (Moderna, Flat, Nova & Solid) editable in admin?
I found some Django Mezzanine CMS themes (Moderna, Flat, Nova & Solid) on Github. I managed to use these in Mezzanine CMS. But these themes are implemented as 'HOMEPAGE AS STATIC TEMPLATE' in urls.py. I tried to change this according to the instructions (among others in the comment of urls.py and the documentation) to 'HOMEPAGE AS AN EDITABLE PAGE IN THE PAGE TREE'. This was only partly succesful. In the end I didn't get any errors but I only saw the outline of the page not the content. Has anyone exerience with this? Can this be done or are the themes simply to complicated to change them into editable pages in the admin? KR Berweb -
Django Apache redirect static file issues
My site was setup with Apache and it does a redirect to serve Django. ProxyPass / http://localhost:15001/ ProxyPassReverse / http://localhost:15001/ Now everything else works, except the static files. When I try to access the admin, the css / js dont load, and if I try the static files directly, I get this: So, the redirect is making it think it's not defined in the URL's file. How do I resolve this? -
Channel and Event in Pusher
I am trying to create a live messaging app in django where only 2 users(one-to-one) can talk simultaneously.Pusher provides a tutorial on messaging app in its doc where everybody who is logged in can type and see message. So,i am struggling to understand event and channel in pusher. def broadcast(request): pusher.trigger(u'a_channel', u'an_event', {u'name': request.user.username, u'message': request.POST['message']}) return HttpResponse("done"); for example the above code!Here i understand about pushing the username and message but not these two parameters u'a_channel' and u'an_event'. What they do actually? -
Django AAdmin: Multiple editable entries in one column in ChangeList View
with this model: class MyModel(models.Model): a = models.BooleanField(default=False) b = models.BooleanField(default=False) c = models.BooleanField(default=False) and this admin definition: class MyModelAdmin(admin.ModelAdmin): list_display = ( 'a', 'b', 'c', ) list_editable = ( 'a', 'b', 'c', ) I have a, b and c in one column each. Is there a way to place a, b and c in the same column? I tried this: class MyModel(models.Model): a = models.BooleanField(default=False) b = models.BooleanField(default=False) c = models.BooleanField(default=False) def all(self): return self.a, self.b, self.c class MyModelAdmin(admin.ModelAdmin): list_display = ( 'all', ) list_editable = ( 'all', ) and get following error: "The value of 'list_editable[0]' refers to 'all', which is not an attribute of 'app.MyModel'." Any suggestions place a, b and c in one column while being able to use "list_editable"? -
Django Dynamic formset: correct usage with inline formsets?
I am using Django Formsets to make invoices (need to add items, people, materials etc.). To be able to add and delete formsets, I am using Django Dynamic Formset. However, this plugin seems to be no longer maintained and while it seems to work fine for modelformsets, the problem arises with inline formsets. I am using this logic to select the number of extra forms I need for the view(where you can modify your invoice) costi_offerta_inline = forms.inlineformset_factory(offerta_impianti, offerta_impianti_costi, form=offerta_impianti_costi_form, extra=0) if (offerta_impianti_costi.objects.filter(offerta_ref=instance).count() > 0) else forms.inlineformset_factory(offerta_impianti, offerta_impianti_costi, form=offerta_impianti_costi_form, extra=1) Problem is that doing this(it's probably not the reason, but you never know) the formsets act weird. If I add a new form, it works fine. Total Forms updates adding plus one and form is displayed correctly. But when I try to remove one, Total Forms doesn't decrement and I'm left with an extra form that blocks all validation from happening. Can someone help me? -
Django can't delete user from my database
I have a problem with my Django project. I need to delete 1 or more users from my database but I can't do it because it returns this error: __str__ returned non-string (type tuple) I tried deleting it from my views but it didn't work. Than I went and used admin panel to try to delete it but the same problem happened. If someone could give some advice or suggestion that would be great. Thank you. -
Django- Using django_filter and Django Forms together
So i am trying to figure out if there is a way to filter results of the database with django_filter and then (on the same url) use the filtered results in a form to edit them. I have a FilterSet which works just fine and the results are plain text with a edit button that gets me to another url where I can edit the results in a Form. However I would like to edit the results on the same webpage to edit them right then and there. SO basically just combining the filtering and the editing on one page. Is there a way to combine both templates? Here is some of my code. my filters.py class CSVFilter(django_filters.FilterSet): class Meta: model = Excel7 fields = {'test1' : ['icontains'], 'test2' : ['icontains'], 'test3' : ['icontains'], 'test4' : ['icontains']} my forms.py class DocumentForm(forms.ModelForm): gebaeudebereich = forms.CharField(required=False) gebaeudenummer = forms.CharField(required=False) ebene = forms.CharField(required=False) raum = forms.CharField(required=False) dose = forms.CharField(required=False) switch_ip = forms.CharField(required=False) switch_port = forms.CharField(required=False) datum = forms.CharField(required=False) akteur = forms.CharField(required=False) class Meta: model = Excel7 fields = ('gebaeudebereich', 'gebaeudenummer', 'ebene', 'raum', dose', 'switch_ip', 'switch_port', 'datum', 'akteur', ) The view that handles the filtering def filter_location(request): user_list = Excel7.objects.values() user_filter = CSVFilter(request.GET, queryset=user_list) … -
ValueError: invalid literal for int() with base 10: '' "IntegerField"
Can you explain it to me? Why this is my models.py? I get this error message: ValueError: invalid literal for int() with base 10: '' from django.db import models # Create your models here. class Contact(models.Model): first_name = models.CharField( max_length=255, ) last_name = models.CharField( max_length=255, ) email = models.EmailField( max_length=255, ) nomor_hp = models.IntegerField( ) -
Mail to with attachment in django
How to open default mail client in browser with all fields pre populated with an attachment. I tried using web browser mailto method but it doesn't seem to support attachment -
how to fix createsuper error invloving a post save signal
Am trying to create a superuser for my new django project, it involves a post save signal that creates user dashboard and save user phone number from the POST request, i define a get_phonenumber() function that returns phonenumber to the signals.py where the function is called. the code work pretty fine when creating a normal user from the browser but when it comes to creating a superuser i have this error (Phone_number not define) -
Django-Admin: how to use one field for both inlinemodel and model
Hello i am working in django admin panel, i am making 2 models workflow, and workflow stages, both has filed company workflow is inline inside of workflow my question is how to make all of the workflow stages uses the same company field up in the workflow. class WorkflowStageInline(admin.TabularInline): model = WorkflowStage extra = 7 class WorkflowAdmin(admin.ModelAdmin): inlines = [WorkflowStageInline, ] list_display = ('id', 'company', 'is_template') list_display_links = ('id', 'company') -
How to create a search functionality that searches for ingredients when the user searches for a meal?
I am trying to create a project in Django which allows users to see a list of images when they search for a particular meal, but I am not sure how I would start this project. I can see that there are some apis available, however, I intend to create this from scratch. -
Getting error in browser console- Uncaught ReferenceError: allauth is not defined
I have been trying to use allauth (facebook js sdk) with my django project. So I put the below lines in layout Setting file code: SOCIALACCOUNT_PROVIDERS = { 'facebook': { 'METHOD': 'js_sdk', 'SCOPE': ['email', 'public_profile'], 'AUTH_PARAMS': {'auth_type': 'reauthenticate'}, 'INIT_PARAMS': {'cookie': True}, 'FIELDS': ['id','email'], 'EXCHANGE_TOKEN': True, #'LOCALE_FUNC': 'path.to.callable', 'VERIFIED_EMAIL': True, 'VERSION': 'v2.12', } } layout file code: {% load socialaccount %} {% providers_media_js %} Facebook Connect Getting below error in browser console when I trying to connect with facebook. Uncaught ReferenceError: allauth is not defined. Please help me. hanks in advance. -
WebSocket service for multiple django projects using pub/sub redis
Description I have two django projects which are separated from each other and doing their own works, but under the same external authorization system. I want to have a shared web socket server for these two projects. So that every message that is published on redis with any of these two django projects, web socket (which is listening on redis) gets it and send it to his connected users via web socket. Note web socket should check message content and see what user to receive it and send it to proper user. Question 1- should i use django for web socket server. if So what framework should i Use, what you suggest. django-channels or ...? 2- I want the published messages be sent to their proper users, For example a notification for user 1 is created django project 1. this message is published and web socket receives it. how should i send this message, which format for better outcome. and How to find out the user to receive it in web socket server side. 3- If a message is published for a user, but that user is not connected via web socket, should i remove it from redis or let … -
When I try to add new category in django admin, OperationalError at /admin/mediaportalapp/category/add/
I made new project on django. Add two models and register them in admin! Whem i try to add something in admin panel i have mistake: I try another 3 new django projects the same problem. I clear all cash in browser I try another port OperationalError at /admin/mediaportalapp/category/add/ no such table: main.auth_user__old Request Method: POST Request URL: http://127.0.0.1:8001/admin/mediaportalapp/category/add/ Django Version: 2.1.4 Exception Type: OperationalError Exception Value: no such table: main.auth_user__old Exception Location: /home/arch/Рабочий стол/mediaportal_project/MediaPortalEnv/lib/python3.7/site-packages/django/db/backends/sqlite3/base.py in execute, line 296 Python Executable: /home/arch/Рабочий стол/mediaportal_project/MediaPortalEnv/bin/python3.7 Python Version: 3.7.1 Python Path: ['/home/arch/Рабочий стол/mediaportal_project/mp_portal', '/home/arch/Рабочий стол/mediaportal_project/MediaPortalEnv/lib/python37.zip', '/home/arch/Рабочий стол/mediaportal_project/MediaPortalEnv/lib/python3.7', '/home/arch/Рабочий ' 'стол/mediaportal_project/MediaPortalEnv/lib/python3.7/lib-dynload', '/usr/lib64/python3.7', '/usr/lib/python3.7', '/home/arch/Рабочий ' 'стол/mediaportal_project/MediaPortalEnv/lib/python3.7/site-packages'] Server time: Sat, 22 Dec 2018 14:50:32 +0000 -
Django Mock QuerySet
Players class: class Players: def __init__(self): self.players = PlayerModel.objects.all() def count(self): return len(self.players) Test: def setUp(self): self.players = Players() @patch('riskgame.entities.Players.count', return_value=9, create=True) def test_count(self): number = self.players.count() self.assertEqual(number, 9) This test throws: Failed: Database access not allowed, use the "django_db" mark, or the "db" or "transactional_db" fixtures to enable it. But why needs this test the database? It seems like that the @patch on Players.count() is'nt working. Is there a better solution to make this more testable? -
Django admin form validation
In my django app, I want to add a validation to the automatically generated admin form of a model. I want to raise a ValidationError if the attribute title equals "test". I have tried the following in admin.py, but nothing happens if the title is "test". Could anyone help, please? from django.contrib import admin from django.forms import ModelForm, ValidationError from .models import MyModel class MyModelAdminForm(ModelForm): class Meta: model = MyModel fields = '__all__' def clean(self): cleaned_data = super().clean() title = cleaned_data.get('title') if title == 'test': raise forms.ValidationError('invalid!') return cleaned_data class MyModelAdmin(admin.ModelAdmin): form = MyModelAdminForm admin.site.register(MyModel) -
Why does heroku say no module found on profile read
I am tryning to deploy a app. But I am getting the following error.I think this might have something to do with wsgi file path location. I am getting this error: 2018-12-22T13:31:42.980813+00:00 app[web.1]: Traceback (most recent call last): 2018-12-22T13:31:42.980815+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/arbiter.py", line 583, in spawn_worker 2018-12-22T13:31:42.980817+00:00 app[web.1]: worker.init_process() 2018-12-22T13:31:42.980818+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 129, in init_process 2018-12-22T13:31:42.980820+00:00 app[web.1]: self.load_wsgi() 2018-12-22T13:31:42.980821+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/workers/base.py", line 138, in load_wsgi 2018-12-22T13:31:42.980823+00:00 app[web.1]: self.wsgi = self.app.wsgi() 2018-12-22T13:31:42.980824+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/base.py", line 67, in wsgi 2018-12-22T13:31:42.980826+00:00 app[web.1]: self.callable = self.load() 2018-12-22T13:31:42.980827+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 52, in load 2018-12-22T13:31:42.980829+00:00 app[web.1]: return self.load_wsgiapp() 2018-12-22T13:31:42.980830+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/app/wsgiapp.py", line 41, in load_wsgiapp 2018-12-22T13:31:42.980832+00:00 app[web.1]: return util.import_app(self.app_uri) 2018-12-22T13:31:42.980834+00:00 app[web.1]: File "/app/.heroku/python/lib/python3.6/site-packages/gunicorn/util.py", line 350, in import_app 2018-12-22T13:31:42.980835+00:00 app[web.1]: __import__(module) 2018-12-22T13:31:42.980841+00:00 app[web.1]: ModuleNotFoundError: No module named 'EIIIFeedback' enter image description here My pr0ject structure is: my Procfile is : web: gunicorn EIIIFeedback.wsgi:application