Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
DJango: Multiple instances of an application in a single project
I have a django application and i've needed to create multiple instances. So currently i create a virtualenv for each instance with its own django project. However this is not scaling well. What i really need is multiple instances of the application inside a single django project. Is there any sort of examples or advice for something like this? I was thinking of using multiple databases, but then each db would get all of the models for all applications in the project. -
Loading Javascript (google Charts) file to html using django
I'm struggling trying to load a google chart from a static file to an html using Django. I'm capable to display the chart if I embed the javascript file into the html file. However, when I try to load it from an external file it doesn't charge. See here below the simplified version of the html: {% extends '_base.html' %} {% load static %} {% block content %} <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.0/jquery.min.js"></script> <script type="text/javascript" src="https://www.gstatic.com/charts/loader.js"></script> <!-- JumboTron --> <div class="container"> <div class="center-block"> <div id="curve_chart"></div> </div> </div> <script type="text/javascript" id=demo> let data_from_django = {{ object_list|safe }}; CHART WORKING function drawChart() { var chart = new google.visualization.LineChart(document.getElementById('curve_chart')); chart.draw(data, options); } </script> {% endblock %} However, if I embed the javascript code in <script type="application/json" src="{% static 'js/load_data.js' %}"></script>, and having loaded static the code is never executed. I've tried to put the the javascript file also inside the header, but it's still not loading. Any insights of anything i could be missing? -
How to create UserManager for bulky custom User (AbstractBaseUser) in Django?
Here is my custom User model for my django project. class User(AbstractBaseUser, PermissionsMixin): phone = models.CharField( max_length=15, unique=True, ) sms = models.BooleanField(default=True) active = models.BooleanField(default=True) staff = models.BooleanField(default=False) admin = models.BooleanField(default=False) tutor = models.ForeignKey( 'self', on_delete=models.SET_NULL, blank=True, null=True, ) TRAINING_ONLINE = 'ON' TRAINING_DISTANCE = 'DT' TRAINING_FULLTIME = 'FT' TRAINING_NONE = 'NN' TRAINING_CHOICES = ( (TRAINING_ONLINE, 'Online'), (TRAINING_DISTANCE, 'Distance'), (TRAINING_FULLTIME, 'Fulltime'), (TRAINING_NONE, 'None'), ) training = models.CharField( max_length=2, choices=TRAINING_CHOICES, default=TRAINING_NONE, ) first_name = models.CharField( max_length=50, blank=True, null=True, ) last_name = models.CharField( max_length=50, blank=True, null=True, ) country = models.CharField( max_length=50, blank=True, ) city = models.CharField( max_length=50, blank=True, ) EFFICIENCY_VERY_LOW = '1' EFFICIENCY_LOW = '2' EFFICIENCY_MEDIUM = '3' EFFICIENCY_HIGH = '4' EFFICIENCY_VERY_HIGH = '5' EFFICIENCY_CHOICES = ( (EFFICIENCY_VERY_LOW, 'Very low'), (EFFICIENCY_LOW, 'Low'), (EFFICIENCY_MEDIUM, 'Medium'), (EFFICIENCY_HIGH, 'High'), (EFFICIENCY_VERY_HIGH, 'Very high'), ) efficiency = models.CharField( max_length=1, choices=EFFICIENCY_CHOICES, default=EFFICIENCY_MEDIUM, ) USERNAME_FIELD = 'phone' REQUIRED_FIELDS = [] def __str__(self): return self.phone def get_full_name(self): return self.first_name + ' ' + self.last_name def get_short_name(self): return self.first_name @property def is_staff(self): return self.staff @property def is_admin(self): return self.admin @property def is_active(self): return self.active I've seen some tutorials with **extra_fields, but i don't really know how to use it correctly to reduce amount of unnecessary code. And i don't know how to … -
Can any of django-redis and django-redis-cache be used on heroku?
The question is pretty straightforward, can I choose any of these two packages to handle my redis addon on heroku? In the heroku devcenter only django-redis-cache is mentioned, but I'd prefer the other one. I cannot just try it, because my current server is kind of production server and I don't want to mess things up there. -
Validate DateTimeField in forms and pass data to View in Django
Is there a way to validate DateTimeField used in models.py in the form and save the data in the view. I can access the DateTimeField from the admin and see it. In case someone wonder what i am trying to achieve: i want to send the data to google sheet. The process to google sheet is working fine but DatetimeField populate "None" because i am not able to receive DateTimeField data from the form. I did not include the code to populate the data to a google sheet. Models.py class Snippet(models.Model): name = models.CharField(max_length=30, blank=False) email = models.EmailField(max_length=10, blank=False) created = models.DateTimeField(auto_now=False, auto_now_add=True, null=True, blank=True) Forms.py class SnippetForm(forms.ModelForm): class Meta: model = Snippet fields = ['name', 'email' ] Views.py def foo(request): if request.method == 'POST': form = SnippetForm(request.POST) if form.is_valid(): form.save() return redirect('snippets:bar') form = SnippetForm() return render(request, 'snippets/foo.html', {'form':form}) Any help would be appreciated. -
Django celery periodic tasks not run automatically
I'm using celery 4.2.1 and setting celery periodic tasks using django_celery_beat in admin. Works fine locally, but at the server side all periodic tasks run only 2 or 3 times. And all tasks will run again (2-3 times), if I update at least one task in admin by hitting save. celery.py: from __future__ import absolute_import, unicode_literals import os from celery import Celery os.environ.setdefault("DJANGO_SETTINGS_MODULE", "proj.settings") app = Celery('proj') app.config_from_object('django.conf:settings', namespace='CELERY') app.autodiscover_tasks() @app.task(bind=True) def debug_task(self): print('Request: {0!r}'.format(self.request)) Celery settings in settings.py: CELERY_BROKER_URL = 'amqp://guest:guest@localhost:5672//' CELERY_BEAT_SCHEDULER = "django_celery_beat.schedulers:DatabaseScheduler" CELERY_TIMEZONE = TIME_ZONE To start celery : celery -A proj worker -l info -E To start beat: celery -A proj beat -l info How to fix that problem? Thank you for your time and help. -
Django req.POST always returns False
I am testing a shipstation webhook and I can't seem to get data from the POST request they are sending. Their webhook docs say that their POST request will contain a body that looks like this: {"resource_url":"https://ssapiX.shipstation.com/orders?storeID=123456&importBatch=1ab23c4d-12ab-1abc-a1bc-a12b12cdabcd","resource_type":"ORDER_NOTIFY"} To debug the issue, I went into the Firefox and tried to send this: And got the same result; req.method = 'POST' and req.POST = False View controller for myNgrokAddress.ngrok.io/bot/shipstation: @csrf_exempt def vc(req): print(req.META) //this works but it looks like meta-data for my browser and not from shipstation print(req.POST.get('resource_url')) //prints false print(req.POST) //prints false return HttpResponse('') When I go to localhost:4040 (the ngrok inspector) the POST body shows up, so something must be incorrectly configured on my django server. I set ALLOWED_HOSTS = ['myNgrokAdress.ngrok.io', 'localhost'] in my settings.py. Is there something else I need to do? What am I missing here? -
Django postman, Nonetype has no attribute
AttributeError at /api/customer/driver/location/ 'NoneType' object has no attribute 'driver' Request Method: GET Request URL: http://localhost:8000/api/customer/driver/location/?access_token=Akol3DrUMU0MRw6Xc2nJKYfO43i2W0 Django Version: 1.10 Exception Type: AttributeError Exception Value: 'NoneType' object has no attribute 'driver' Exception Location: C:\Users\shinl\Desktop\foodtasker\foodtaskerapp\apis.py in customer_driver_location, line 112 Line 112: location = current_order.driver.location Here is the project: (sorry it is in zip) https://github.com/iudragon/DjangoBugFiverr -
My form for uploading photos does not work. Django
When I use the form provided by django admin everything works fine. But after creating my own form, django does not write data to my model. Is something missing in my code? Models.py class Offert(models.Model): name = models.CharField(max_length=50) file = models.FileField(upload_to='app/documents/') forms.py class OffertFormCV(forms.ModelForm): class Meta: model = Offert fields = ( 'name', 'file') views.py def my_views(request): if request.method == 'POST': form = OffertFormCV(request.POST, request.FILES) if form.is_valid(): form.save() return HttpResponseRedirect(reverse('app:thank_you_page')) else: form = OffertFormCV() context = {'form': form} return render(request, 'form_application.html', context) urls.py urlpatterns = [ path('admin/', admin.site.urls), path('', include('app.urls', namespace='app')) ] + static(settings.MEDIA_URL, document_root=settings.MEDIA_ROOT) settings.py STATIC_URL = '/static/' MEDIA_URL = '/media/' MEDIA_ROOT = os.path.join(BASE_DIR, 'app/media') form_application.html <form method="post"> {% csrf_token %} {{ form|crispy }} <button type="submit" class="btn btn-primary">Send</button> </form> After sending the form, nothing happens. Any help will be appreciated. -
Template fragment cache not loading in my django project?
So my store_navbar sometimes loads sometimes is doesn't. I'm using django 1.7. I use fragment cache to load categories in my navbar. {% load cache %} {% cache CACHE_DEFAULT_TIMEOUT store_navbar store.id %} . . . {% endcache %} My cache timeout variable is: CACHE_DEFAULT_TIMEOUT = 86400 -
django deploy to Heroku : Server Error(500)
I am trying to deploy my app to heroku. Deploy was done correctly but I got Server Error(500). When I turned DEBUG true, no Sever Error occurred. So I think there is something wrong with loading staticfiles. I can't find any notable, critical error in log. I have already installed whitenoise, but it doesn't work. It there anyone who solves this problem? heroku logs 2019-02-26T17:01:26.064554+00:00 heroku[web.1]: State changed from down to starting 2019-02-26T17:01:34.347474+00:00 heroku[web.1]: Starting process with command `gunicorn project5.wsgi --log-file -` 2019-02-26T17:01:37.602081+00:00 heroku[web.1]: State changed from starting to up 2019-02-26T17:01:37.192553+00:00 app[web.1]: [2019-02-26 17:01:37 +0000] [4] [INFO] Starting gunicorn 19.9.0 2019-02-26T17:01:37.199091+00:00 app[web.1]: [2019-02-26 17:01:37 +0000] [4] [INFO] Listening at: http://0.0.0.0:35760 (4) 2019-02-26T17:01:37.199669+00:00 app[web.1]: [2019-02-26 17:01:37 +0000] [4] [INFO] Using worker: sync 2019-02-26T17:01:37.219788+00:00 app[web.1]: [2019-02-26 17:01:37 +0000] [10] [INFO] Booting worker with pid: 10 2019-02-26T17:01:37.317796+00:00 app[web.1]: [2019-02-26 17:01:37 +0000] [11] [INFO] Booting worker with pid: 11 2019-02-26T17:01:39.269757+00:00 heroku[router]: at=info method=GET path="/" host=shunka-blog.herokuapp.com request_id=a5a7c921-c0d2-4bc2-8831-371da12d3945 fwd="111.239.176.72" dyno=web.1 connect=0ms service=522ms status=500 bytes=234 protocol=https 2019-02-26T17:01:39.271879+00:00 app[web.1]: 10.99.220.185 - - [27/Feb/2019:02:01:39 +0900] "GET / HTTP/1.1" 500 27 "-" "Mozilla/5.0 (Macintosh; Intel Mac OS X 10_14_1) AppleWebKit/537.36 (KHTML, like Gecko) Chrome/72.0.3626.109 Safari/537.36" settings.py import os import dj_database_url import django_heroku BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = False SECRET_KEY = … -
Keycloak single logout with Django
I created a Django application that integrates with Keycloak's OpenID authentication. So far the only pressing issue I've encounted is the logout function. When I log out via the Django app, I could implement it such that it logs the user out of the Keycloak as well. However, I could not find a way to perform the reverse. Logging out via Keycloak account management interface does not log the user out from the Django app. This means that the user can still remain authenticated on the Django app even though he is already logged out of Keycloak, which appears to be a security concern. From what I understood from most other similar StackOverflow post, Keycloak supposedly has a way to call back to web application to logout the user, but however it is not very clearly documented on how to implement it: https://www.keycloak.org/docs/latest/securing_apps/index.html#_applicationclustering Does anyone have any idea how this can be implemented on django? I used Django 2.1 + mozilla-django-oidc package. -
Issues with logout/login views
I am not able to log out of my account in my django app. Or if i am, i am able to go to a view where login is required. In other words, I am able to login correctly, but when i try to add logout functionality, it seems to do nothing, or the LoginRequiredMixin is not working correctly views.py class LoginView(TemplateView): template_name = 'APP/login.html' def post(self, request): email = password = "" state = "" if request.POST: email = request.POST.get('email') password = request.POST.get('password') print(email, password) user = authenticate(username=request.POST.get('email'), password=request.POST.get('password')) if user is not None: login(request, user) return redirect('/login/index/') else: state = "Inactive account" # logging.StreamHandler return render(request, self.template_name, {'state': state, 'email': email}) class LogOutView(TemplateView): template_name = 'APP/logout.html' def logout(self, request): logout(request) return redirect('/login') class IndexView(LoginRequiredMixin,TemplateView): login_url = '/login/' template_name = 'APP/index.html' I currently have these in my urls.py app_name = 'app' urlpatterns = [ path('logout/', views.LogOutView.as_view(), name='logout'), path('login/', views.LoginView.as_view(), name='login'), path('login/index/', views.IndexView.as_view(), name='index'), settings.py LOGIN_URL = '/login' LOGOUT_REDIRECT_URL = '/logout' and my logout button is on my index.html page like so: <a href="logout/"> <button>logout</button> </a> I am not sure how to implement LoginRequiredMixin for it to work, and clicking the logout button doesn't seem to log out the user. -
Django - How to display GeoJSON on a Mapbox map?
Using Django (v1.11) and Mapbox, I am trying to display a map with some GeoJSON content which I load from a local file. For example purposes I am using this sample.json file. My idea was to load the GeoJSON file into a JSON object, and pass that to a template (in this case map.html). Additionally, I attempted to convert the JSON object into a string, pass that string, and then re-create a new JSON object with Javascript (shown below). Neither method has worked for me. However, if I simply copy-paste the contents of sample.json as a Javascript variable, everything works and the GeoJSON is displayed correctly. So my question is, how can I load the GeoJSON from a file, pass that to an HTML template, and then display the contents on a Mapbox map? views.py def get(self, request, *args, **kwargs): with open('/somepath/sample.json') as f: data = json.load(f) data = json.dumps(data) return render(request, 'map.html', {'data':data}) map.html map.on('load', function () { // THIS DOES NOT WORK var json_data = JSON.parse({{ data }}) map.addLayer({ 'id': 'layerid', 'type': 'fill', 'source': { 'type': 'geojson', 'data': json_data } }); }); map.html map.on('load', function () { // THIS WORKS var json_data = { "type": "FeatureCollection", "features": [ … -
AttributeError: module 'django.db.models' has no attribute 'model'
i am making simple model in videorequest app from django.db import models from django.utils import timezone # Create your models here. class video(models.Model): videotitle = models.CharField(max_length=40) videodesc = models.TextField() dateadded = models.DateTimeField(default=timezone.now) def __str__(self): return 'Name: {},Id: {}'.format(self.videotitle,self.id) what's wrong in my code -
Send a token to another app and then validate
There are two separate django projects, So I want both are generating tokens with the same user_id, secret key and same HS256 algorithm and then once Project B sends request along with token, the token should be decrypted and the required response should be send back from Project A. How do I go forward and implement it. Should i use JWT? -
Logging into a Django Website without checking users against the Django Admin Site
For my Project i currently check the users (username & password) against an Active Directory so once i check that the user credentials are correct but im asking to see if is possible to log the user in to the system to see (@login_required) views for example Is this something is possible as per my requirements I am not allowed to store passwords in the Django Admin page Thanks in Advance -
Django any installed app not finding static files
latest versions of Django and Python, MacOS, PyCharm I am having trouble installing any app. Everytime I try, it does not find the resources. Currently, I'm attempting to install uncaught in my Django app. My app's name is RealEstate. Deployment Directory for static: project_name/app_name/static/ Directory I use to copy new or revised files to Deployment Directory with collectstatic: project_name/app_name/static_changes/ inside static, I have an admin folder with different subfolders: static/admin/css, static/admin/fonts, static/admin/img, static/admin/js, static/admin/node_modules settings.py: BASE_DIR = os.path.dirname(os.path.dirname(os.path.abspath(__file__))) DEBUG = TRUE STATIC_ROOT = os.path.join(BASE_DIR, 'RealEstate/static') STATIC_URL = '/static/' STATICFILES_DIRS = [ os.path.join(BASE_DIR, "RealEstate/static_changes/"), ] STATICFILES_FINDERS = [ 'django.contrib.staticfiles.finders.FileSystemFinder', 'django.contrib.staticfiles.finders.AppDirectoriesFinder', ] I have run the install for uncaught, which created a package-lock.json file and a node_modules folder with the uncaught resources, both put into the root of my project: $ npm install --save uncaught Since I use static_changes to copy any new or modified resources into the deployment directory static, I have copied the node_modules folder put into the project root to my app_name/static_changes/admin folder and run collectstatic python3.7 manage.py collectstatic It copies the files to app_name/static. But when I open the browser, the files are never found, and I get this message in the Run Console: Not Found: /admin/node_modules/uncaught/lib/index.js [26/Feb/2019 … -
How do you only run a validator on a form field at the end after no validation errors have been raised?
I would like to only run a specific checksum validation if things like required, min and max validations as well as a custom is_digit() validation is run. The reason is I do not want to show the error message for the checksum validation if some other validation is failing. I've tried: id_number = ZaIdField( required=False, max_length=13, min_length=13, validators=[validate_numeric, ] ) then I have the checksum validator after others run in super(): class ZaIdField(forms.CharField): ''' Field for validating ZA Id Numbers ''' def __init__(self, *args, **kwargs): super().__init__(*args, **kwargs) def validate(self, value): """Check if id is valid""" # Use the parent's handling of required fields, etc. super().validate(value) validate_sa_id(value) -
Django - Model choices from another model's choices that are already selected
So I have one model AdminChoices that has a ManytoMany field which selects choices from another model choices. I want another model that has a ManytoMany field who's choices are only the selected choices of AdminChoices. Here is the current code for the models. class choices(models.Model): choices = models.CharField(max_length=300) def __str__(self): return self.choices class AdminChoices(models.Model): choice1 = models.ManytoManyFields(choices, related_name="adminchoices_choice1_related") choice2 = models.ManytoManyFields(choices, related_name="adminchoices_choice2_related") etc class UserChoices(models.Model): choice1 = "choice that can only be chosen from selected AdminChoices choice1" choice2 = "AdminChoices choice2" etc I'm making an application where users can create a hardware configuration. A field in this model represents a slot and only one choice can be selected for the slot. These choices would have to be approved by an admin first to ensure that the slot can accept that choice. This is where the AdminChoices model comes in, where an admin would have access to a global admin configuration that approves choices for a slot, which would then allow a user to select one of the approved choices in their personal configuration. I'm not sure if I'm taking the right approach, how would I go about making this model? -
Factorize Django function
I have some functions which work very fine, but it's a bit ugly and could be factorized to my mind : def get_topic_slug(obj): if type(obj) == Thread: topic_slug = obj.topic.slug return topic_slug def get_topic_title(obj): if type(obj) == Thread: topic_title = obj.topic.title return topic_title def get_topic_pk(obj): if type(obj) == Thread: topic_pk = obj.topic.pk return topic_pk As you can see, each function lets to get a specific attribute from my Thread object. Attributes are : id, title, slug ... I would like to write something like this : def get_topic(obj, attributes): if type(obj) == Thread: topic_attributes = obj.topic.attributes return topic_attributes But it doesn't work because I get : topic_slug = get_topic(thread, param=slug) name 'slug' is not defined How I could factorize my function in order to pass obj and specific attribute like this : topic_slug = get_topic(thread, slug) Thank you ! -
heroku rejects django app push with M2Crypto error
Heroku rejected django app push having python version: 3.6.22 with following error: remote: SWIG/_m2crypto_wrap.c:31145:5: remote: (PyObject*) 0, /* ht_name */ remote: { remote: SWIG/_m2crypto_wrap.c:31147:1: remote: }; remote: } remote: error: command 'gcc' failed with exit status 1 remote: remote: ---------------------------------------- remote: Command "/app/.heroku/python/bin/python -u -c "import setuptools, tokenize;__file__='/tmp/pip-build-pbjs22ys/M2Crypto/setup.py';f=getattr(tokenize, 'open', open)(__file__);code=f.read().replace('\r\n', '\n');f.close();exec(compile(code, __file__, 'exec'))" install --record /tmp/pip-yovrfdk2-record/install-record.txt --single-version-externally-managed --compile" failed with error code 1 in /tmp/pip-build-pbjs22ys/M2Crypto/ remote: ! Push rejected, failed to compile Python app. remote: remote: ! Push failed Django-1.9.4 python-3.6.2 M2Crypto-0.31.0 The whole setup works on local, not sure why it is failing on heroku push. I have created runtime.txt with python-3.6.2 -
I'm having problem making an mcq quiz in django
This is my html page conduct.html Here i get an error saying couldnt parse remainder. I want to use the enumerate function here but it shows an error again Is there a way to solve this problem. {% extends 'TakeTestApp/base.html' %} {% load crispy_forms_tags %} {% block content %} <h3 class="display-6">Test has begun!</h3><br> <div class="content-section"> <form method="POST"> {% csrf_token %} {% for q, opts in quesBank.items %} <ol>{{ q }}</ol> {% for op in opts %} {{ form.options[forloop.counter] }}{{ op }}<br> {% endfor %} {% endfor %} <button class="btn btn-outline-info" type="submit">Submit</button> </form> </div> {% endblock content%} and my forms.py is from django import forms class TestFORM(forms.Form): CHOICES = (('a', 'A'), ('b', 'B'), ('c', 'C'), ('d', 'D')) options = forms.MultipleChoiceField(label=False, choices=CHOICES, widget=forms.RadioSelect()) and my views.py is like this from django.shortcuts import render, redirect from Test.models import TestM from .forms import TestFORM def MakeTest(request): file1 = open('media/Test/TestName/ques.txt', 'r') lines = file1.readlines() file1.close() ques = [] options = [] ans = [] for line in lines: if "Q:" in line: ques.append(line) if "opt" in line: options.append(line.replace('*', '')) if "*" in line: ans.append(line) i = 0 quesBank = {} for qu in ques: quesBank[qu] = [options[x] for x in range(i, i + 4)] i … -
Including captcha in a django form
I'm trying to add Captcha to my Django form. I tried three different libraries but none of them worked for me and i don't know what i'm doing wrong. Here is my last try: I used this library. My forms.py looks like this: class NewUserForm(UserCreationForm): email = forms.EmailField(required=True) captcha = NoReCaptchaField() class Meta: model = User fields = ("username", "email", "password1", "password2") def save(self, commit=True): user = super(NewUserForm, self).save(commit=False) user.email = self.cleaned_data['email'] if commit: user.save() return user This is urls.py: path("login/", views.login_request, name="login"). This is the frontend: login.html: <script src="https://www.google.com/recaptcha/api.js" async defer></script> I updated my settings.py file, so the error must not be there. -
Django doesn't update html template after `model.save()`
I have a Django application with DRF. In some moment I do an Ajax call that change a simple field of the model: # Delete media def delete(self, request, pk, format=None): media = get_object_or_404(Media, pk=pk) media.deleted = True media.save() return Response(status=status.HTTP_200_OK) After that the Ajax call just make a location.reload(); but the reloaded page still contain the "deleted" model. On the database the deleted field is True, and on my template I make this: {% for media in issue.getMedia %} {% if not media.deleted %} {% include 'core2/include/media.html' %} {% endif %} {% endfor %} So if I reload the python app it not show the media.deleted objects.