Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
How to delete arguments from url
I need to generate keys by clicking button and to show generated ones. Here my view: @user_passes_test(lambda u: u.is_superuser) def get_key(request): if(request.GET.get('create_new_key')): for_whom = request.GET.get('for_whom') create_key(for_whom) created_keys = RegistrationKey.objects.all() return render(request, 'registration/get_key.html', { 'created_keys':created_keys, }) And template: <!DOCTYPE html> <html> {% include "core/header.html" %} <body> <form action="#" method="get"> <input type="text" name="for_whom"/> <input type="submit" class="btn" value="Create" name="create_new_key"> </form> <ul> {% for created_key in created_keys %} <p>{{created_key.key}}</p> <p>{{created_key.for_whom}}</p> {% endfor %} </ul> </body> {% include "core/footer.html" %} </html> Now when I'm clicking the button on page http://127.0.0.1:8000/get_registration_key/ the key is generating but now I'm at http://127.0.0.1:8000/get_registration_key/?for_whom=&create_new_key=Create#, so refreshing this page would generate more keys. I really need to cut this arguments from url but don't understand how. -
ng-show not updating with $timeout function
I'm trying to write my own photo slider so that the image and text I have on my Django homepage will fade from one to the next (and then repeat). I created a timeout function to loop a $scope.current_slide variable from 1-3, and back to 1 at a set interval. I'm using ng-show on each so that when the $scope.current_slide variable is equal to the number of slide, each picture will appear. The problem I'm having: The images aren't cycling through when I use the timeout function. However! I know in theory my code should work because when I make a button, and use ng-click to allow the button to increment a an angular 'click' variable (1, 2, 3, etc.) the correct pictures show up. The pictures just don't scroll correctly with the timeout function. I added $scope.$apply() thinking this would fix it, but nothing changed. I have the JS file within my home.html page so that it can dynamically pull the total number of slides from Django. home.html <script> var myApp = angular.module('myApp', ['ngRoute', 'ui.bootstrap', 'ngAnimate']); myApp.controller('myController', ['$scope', '$timeout', function($scope, $timeout) { $scope.timeInMs = 0; console.log("We are here in CTRL Controller"); $scope.current_slide = 1; // FUNCTION EXECUTES EVERY FEW … -
django different domain url routing using {% url %} and app urls
How would I setup django url routing to reroute to a specific domain for each app's urls? Meaning: Let's say I have an app "Jobs" and I want to route to "jobs/list" to view a lsit of all jobs which is on domain: "(name)jobs.io" whereas my main app is on (name).io. These links are in the navbar. I've ported django-multiple-domains to Django 1.11 and have the setting, used by the middleware, setup to use each apps urls based upon the domain but this doesn't seem to take care of using the {% url %} tag. -
django rest 400 responce when putting date field
I am putting a datetime value to my drf backend. This is my code: models.py class MyModel(models.Model): .... date = models.DateField(blank=true, null=true) ..... serializers.py class MyModelSerializer(ModelSerializer): class Meta: model = MyModel fields = '__all__' views.py class UpdateNRetrieve(RetrieveUpdateAPIView): queryset = MyModel.objects.all() serializer_class = MyModelSerializer lookup_field = 'pk' On my settings.py I have this: REST_FRAMEWORK = [ ..... 'DATE_FORMAT': '%d/%m/%Y', 'DATE_INPUT_FORMATS': '%d/%m/%Y', ..... ] And also this: LANGUAGE_CODE = 'it-IT' TIME_ZONE = 'Europe/Rome' USE_I18N = True USE_L10N = True USE_TZ = True When i make a PUT request from my front-end I am getting a 400 error (bad request) whit this value: date:"04/12/1984" I always get this response: Date has wrong format. Use one of these formats instead: %, d, /, %, m, /, %, Y." I can't realize where is my error! -
Django how to get record id from ModelForm
I've been banging my head on this for weeks but I am determined to get ModelForm to work! When you process a POST with data received from a ModelForm, I understand that you need to get the original record from the database and then create a new form using that original record as the 'instance'. This is documented in the Django docs as follows: >>> from myapp.models import Article >>> from myapp.forms import ArticleForm # Create a form instance from POST data. >>> f = ArticleForm(request.POST) # Save a new Article object from the form's data. >>> new_article = f.save() # Create a form to edit an existing Article, but use # POST data to populate the form. >>> a = Article.objects.get(pk=1) >>> f = ArticleForm(request.POST, instance=a) >>> f.save() In this example they know that the pk of the record they are looking for is 1. BUT, how do you know the pk if you're reading data from request.POST, assuming that the POST is based on data you previously wrote to the screen? ModelForm doesn't store the pk. So, from where do you pick this up? Without it, how do you know which record to pull out of the DB … -
formatting data from a DateField using ModelForm - Django 1.11
I'm creating an edit view that uses ModelForm, and I'd like the form's date field to appear in the following format: "%d/%m/%Y". However, regardless of what I do, when the edit page is called, the date is displayed in the format "%m-%d-%Y". models.py class Pessoa(models.Model): nome = models.CharField(max_length=255, null=False) sobrenome = models.CharField(max_length=255, null=False) cpf = models.CharField(max_length=14) data_nascimento = models.DateField() rg = models.CharField(max_length=15, null=False) responsavel = models.ForeignKey('Pessoa', related_name='dependentes', blank=True, null=True) foto = models.ImageField(upload_to='pessoas') usuario_alteracao = models.CharField(max_length=255, blank=True, null=True) data_criacao = models.DateTimeField(auto_now_add=True) data_alteracao = models.DateTimeField(auto_now=True) settings.py (DATETIME_INPUT_FORMATS and DATE_INPUT_FORMATS) DATE_INPUT_FORMATS = ['%d/%m/%Y'] DATETIME_INPUT_FORMATS = ['%d/%m/%Y'] pessoas_forms.py class PessoaForm(ModelForm): data_nascimento = DateField( input_formats=settings.DATE_INPUT_FORMATS, widget=DateInput(attrs={'class': "input", 'placeholder': "Ex.: dd/mm/aaaa", "OnKeyPress":"mask('##/##/####', this)"})) class Meta: model = Pessoa fields = ['nome', 'sobrenome', 'cpf', 'data_nascimento', 'rg', 'foto'] exclude = ['usuario', 'usuario_alteracao', 'data_criacao', 'data_alteracao', 'responsavel'] widgets = { 'nome': TextInput(attrs={'class': "input"}), 'sobrenome': TextInput(attrs={'class': "input"}), 'cpf': TextInput(attrs={'class': "input", 'placeholder': "Ex.: 000.000.000-00", "OnKeyPress":"mask('###.###.###-##', this)"}), 'rg': TextInput(attrs={'class': "input"}), } views.py def get(self, request, id): try: pessoa = Pessoa.objects.get(id=id) except ObjectDoesNotExist: messages.warning(request, 'Not Found.') return redirect('pessoas') pessoa_form = PessoaForm(instance=pessoa) context = { 'pessoa_form': pessoa_form, 'id': pessoa.id } return render(request, 'sagasystem/configuracoes/pessoas/editar_pessoa.html', context) -
ImportError at /admin/ No module named 'honeywordHasher.hashers.honeywordgen'; 'honeywordHasher.hashers' is not a package
Hye . i try to make my own customize password hasher and i still cannot manage to import it because of this error . how to fix this error ? complete traceback: During handling of the above exception (module 'honeywordHasher.hashers' has no attribute '__path__'), another exception occurred: File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\exception.py" in inner 41. response = get_response(request) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\base.py" in _get_response 217. response = self.process_exception_by_middleware(e, request) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\core\handlers\base.py" in _get_response 215. response = response.render() File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\response.py" in render 107. self.content = self.rendered_content File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\response.py" in rendered_content 84. content = template.render(context, self._request) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\backends\django.py" in render 66. return self.template.render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in render 207. return self._render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in _render 199. return self.nodelist.render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in render 990. bit = node.render_annotated(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in render_annotated 957. return self.render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\loader_tags.py" in render 177. return compiled_parent._render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in _render 199. return self.nodelist.render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in render 990. bit = node.render_annotated(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in render_annotated 957. return self.render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\loader_tags.py" in render 177. return compiled_parent._render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in _render 199. return self.nodelist.render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in render 990. bit = node.render_annotated(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in render_annotated 957. return self.render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\defaulttags.py" in render 322. return nodelist.render(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" in render 990. bit = node.render_annotated(context) File "C:\Users\Adila\Envs\tryFOUR\lib\site-packages\django\template\base.py" … -
multiple forms in Django createView class
I'd like to create a formView(based on Django build-in CreateView class) to allow creating new user records, which are from two different models. Both models sounds like one is user model and another is user profile model. I wish one form with one submit button to approach it, but I found only one form_class could be assigned in one createView class in Django. So I wonder is that possible to use CreateView to approach it? if not, any solution recommended? Appreciated if any assistance from you. -
Django - licensing application (connecting an app with particular domain)
I would like to sell my app. The only problem is to protect the source code. I would like to allow to use it with only one particular domain (one license = one domain). Is it possible to prevent reuse code on another domains? By now every user can change allowed host by simply editing setting.py file. I don't have any idea how can I prevent that. Is there any third party app for licensing functionality? -
Python/Django vs JS/HTML5 to build a CASAbrowser-like website?
I want to build a web interface which looks like this browser for a scientific application (click on the play button and move the position scroller to see the demo). Here is a screenshot of the browser : I was wondering which language/framework would be the best suited for this task ? A python/Django combination or JS/HTML5 ? Besides the GUI part (buttons, scrolls, ..) I want the freedom to add multimedia components (a video, a speech signal, ..) and scatter plots. -
Locally test different domain url configuration in Django
As the title says how do i test different domain not subdomain url routing? I'm using a middleware as follows: class MultipleDomainMiddleware(MiddlewareMixin): def process_request(self, request): url_config = getattr(settings, 'MULTIURL_CONFIG', None) if url_config is not None: host = request.get_host() if host in url_config: request.urlconf = url_config[host] Where the url_config[host] value points to app.urls in the settings MULTIURL_CONFIG dictionary. Each app is on a different domain. Now, when locally testing I'm on localhost:8000/ so how can I test this so I can test my routing schema as well as shared data across the domains locally? -
Python/Django: How to show both main model and 'foreign-key model' together in HTML
Good Day SO, I am a beginner in Django and python, just started learning two days ago. Currently, I am trying to do my filtering of data in views.py and creating a context to be shown in my main page that contains both the initial model and the 'foreign-key' model. However, I am having trouble finding help online, even though this is a simple question.. Here goes.. Models involved: class Plan(models.Model): plan_ID = models.CharField( primary_key=True, max_length=8, validators=[RegexValidator(regex='^\w{8}$', message='Length has to be 8', code='nomatch')] ) plan_crisisID = models.ForeignKey(Crisis, on_delete=models.CASCADE) plan_status = models.CharField(max_length=50) class Crisis(models.Model): crisis_ID = models.CharField( primary_key=True, max_length=4, validators=[RegexValidator(regex='^\w{4}$', message='Length has to be 4', code='nomatch')] ) crisis_name = models.CharField(max_length=50) Views.py for HTML: def home(request): template = loader.get_template('pmoapp/home.html') crisisList = Crisis.objects.filter(crisis_status='Ongoing').order_by('-crisis_ID') context = { 'crisisList': crisisList, #'planList': planList } return HttpResponse(template.render(context, request)) And finally, my HTML page: <tbody> {% if crisisList %} {% for crisis in crisisList %} <tr> <td>{{ crisis.crisis_ID }}</td> <td><a href="/report/{{ crisis.crisis_ID}}">{{ crisis.crisis_name }}</a></td> <td>{{ crisis.crisis_dateTime }}</td> <td>planid</td> <td>planstatus</td> </tr> {% endfor %} {% else %} <p>No crisis available.</p> {% endif %} </tbody> I have several things that I do not know how to do here.. so sorry and bear with me.. I have a many-to-one relationship between … -
Inheriting a Django crispy form in all pages of my website
I am building my website with Django. I have built a newsletter app for my website where users can join the newsletter group by putting their email address. I am sending the form as a context variable to "base.html". I have another html file called "carousel.html" which is my homepage. This html file contains the tag {{ % include "base.html" % }} However, in my "urls.py", when I use "carousel.html" as a templateview, urlpatterns = [ url(r'^admin/', admin.site.urls), url(r'^$', TemplateView.as_view(template_name = 'carousel.html'))] I don't see the form. Basically, I am unable to inherit the form in the right way. Here is what the actual form should look like The right form And this is what it looks like now How the form looks now -
Oscar Partner Model to OnetoOne
Trying to update theOnetoOneField so that I can have multiple partners with their own dashboard. I'm not sure if I have my paths right too. I keep getting Permission denied! for an user that I manually selected to be a partner to test if it works. where im trying to update partner models.py from oscar.apps.partner.abstract_models import AbstractPartner from django.contrib.auth.models import User from django.utils.translation import ugettext_lazy as _ from oscar.apps.partner.models import * class Partner(AbstractPartner): user = models.OneToOneField( User, related_name="partner", blank=True, verbose_name=_("Users")) my path App |--app (main) |--oscarapp (oscar app) |----partner |------models.py |----oscarapp |------__init__.py |------settings.py -
django urls throwing error in browser
i switched from the general url format to creating a urls.py file for each app so after moving the urls I get an error Reverse for 'trending' not found. 'trending' is not a valid view function or pattern name urls.py from django.conf.urls import url from . import views from django.contrib import admin app_name = 'posts' urlpatterns = [ url(r'^$', views.index, name='index'), url(r'^trending/$', views.trending, name='trending'), url(r'^ranking/$', views.post_ranking, name='rank'), url(r'^create/$', views.create, name='create'), ] general urls.py url(r'^', include('posts.urls' , namespace="posts")), template <li><a href="{% url 'trending' %}"><i class="fa fa-hashtag"><small class="notification-badge">5</small></i> Trending</a></li> <li><a href="{% url 'index' %}"><i class="fa fa-level-down"></i> Recent</a></li> additional codes would be added on request. -
Django library for rest auth Google, Instagram, VK, ant others?
I need SOCIAL REST AUTH in my Django project for SPA, and iOS app. All library I've found have only Facebook and Twitter REST auth. Is there any library, which has all what I need for another famous social: Google, Instagram, VK... ? -
Use the Django Rest Framework with tables not defined in your models.py
I finished a tutorial with the Django Rest Framework and I am super excited with this approach of developing, meaning to have separated the front end with the back end and have those two communicate with a REST API. So at this point I am trying to wrap my head around the DRF idea and here I am stuck with the following question: With the Django Rest API you can actually fetch data (e.g. in JSON format) from your django models. Later in your frontend, you can get these data via an AJAX request (using jquery or react or angular) and then you display them.. But all these data they come from the tables which are also defined as Django models. What if I need to get the data from a database (tables) which is not defined in the models.py? Does the DRF works in these cases? What approach would I follow? -
how to format date dd-MMM-yyy in django?
i have the following error i have tried everything but not still giving. i tried this 'start=datetime.strptime(request.GET.get('start'),'%d.%B.%Y')' THis is the error i received time data '1 janvier 2017' does not match format '%d.%m.%y' -
uwsgi for django and nginx not running but active. Using upstart on ubuntu 16
I have been working on deploying my django app for 3 days now with no success. uwsgi is not running. On start of server if i type upstart command: service uwsgi status here is what i get shown even if i stop and start it. ● uwsgi.service - LSB: Start/stop uWSGI server instance(s) Loaded: loaded (/etc/init.d/uwsgi; generated; vendor preset: enabled) Active: active (exited) since Sat 2017-10-14 16:36:54 UTC; 10min ago Docs: man:systemd-sysv-generator(8) CGroup: /system.slice/uwsgi.service Oct 14 16:36:52 mailhub systemd[1]: Starting LSB: Start/stop uWSGI server instance(s)... Oct 14 16:36:53 mailhub uwsgi[1729]: * Starting app server(s) uwsgi Oct 14 16:36:54 mailhub uwsgi[1729]: ...done. Oct 14 16:36:54 mailhub systemd[1]: Started LSB: Start/stop uWSGI server instance(s). Here is my upstart config or init description "uWSGI application server in Emperor mode" start on runlevel [2345] stop on runlevel [!2345] setuid user setgid www-data chdir /home/user/mailhub exec /usr/local/bin/uwsgi --emperor /etc/uwsgi/sites # ALSO: tried uwsgi from virtualenv exec /home/user/venv/bin/uwsgi --emperor /etc/uwsgi/sites -- same exit Here is the uwsgi file ini file aka mailhub.ini [uwsgi] chdir = /home/user/mailhub/ module = mailhub.wsgi:application virtualenv = /home/user/venv/ socket = /home/user/mailhub//mailhub.sock master = true processes = 5 enable-threads = true thread-stacksize = 5 plugins = python [enter link description here][1] chmod-socket = … -
Do Django loggers have a universal parent?
I want to keep the logger = logging.getLogger(__name__) convention in individual Python files, but have a single logger that captures them all. Is that possible, and what should the logger's name be? (I do not want to switch everything to logger = logging.getLogger('django')) -
Cant retrieve data from azure sql server DB-Django Python
I have a web-app developed with Python 2.7 and Django. My back end database is Azure sql server , i am using both pyodbc(4.0.17) and django-pyodbc-azure(1.11.0.0) I am using the following settings in seetings.py DATABASES = { 'default': { 'ENGINE': 'sql_server.pyodbc', 'NAME': 'XXXX', 'HOST' : 'XXXX.database.windows.net', 'AUTOCOMMIT' : True , 'USER' : 'XXXX', 'PASSWORD' : 'XXXX', 'OPTIONS': { 'driver': "ODBC Driver 13 for SQL Server", } } While opening a connection with the database i am facing a very strange situation , the queries are running on the database but when i am trying to retrieve the data i am getting either none(fetchone) or empty list(fetchall) I know that queries are running on the database because i can see that the query ran on the database level and in addition when i am calling store procedures i can see that they are running , does anyone has any ideas why it is not working and i cant get the data back from the database? with connections['default'].cursor() as cursor: cursor.execute("select Description_ from data_input_work") cursor.commit() records=cursor.fetchall() Thanks in advance Nir -
Which Django/Python handler class will pass logs to the UWSGI logger?
I am running my Django site as a vassal of UWSGI emperor. I have created /etc/uwsgi-emperor/vassals/mysite.ini as follows: [uwsgi] socket = /var/opt/mysite/uwsgi.sock chmod-socket = 775 chdir = /opt/mysite master = true virtualenv = /opt/mysite_virtualenv env = DJANGO_SETTINGS_MODULE=mysite.settings module = mysite.wsgi:application uid = www-data gid = www-data processes = 1 threads = 1 plugins = python3,logfile logger = file:/var/log/uwsgi/app/mysite.log vacuum = true And defined LOGGING in settings.py as follows: LOGGING = { 'version': 1, 'disable_existing_loggers': False, 'handlers': { 'console': { 'level': 'DEBUG', 'filters': None, 'class': 'logging.StreamHandler', }, }, 'loggers': { 'django': { 'handlers': ['console'], 'level': 'DEBUG', }, }, } But Django logs are not appearing in file:/var/log/uwsgi/app/mysite.log. Which handler class will pass the logs on to UWSGI? -
Run cron based on Django Datefield/Datetimefield?
I hope you can help me, I was wondering if there's any way to run a cron based on a stored value in Datefield or Datetimefield in django? Maybe with the use of a module? I was thinking to store the time in increments of 15 minutes, and then run my cron every day 15 minutes, and then check if the time matches. e.g. Store if my object the datetimefield with 10/09/2017 (dd/mm/yyyy) and 13:00 or 13:15 or 13:30 .... Then every 15 minutes my cron runs a django management command and with it make a filter to get all the objects with a matching datetime and if exist(using a datetime.now maybe to get the cron date and time when it's executed), and then perform another action. Maybe this I'm taking the wrong course to solve this, I hope you can help me. -
How to do an "OneToMany(Field)" relationship in Django?
I know that there is no OneToManyField. But in this situation I need one. I want to save many Image objects to one Advertisement object. How can I achieve this ? I have the following situation: models.py class Image(models.Model): id = models.AutoField(primary_key=True) image = models.ImageField(upload_to="", default="", null=True) def __str__(self): return self.image.url class Advertisement(models.Model): id = models.AutoField(primary_key=True) user = models.ForeignKey(User, on_delete=models.CASCADE, related_name='user', null=True) category = models.ForeignKey(Category, related_name='category', null=True) title = models.CharField(max_length=100, null=True) description = models.CharField(max_length=5000, null=True) date = models.DateTimeField(auto_now_add=True, null=True) def __str__(self): return self.description -
Web framework for facebook chatbot
I'm improving my simple chatbot on FB with new features. I want to use the templates - buttons etc to confirm requests/choose options. It means for each button I send to the user, I need to somehow keep its ID and wait for the response. I'm currently using Django framework, but I'm wondering if there is anything more suitable. I looked up Twisted and Tornado, but not sure if its exactly what I want? My plan is to keep the button IDs in SQLite/Mongo and when callback comes, check which button it is and respond accordingly. But then isn't it too slow? Or would get slow? PS: I know it's bordering on relevancy to SO as an opinion-based question, I'd just like to verify what sort of principles I'm looking for, because that's not my strongest suit. Many thanks