Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
Django and NodeJs - Manage authentication
I'm using for my main app Django, and for a third party modules NodeJs with Express. Now, i have to manage in a secure way the authentication of the third party app to my main app written in Django, that implements Tokens for API and default Django Authentication methods. I have a bunch of ideas in order to achieve that, like: Create an API endpoint that checks the authentication via Token and call that API from the NodeJs App for every request (so, the auth Token it will be stored in a secure way to the backend of the third party app) Check the auth cookie from the NodeJs app I think that the first approach is the way to go, but if anyone has some smarter ideas i'll be glad to listen them! Final remarks/notes: These two apps are exposed to the users using a reverse proxy, and the authentication check can be managed directly backend-to-backend, and, if it's all ok, the application will be served to the user, without exposing any token authentication to the frontend -
Iterate through models with AJAX in Django
To say I'm struggling is an understatement. I have a form that I am trying to update with AJAX javascript, and using the form fields in a Queryset to retrieve data from my database in a model. I then return these models through AJAX on the template. But how do I retrieve the models in my template? I simply do not understand where/how JS pushes the models into my template. Here's my setup. views.py def show_movielens(request): if request.is_ajax(): if request.method == 'POST': q = {} # retrieve data from AJAX POST gender = request.POST.get('post_gender') age = request.POST.get('post_age') occupation = request.POST.get('post_occupation') if age != 'all': q.update({'user__age_range': age}) if gender != 'all': q.update({'user__gender': gender}) if occupation != 'all': q.update({'user__occupation': occupation}) queryset = Movielens.objects.all().filter(**q) serialized_obj = serializers.serialize('python', queryset) # serialized my object in python, could also be 'json' response_data = {} response_data['result'] = 'Create post successful!' response_data['table'] = serialized_obj return HttpResponse(response_data) # these two other methods below do not work: render() gives me nothing and JsonResponse gives me a 500 internal error :/ # context = { # 'table': queryset, # } # return render(request, 'journal/index.html', context) # return JsonResponse({'table': list(queryset)}) I've checked and HttpResponse is the only function that correctly returns my … -
how to chain queryset mixin for django rest viewsets?
I need to write the following querysets mixins: class VendorOwnedQuerySetMixin(models.QuerySet): def get_objects_for_vendor(self, request): vendor_user = VendorUserModel.objects.get(user=request.user) return qs.filter(vendor=vendor_user.vendor) class OrganizationOwnedQuerySetMixin(object): def get_objects_for_organization(self, request): return self.filter(organization__domains__name=hostname_from_request(request)) All's working well because some model managers will inherit the first mixin and some inherit the second. Then inside the get_queryset of the viewset, i will call the appropriate get_objects method. example def get_queryset(self, queryset=None): return Some.objects.get_objects_for_organization(self.request) Now I need to have a django rest viewset that needs to run the get_queryset method that runs both filters. How do I "chain" them within the get_queryset method? Because I want to reuse my code where possible -
How to show every user specific payment for them in django?
I have a problem. I have given some random numbers in admin page as a balance for users and connected it to database. Basically I want it to show for different users different payments. But I don't know what to write in views.py and html page so that it shows different payment for different users. views.py def payment(request): receiving1 = Payment.objects.all() for field in receiving1: field.payment_numbers context = { 'receiving1': receiving1 } return render(request, 'index.html', context) models.py class Payment(models.Model): payment_numbers = models.CharField(max_length=100) HTML PAGE {% for numbers1 in receiving1 %} <li style="float: right;">Your Balance: Rs. {{numbers1.payment_numbers}}</li> {% endfor %} -
How to use razorpay in django for payments?
I am completely new to using payment gateway and I have never done it before. I can't even find a proper github project that tells me how to do it. I know how to install and addd it in settings, but i have no idea what should I do for views or even templates. If anyone has any guthub link which tells what to do completely, please tag it. I am clueless right now. I am addding my payment model if it is of any use for integrationg payment gateway. Please help. Really Needed. thanks in advance. models.py class Payment(models.Model): username = models.ForeignKey(UserProfile,on_delete = models.CASCADE, related_name='name') amount = models.IntegerField() date = models.DateField(blank=False, default = datetime.datetime.now()) payment_mode = models.CharField(max_length=50, choices=PaymentModes,null=True,blank=True) collected_by = models.ForeignKey(UserProfile,on_delete = None, related_name='collected_by') is_due = models.BooleanField(default = False) -
Django redirect with parameters not in the URL
Although this may seem like a question that has been asked before, answers I've seen all include having the parameters in the URL which is not what I want. What I currently have is a set of URL's that work as intended but don't follow conventions and aren't clear to look at. I'll skip all the background of what I am doing since it isn't necessary to understand nor help me find a solution. I have a URL in the following format: exchange/university/<int:univID>/personal-info which is a page specifically for users to enter their personal information on. This page has a button which will redirect users to a new page which is where my problem lies. The current redirect URL looks like this: exchange/university/<int:univID>/<int:studID>/department and the redirect command within my code looks like this: return redirect('/exchange/university/'+str(univID)+'/'+str(studentID)+'/department') What I would like is simply to pass the student ID as a parameter into the redirect and not have it appear in the URL since having it in the URL doesn't follow the site structure where users enter information with regards to a specific university and therefore, for me, only the university ID is necessary to understand what the page is supposed to do … -
How is it possible to use group in field lookups in the query below
Looking at django documentation, Permission has this fields (id,name,content_type and codename). I want to know how is it possible to use group in the fieldlookup in the second block of the code? from django.contrib.auth.models import Permission user_permissions = Permission.objects.filter(id__in=[1]).values_list('codename', flat=True) print("PERMISSIONS===>",user_permissions) Outputs: PERMISSIONS===> <QuerySet ['add_logentry']> user_permissions = Permission.objects.filter(group__id__in=[1]).values_list('codename', flat=True) print("PERMISSIONS===>",user_permissions) Outputs: PERMISSIONS===> <QuerySet ['add_user', 'change_user', 'delete_user']> -
Heroku app cannot connect to Celery worker
I have created a Django app which is using Celery for task processing. It’s working fine locally but when I pushed it to Heroku, I found that app cannot connect to Celery worker. I can see worker is running without any problem. $ heroku ps === web (Free): gunicorn my_django_project.wsgi --log-file - (1) web.1: up 2019/08/10 11:54:19 +0530 (~ 1m ago) === worker (Free): celery -A my_django_project worker -l info (1) worker.1: up 2019/08/10 11:54:19 +0530 (~ 1m ago) But when I checked the logs I found this error message 2019-08-10T06:04:30.402781+00:00 app[worker.1]: [2019-08-10 06:04:30,402: ERROR/MainProcess] consumer: Cannot connect to amqp://guest:**@127.0.0.1:5672//: [Errno 111] Connection refused. 2019-08-10T06:04:30.402801+00:00 app[worker.1]: Trying again in 32.00 seconds... Seems like app cannot connect to celery worker. Project directory structure Project | ├── data/ ├── db.sqlite3 ├── manage.py ├── Procfile ├── README.md ├── requirements.txt ├── my_app/ │ ├── admin.py │ ├── apps.py │ ├── __init__.py │ ├── tasks.py │ ├── templates │ ├── tests.py │ ├── urls.py │ └── views.py ├── my_django_project/ │ ├── celery.py │ ├── __init__.py │ ├── settings.py │ ├── staticfiles │ ├── urls.py │ └── wsgi.py ├── runtime.txt └── static/ Procfile web: gunicorn my_django_project.wsgi --log-file - worker: celery -A my_django_project worker -l info celery.py … -
How to order django charfield by alphabetical+numeric
I have the following a model, I already try to order_by('cell_name') but no same what I want. I want to order base on alphabet+number field. Could you please have your suggestions on this??, any help will be appreciated. #mymodel class BuildingCell(models.Model): .... cell_name = models.CharField(max_length=100, blank=True, null=True) #myqueryset q1 = BuildingCell.objects.all().order_by('cell_name') # myresult cell_name 10a 10b 10c 11a 11b 1a 1b 2a 2b The result that I want 1a 1b 2a 2b 10a 10b 11a 11b -
RequestError(400, 'search_phase_execution_exception', 'failed to find geo_point field [loc.location]')
I have seperate columns of latitude and longitude in my django model and have indexed my data using elasticsearch-dsl. I want to find the points in the database which are within a certain range. Since I have separate fields of latitude and longitude in models , I have defined a function for geopoint in models.py . /.models.py @property def type_to_string(self): x1 = Locations.objects.all() return {'lat': self.lat, 'lon': self.lng} ./documents.py loc1 = fields.GeoPointField(attr='type_to_string' , lat_lon = True) It is indexing successfully, but when i run the checker function , I get error def checker(): s = LocationDocument.search() body = { "query": { "bool" : { "must" : { "match_all" : {} }, "filter" : { "geo_distance" : { "distance" : "200km", "location" : { "lat" : 40, "lon" : -70 } } } } } } s = s.from_dict(body) t = s.execute() for x in t: print(x.address) I get error failed to find geo_point field[location] . How can I rectify this error ? -
When should you not use Celery?
It seems pretty clear to me when to use Celery with Django Scheduled tasks Sending an email every 24 hours Multiple complex components to load Facebook pulling in pictures and text separately Large user requests User request a report, report is emailed to them when ready "No immediate response" user requests User requests a password reset link, you can tell them it's been sent instantly, without waiting for email to actually be sent (2-3 seconds) When should Celery not be used? Some situations seem very straightforward, like simple, < 1 second queries from databases -- probably don't need Celery for that. I have an app where user uploads content, waits about 20 seconds for the content to be processed, then gets their response. I'm having trouble figuring out whether Celery is the right option in this case. It seems when the user is waiting for the response, Celery isn't the option. Or is Celery always the option, if you have the resources to handle it and make sure it executes quickly? Similar question was asked here, with the idea that Celery should only be used for tasks that are "purely out-of-process" -
Pop up messages box are not displayed
I want after a user is registered a message showing that user is successful registered should display, the same for same for logout and login The message is displayed, but it doesn't pop up I think the problem is on the script side. Please help!! base.hmtl {% if messages %} {% for message in messages %} {% if message.tags == 'success' %} <script>M.toast({html: " {{message}}, classes:"blue rounded",displayLenght:2000});</script> {% elif message.tags == 'info' %} <script>M.toast({html: " {{message}}, classes:"blue rounded",displayLenght:2000});</script> {% elif message.tags == 'warning' %} <script>M.toast({html: " {{message}}, classes:"blue rounded",displayLenght:2000});</script> {% elif message.tags == 'error' %} <script>M.toast({html: " {{message}}, classes:"blue rounded",displayLenght:2000});</script> {% endif %} {% endfor %} {% endif %} -
The "override_settings" in TestCase is not work
I used "override_settings" in my test case, and I want to test DEFAULT_THROTTLE_RATES of REST_FRAMEWORK in the test case. When I tested my api, it didn't work. my settings.py: REST_FRAMEWORK = { 'DEFAULT_THROTTLE_RATES': { 'anon': '60/min', 'user': '500/hour', 'custom': '200/day', } } test api: @throttle_classes([AnonRateThrottle, UserRateThrottle]) def test_api(request): pass TestCase: @override_settings(REST_FRAMEWORK = { 'DEFAULT_THROTTLE_RATES': { 'anon': '600000/min', 'user': '5000000/hour', 'custom': '200000/day', } }) def test_api(self): from rest_framework.settings import api_settings print(api_settings.DEFAULT_THROTTLE_RATES) print(api_settings.user_settings) from rest_framework.throttling import AnonRateThrottle, api_settings as throttling_setting print(AnonRateThrottle().get_rate()) print(id(throttling_setting)) print(id(api_settings)) print(id(AnonRateThrottle().THROTTLE_RATES)) print(id(api_settings.DEFAULT_THROTTLE_RATES)) print(id(throttling_setting.DEFAULT_THROTTLE_RATES)) url = 'api' for i in range(100000): response = self.client.get(url) self.assertEqual(response.status_code, 200) I want the test case to work, but it asserts in the state of 429. I print the id of "apisetting", "DEFAULT_THROTTLE_RATES" , which is the same, but the "THROTTLE_RATES" id in the "AnonRateThrottle" instance is not the same, the value is not the same. The value is "{'anon': '60/min', 'user' : '500/hour', 'custom': '200/day',}". Please help me, I am going crazy. -
Modules calling modules is not working. Why?
I have an app in my project and I created some extra modules within it. When I can these modules within the views.py it works very well. However when I try to call them in other modules, it says that the module that I'm trying to import does not exist. This is the message: AttributeError at /user-dashboard-dividas module 'pri' has no attribute 'conversationModulesTests' The name of the app is 'pri' I have the 'conversationModulesTests' and 'conversationModulesActions'. I import both of them in 'views.py' and it works fine. But when I try to call 'conversationModulesActions' within 'conversationModulesTests' it gives me that response. My code in 'conversationModulesTests': import pri.conversationModulesActions as CMA What I am missing? -
'ContentCreateUpdateView' object has no attribute 'module_id'
I am following the tutorial on this book. Everything was fine until I got to this view here. The console return the issue below: 'ContentCreateUpdateView' object has no attribute 'module_id' when i click on the page that has the link to the view below. views.py class ContentCreateUpdateView(TemplateResponseMixin, View): """ Create and update contents from different models. """ module = None model = None obj = None template_name = 'core/manage/content/form.html' def get_model(self, model_name): if model_name in ['text', 'video', 'image', 'file']: # app label == app installed return apps.get_model(app_label='core', model_name=model_name) return None def get_form(self, model, *args, **kwargs): """ Build dynamic form. Check that the given model name is one of the four content models. """ Form = modelform_factory(model, exclude=['owner', 'order', 'created', 'updated']) return Form(*args, **kwargs) def dispatch(self, request, module_id, model_name, id=None): self.module = get_object_or_404(Module, id=module_id, course__owner=request.user) self.model = self.get_model(model_name) if id: self.obj = get_object_or_404(self.model, id=id, owner=request.user) return super(ContentCreateUpdateView, self).dispatch(request, module_id, model_name, id) def get(self, request, module_id, model_name, id=None): form = self.get_form(self.model, instance=self.obj) return self.render_to_response({'form':form, 'object':self.obj}) def post(self, request, module_id, model_name, id=None): form = self.get_form(self.model, instance=self.obj, data=request.POST, files=request.FILES) if form.is_valid(): obj = form.save(commit=False) obj.owner = request.user obj.save() if not id: # new content Content.objects.create(module=self.module, item=obj) return redirect('core:module_content_list', self.module_id) return self.render_to_response({'form':form, 'object':self.obj}) list.html <a … -
Handle Django form submit using javascript to prevent normal submission
I'm trying to prevent django following normal form submission using javascript. It looks like program never entering javascript. Here is the code {% load static %} <form method="POST" id="post-form"> {% csrf_token %} {{formPost.as_p}} <button type="submit" class="save btn btn-default">Post </button> </form> <script> $('#post-form').on('submit', function(event){ console.log("Inside Javscript!") event.preventDefault(); create_post(); }); </script> Can someone help me with this? Thanks! -
Django register user using social-auth-app-django
I'm working on implementing social auth in my django project. The requirement is letting only registered users to login. I'm using social-auth-app-django library for it. I already found how to do it using custom pipelines It’s possible to override it by defining the setting SOCIAL_AUTH_PIPELINE. For example, a pipeline that won’t create users, just accept already registered ones would look like this: The problem is I don't know how to register the users because the form in the admin is requesting extra data field to be filled. Maybe I'm missing something or the current approach is not the correct. -
Question.objects.all() isn't returning what's intended
Hi so I'm coding along to Django's official guide however I'm having a bit of trouble with my code. I'm using the Python shell and I'm running the Question.objects.all() command and it returns with the following: ', ]>'. The answer I'm looking for is ']>'. -
Django group by and aggregate with weights
I have a table like this, that I interact with using Django ORM. date car_crashes city 01.01 1 Washington 01.02 4 Washington 01.03 0 Washington 01.04 2 Washington 01.05 0 Washington 01.06 3 Washington 01.07 4 Washington 01.08 1 Washington 01.01 0 Detroit 01.02 2 Detroit 01.03 4 Detroit 01.04 2 Detroit 01.05 0 Detroit 01.06 3 Detroit 01.07 1 Detroit I want to know how many car crashes for each day happened in the entire nation, and I can do that with this: Model.values("date").annotate(car_crashes=Sum('car_crashes')).values("date", "car_crashes") Now, let's suppose I have an array like this: weights = [ { "city": "Washington", "weight": 1, }, { "city": "Detroit", "weight": 2, } ] This means that Detroit's car crashes should be multiplied by 2 before being aggregated with Washington's. My solution would be to aggregate all different weights separately, multiply by the weight either with Pandas or SQL and then do the aggregation. This would be inefficient and slow (many queries at best, using Pandas at worst). Is it possible to do it with a single ORM query? -
serving media files from a separate storage
my web works great, I can get the media files(images uploaded from others) show up and static files are served from digitalocean space. But I want the media files to be served from digital ocean as well. is it possible for one bucket to store both static and media files? My settings.py STATIC_URL = '/static/' STATIC_ROOT = os.path.join(BASE_DIR, 'static/') MEDIA_ROOT = os.path.join(BASE_DIR, 'media/') MEDIA_URL = '/media/' AWS_ACCESS_KEY_ID = '' AWS_SECRET_ACCESS_KEY = ' AWS_STORAGE_BUCKET_NAME = '' AWS_S3_ENDPOINT_URL = '' AWS_S3_OBJECT_PARAMETERS = { 'CacheControl': '', } AWS_LOCATION = '' STATICFILES_DIRS = [ os.path.join(BASE_DIR, 'static'), ] STATIC_URL = 'https://%s/%s/' % (AWS_S3_ENDPOINT_URL, AWS_LOCATION) STATICFILES_STORAGE = 'storages.backends.s3boto3.S3Boto3Storage' my directory looks like project project app media static I have /etc/nginx/sites-avaliabe/myproject server { server_name www.xx.com xx.com; location = /favicon.ico { access_log off; log_not_found off; } location /static/ { alias /home/zz/xx; } location /media/ { root /home/zz/x;x } location / { include proxy_params; proxy_pass http://unix:/home/zz/x.xsock; } with the above way static files operate the way I want so I did the same thing for the media files but with that media files won't be displayed.... -
Passing parameters to login_redirect_url
I'd like my login page to redirect a user to an instance of a page. Such an instance will be denoted as follows: www.example.com/adminpage/username This is what I have in my settings.py LOGIN_REDIRECT_URL = 'leicunnadmin' LOGOUT_REDIRECT_URL = 'login' In the urls.py: urlpatterns = [ path('', views.index, name='index'), path('leicunnadmin/<str:user>', views.leicunnAdmin, name='leicunnadmin'), ] The following is the code from the views.py script. My aim here was to check that the user is authenticated, get their username and append that to the URL. (The code) @login_required def leicunnAdmin(request, user): username = None User = get_user_model() if request.user.is_authenticated: username = request.user.username get_logged_user = User.objects.get(username=user) print('get_logged_user: '+username) return render(request, 'leicunnadmin.html') else: return render(request, 'login') Instead what I get when I log in is www.example.com/adminpage. When I type in the logged in username (www.example.com/adminpage/manuallytypedusername), it then redirects to the right page. Is there no way to automate this? -
How to execute a specific code in a defined period -Django-
I would like to know how to automatically execute a code in Django within a defined period of time. I'm building a web crawler that collects information and stores it in a JSON file and a function that reads the file and stores the file information in a SQLite database. This information is rendered and visible on my website. At the moment I have to run the crawler and the function that saves the data in a database with a click on a button, but that is very ineffective. It would be better if the database information were updated automatically, about every 6 hours (of course, only if the server is running). -
how CKEDITOR save images and is that an efficient way to use that for building blog and posts with several images?
i want to build a blog app in django and create Posts including multiple images. i don't want to create custom cms and want to use django admin cms. but i have to use CKEDITOR to do that. because i want to include images between content textarea section. i wanna to know how CKEDITOR saves images and files. does it save images into database? is this an efficient way to biuld blog? thanks for helps. from django.conf import settings from django.db import models from django.contrib.auth.models import User name = models.CharField(max_length=32) class Meta: verbose_name_plural = "Categories" def __unicode__(self): return self.name class Category(models.Model): name = models.CharField(max_length=32) class Meta: verbose_name_plural = "Categories" def __unicode__(self): return self.name class Tag(models.Model): name = models.CharField(max_length=32) def __unicode__(self): return self.name class Post(models.Model): author = models.ForeignKey(User) category = models.ForeignKey(Category) title = models.CharField(max_length=64,unique=True) symbol = models.CharField(max_length=2) tags = models.ManyToManyField(Tag) byline = models.CharField(max_length=255) background_image = models.URLField(verify_exists=True) slug = models.SlugField(max_length=128) content = models.TextField() updated_on = models.DateField(auto_now=True) created_on = models.DateField(auto_now_add=True) publish_on = models.DateField() list_display = ('title', 'category', 'tags', 'author', 'publish_on','created_on','updated_on') search_fields = ['title','byline','symbol'] list_filter = ['publish_on','created_on'] date_hierarchy = 'pub_date' ` -
Django UpdateView for Profile model that also includes a User form
Using Django 2.x, I have a Profile model, and I want to update some User fields in the Profile's UpdateView, for example, User.email I can get the email field to display, and to show the current value, but I can't figure out how to get it to update. Here's my setup: models.py: class Profile(models.Model): user = models.OneToOneField(User, on_delete=models.CASCADE) # other fields forms.py: class UserForm(forms.ModelForm): class Meta: model=User fields=('email') class ProfileForm(forms.ModelForm): class Meta: model=Profile fields=(...) views.py class ProfileUpdate(UpdateView): model=Profile form_class = ProfileForm user_form_class = UserForm def get_context_data(self, **kwargs): ... user = get_object_or_404(Profile, pk=self.kwargs.get('pk')).user context['user_form']= self.user_form_class(instance=user) Everything up to here seems to work. The user form works and the current email address appears in the form. However, this is where I get stuck, I don't know how to save that email address. Still within the ProfileUpdate, this is what I'm trying: def post(self, request, *args, **kwargs): user_form = self.user_form_class(request.POST) if user_form.is_valid(): user_form.save() # code makes it this far when submitting form. return super(ProfileUpdate, self).post(self, request, *args, **kwargs) Although the code is run, only the Profile model is updated, the User model doesn't get an updated email address. -
Blank page when using Vue in Django
I recently added VueJS to my Django project, following this guide. I'm now trying to test Vue, to see if it's running, by running this template: {% load render_bundle from webpack_loader %} <!DOCTYPE html> <html lang="en"> <head> <meta charset="utf-8"> <meta http-equiv="X-UA-Compatible" content="IE=edge"> <meta name="viewport" content="width=device-width,initial-scale=1.0"> <link rel="icon" href="<%= BASE_URL %>favicon.ico"> <title>Django Vue Integration</title> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Roboto:100,300,400,500,700,900"> <link rel="stylesheet" href="https://fonts.googleapis.com/css?family=Material+Icons"> </head> <body> <noscript> <strong>We're sorry but frontend doesn't work properly without JavaScript enabled. Please enable it to continue.</strong> </noscript> <div id="app"> <app></app> </div> {% render_bundle 'app' %} <!-- built files will be auto injected --> </body> </html> It should just render the default VueJS page. The problem is that when i run Django using manage.py runserver, i will only see a blank page on http://127.0.0.1:8000/. I'm not receveing any error in my cmd console, but in my dev tools i found this error: GET http://127.0.0.1:8000/app.js net::ERR_ABORTED 404 (Not Found) <script type="text/javascript" src="http://127.0.0.1:8000/app.js" ></script> Any advice on how to fix this issue? Thanks in advance