Django community: RSS
This page, updated regularly, aggregates Django Q&A from the Django community.
-
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 -
Get data from dynamically added elements and pass to Django request.POST
I have a restaurant_form which allows user to input menu items. Each menu item represent a table row which is added dynamically. Each table row has input for: menu item, price, halal(Boolean), and notes. Here is a sample entry. data-ids and names of input elements are incremented. <tbody class="menu-entry "> <tr id='menu0' data-id="0" class="hidden"> <td data-name="name" class="name"> <input type="text" name='name0' placeholder='Menu Item' class="form-control"/> </td> <td data-name="price"> <input type="text" name='price0' placeholder='0.00' class="form-control"/> </td> <td data-name="halal"> <input type="checkbox" name="veg0" value="halal" class="form-control"> </td> <td data-name="notes"> <textarea name="notes0" placeholder="Contains soy." class="form-control"></textarea> </td> <td data-name="del"> <button name="del0" class='btn btn-danger glyphicon glyphicon-remove row-remove'></button> </td> </tr> </tbody> What is the best way to retrieve data from the table? I have tried this: $('#restaurant_form').submit(function () { $('.menu-entry').each(function() { $(this).find('td').each(function(){ $(this).find("input").each(function() { alert(this.value) }); $(this).find("textarea").each(function() { alert(this.value) }); }) }) }) The alert() shows the correct values however I am wondering if there is a better way to do this? Also, after retrieving the values, how can I pass it to the view with a POST request? I would like to save the values to model RestaurantMenu with columns name, price, halal and notes. Thank you. -
How to correct logic in comments View?
I build comments functional for post but has bug. When someone comment post, another user see correct comment body, but incorrect image and def p(request, pk): user = request.user #user_that_text_comment = User.objects.filter(pk=pk) topic = get_object_or_404(Topic, pk=pk) post = get_object_or_404(Post, pk=pk) comment = Comments.objects.filter(pk=pk) if request.method == 'POST': form = CustomCommentForm(request.POST) if form.is_valid(): comment = form.save(commit=False) comment.post = post comment.creator = user comment.save() comment = Comments.objects.create( body=form.cleaned_data.get('body'), creator=user, ) return render(request, 'post.html', {'post': post, 'topic': topic, 'comment': comment, 'form': form}) else: form = CustomCommentForm() return render(request, 'post.html', {'post': post, 'topic': topic, 'comment': comment, 'form': form}) I builded comment function for post but it has bug. When someone comment post, another user see correct comment body, but incorrect image and name. i know why i has this problem(i suppose), it happend because i use user=request.user. Notice on string that i comment on 3 line. I was think that will help me,but it isn't. I use primary key in my url. url(r'^boards/(?P<pk>\d+)/$', views.board_topics, name='board_topics'), and when i use primary key in filter it return to me user that has same pk as post pk. I need that it return to me username and picture of user that create this comment. Html template: <div … -
Django admin - Use inlines in django admin saving data in current model
I need use inlines in django admin for show relation between two models but in the moment that i do, i had to do the reverse relationship to show inlines. Example: class OtherModel(models.Model): field1=models... ........ class Model(models.Model): field1 = models.... other_model = models.ForeignKey(OtherModel) I create the inline... class OtherModelInline(admin.StackedInline): model = OtherModel extra = 1 @admin.register(Model): class ModelAdmin(admin.modelAdmin): inlines = [OtherModelInline] So... When I create the Inline it required foreign key on OtherModel.. How can I show this without change the relationship? -
Why does django pgm crash when entered number exceeds DecimalField max_digits?
I have the following field in my Django model: price = models.DecimalField(max_digits=8, decimal_places=2, default=0) and the following code in my form: price = forms.DecimalField(widget=forms.NumberInput(attrs={'step': '0.01', 'text-align': 'right;'})) (BTW, the text-align doesn't work - different problem, I think) It works when displayed in a form. In fact, when I try to use more than 2 decimal places, the form pops up a message: However, if I enter too many digits, as in: Django throws the following error: InvalidOperation at /balancer/set_security_prices/2017-10-14 [] Request Method: POST Request URL: http://localhost:8000/balancer/set_security_prices/2017-10-14 Django Version: 1.9.1 Exception Type: InvalidOperation Exception Value: [] Exception Location: /Library/Frameworks/Python.framework/Versions/3.5/lib/python3.5/site-packages/django/db/backends/utils.py in format_number, line 200 Python Executable: /Library/Frameworks/Python.framework/Versions/3.5/bin/python3.5 Python Version: 3.5.1 The is_valid() check I do before saving the data doesn't trap the problem. This doesn't make sense to me. Shouldn't Django protect against this or must I add try ...except code? Thanks! -
Django UnicodeDecodeError: utf-8' codec can't decode byte 0xe2 in position 10: invalid continuation byte
I am making an app with Django. I want to generate pdf when I browse select link. So I used weasyprint module for convert my pdf. I import weasyprint module. But When I run that app, I found some error. This is views.py file def customersProfile(request, customer_id, sys_type): sys_type=sys_type area="profile" site_credit = site_credit1 time_now=timezone.now() customers=get_object_or_404(CustomerInfo, pk=customer_id) html_string = render_to_string('shop/profile.html', {'customers': customers, 'todaydate': today_date,'site_name': 'Moon Telecom', 'time_now': time_now, 'site_credit': site_credit, 'area': area}) html = HTML(string=html_string) result = html.write_pdf() response = HttpResponse(content_type='application/pdf;') response['Content-Disposition'] = 'inline; filename=list_people.pdf' response['Content-Transfer-Encoding'] = 'binary' with tempfile.NamedTemporaryFile(delete=True) as output: output.write(result) output.flush() output = open(output.name, 'r') response.write(output.read()) return response This is HTML file. I wanna create pdf this html file. <!DOCTYPE html> <html> <head> <meta name="viewport" content="width=device-width, initial-scale=1"> <link rel="stylesheet" href="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/css/bootstrap.min.css"> <script src="https://ajax.googleapis.com/ajax/libs/jquery/3.2.1/jquery.min.js"></script> <script src="https://maxcdn.bootstrapcdn.com/bootstrap/3.3.7/js/bootstrap.min.js"></script> </head> <body style> <div class="container"> <div class="row"> <div class="col-lg-12"> <div class="site_title" style="text-align:center; margin:0 auto"> <h3>মুন টেলিকম</h3> <h3> <a href="{% url 'shop:index' %}" target="_blank">{{site_name}}</a> </h3> <div class="invoice_info_one" style="width:100%; text-align:center"> <p>সকল প্রকার মোবাইল সেট, সীম কার্ড, মেমোরী কার্ড, MP-3, সোলার চার্জার, সোলার ফ্যান, মোবাইল ফোনের ব্যাটারী, চার্জার, ক্যাচিং,কাভার,হেডফোন, রেবন, ডিসপ্লে এবং ইলেট্রিক মালামাল বিক্রেতা</p> </div> <div class="invoice_location"> <p>জাহাঙ্গীর সুপার মার্কেট, ব্রীজ রোড, ফুলহাতা বাজার, মোডেলগঞ্জ।</p> </div> <div class="invoice_contact"> <p>01717-051200(সুকান্ত) 01828-163858(দোকান)</p> <p><b>Email:</b> moontelecom2008@gmail.com</p> </div> <div class="copy_right"> {% … -
Unable to config django for mysql
I'm trying to connect Django app to MySQL on windows 10. I have installed mysqlclient as an interface between my Django app and MySQL. Whenever I try to open dbshell I'm getting error something like this:- django.core.exceptions.ImproperlyConfigured: Requested setting USE_I18N, but settings are not configured Here is my setting.py file DATABASES = { 'default': { 'ENGINE': 'django.db.backends.mysql', 'NAME': 'blog', 'USER':'root', 'PASSWORD':'root', 'HOST':'127.0.0.1', 'PORT':'3306' } } I have tried other solutions on StackOverflow but it didn't work for me. I also tried deleting the dbsqlite3 file from the project directory. Versions for different elements are as follows:- Python (3.6) Django (1.11.4) mysqlclient (1.3.12) pip (9.0.1) MySQL(5.7) -
html form creating user but not connecting to django model
I am creating a user sign-in system using the default django authentication system and have attached a model to it. The problem however is that whilst the user is created when I input the data in the form, the rest of the details are not actually transferred to the model i.e First Name and Last Name. It just creates the instance of that model but it has blank values. How do i fix this (among others)? I've tried: With Django ModelForms, how do I including the "id" column or primary key in the HTML? Django - Use multiple models and forms for the same view How to post my html form to django model and save it? HTML {% load account socialaccount %} {% load i18n %} {% load static %} {% load staticfiles %} <form id="register-form" role="form" method="POST" action="{% url 'student-register' %}"> {% csrf_token %} <br> <div class="form-group"> <img src="{% static 'img/logo_dark_100.png' %}"/> </div> <div class="form-group"> <label class="control-label">First Name:</label> <input type="text" id="register-name" name="first_name" class="form-control"> </div> <div class="form-group"> <label class="control-label">Surname:</label> <input type="text" id="register-last_name" name="last_name" class="form-control"> </div> <div class="form-group"> <label class="control-label">Email:</label> <input type="email" id="register-email" name="email" class="form-control"> </div> <div class="form-group"> <label class="control-label">{% trans "Password:" %}</label> <input type="password" id="register-password" name="password1" class="form-control"> </div> <div … -
How to solve error if form is not valid in Django?
I have write down a view like this: views.py def Pep_Des(request): #result_files_list = [] if request.method == 'POST' and request.FILES.get('myfile'): myfile=request.FILES.get('myfile') fs = FileSystemStorage() filename = fs.save(myfile.name, myfile) uploaded_file_url = fs.url(filename) return render(request, 'Peptide_Descriptor/success.html', {}) if request.method == 'POST': form = Random_pep_seq(request.POST) else: myfile=None Fasta = "MGSSHHHHHHSS,GLVPRGSHMARV,TLVLRYAARSDRG,LVRANNEDSVYA,GARLLALADGMG,GHAAGEVASQLV,IAALAHLDDDEP,GGDLLAKLDAAV,RAGNSAIAAQVE,MEPDLEGMGTT,LTAILFAGNRLG,LVHIGDSRGYLL,RDGELTQITKDD,TFVQTLVDEGRI,TPEEAHSHPQRS,LIMRALTGHEVE,PTLTMREARAGD,RYLLCSDGLSDP,VSDETILEALQI,PEVAESAHRLIE,LALRGGGPDNVT" form = Random_pep_seq(initial={'Sequence':Fasta}) return render(request, 'Peptide_Descriptor/des.html', {'form':form}) #return render(request, 'FragBuild/Rand_Frag.html', {'form': form}) def success_file(request): return render(request, 'Peptide_Descriptor/success.html', {}) def Pep_Des_generated(request): Fasta = "MGSSHHHHHHSS,GLVPRGSHMARV,TLVLRYAARSDRG,LVRANNEDSVYA,GARLLALADGMG,GHAAGEVASQLV,IAALAHLDDDEP,GGDLLAKLDAAV,RAGNSAIAAQVE,MEPDLEGMGTT,LTAILFAGNRLG,LVHIGDSRGYLL,RDGELTQITKDD,TFVQTLVDEGRI,TPEEAHSHPQRS,LIMRALTGHEVE,PTLTMREARAGD,RYLLCSDGLSDP,VSDETILEALQI,PEVAESAHRLIE,LALRGGGPDNVT" form = Random_pep_seq(initial={'Sequence':Fasta}) form = Random_pep_seq(request.POST) if form.is_valid(): val_1 = form.cleaned_data['Sequence'] else: val_1 = " form is not valid" return render(request, 'Peptide_Descriptor/des_result.html',{'val_1':val_1}) "forms.py" like this from django import forms class Random_pep_seq(forms.Form): Sequence = forms.CharField(widget=forms.Textarea(attrs={'class':'form-control','placeholder':'Ex.: ATTHYILLKY,ATTYYILLKY,ATTIILLKY'})) myfile = forms.FileField(allow_empty_file= True, label='3 Upload file 1', help_text='*') class Meta: fields = ['Sequence'] template like this: {% extends 'protocol/base.html' %} {% load staticfiles %} {% block content %} <style type="text/css"> .button { background-color: #ff9800; /* Green */ border: none; color: black; padding: 10px 32px; text-align: center; text-decoration: none; display: inline-block; font-size: 16px; margin-top: 10px; margin-bottom: 30px; } </style> <div style="margin-left: 50px; margin-right: 300px "> <form action="/Pep_Des_generated/" method="post"> <div class="heading"> <h2> Peptide Descriptor Generation..... </h2> <h5> Submit Peptide directly or upload ".csv" file contains peptide library.. </h5> <div class="form-group"> {%csrf_token%} {{form.Sequence}} </div> {% csrf_token %} … -
Using custom python classes alongside Django app
First and foremost, this is my very first question on Stackoverflow. Any positive criticism is welcome. I tried looking everywhere for an answer, this is my last resort. In a school project, my team and I have to create a shopping website with a very specific server-side architecture. We agreed to use python and turned ourselves towards Django since it seemed to offer more functionalities than other possible frameworks. Be aware that none of us ever used Django in the past. We aren't masters at deploying application on the web either (we are all learning). Here's my problem: two weeks in the project, our teacher told us that we were not allowed to use any ORM. To me, this meant bye bye to Django models and that we have to create everything on our own. Here are my questions: as we already have created all our python classes, is there any way for us to use them alongside our Django app? I have not seen any example online of people using their own python classes within a Django app. If it were possible, where should we instantiate all our objects? Would it be easier to just go with another framework … -
NVD3 Chart won't render in Django
I'm having trouble getting my nvd3 pie chart to render. I'm using a template tag (simple tag) to return the data required to construct the pie chart. Already verified: All static files are loading The template tag is passing the correct dictionary to the template All templates are loading No errors The chart appears to be loading in the source code header color-id.html (template for just the pie chart) {% load static %} <link media="all" href="{% static 'nvd3/build/nv.d3.css' %}" type="text/css" rel="stylesheet" /> <script type="text/javascript" src='{% static 'd3/d3.min.js' %}'></script> <script type="text/javascript" src='{% static 'nvd3/build/nv.d3.min.js' %}'></script> {% load nvd3_tags %} {% load basic_deck_stats %} <head> {% include_chart_jscss %} {% color_id deck as data %} {% load_chart data.charttype data.chartdata data.chartcontainer data.extra %} </head> <body> <h3>Color Identity</h3> {% include_container "asdf" 400 400 %} charttype: {{ data.charttype }}<br> chartdata: {{ data.chartdata }}<br> chartcontainer: {{ data.chartcontainer }}<br> extra: {{ data.extra }} </body> basic_deck_stats.py (template tag) from django import template from card_search.views import Card, Deck, Quantity from django.shortcuts import render_to_response register = template.Library() @register.simple_tag def color_id(deck): black=blue=red=white=green = 0 queryset = Quantity.objects.filter(deck__deck_name=deck.deck_name).all() for item in queryset: if item.card.mana_cost: black += item.card.mana_cost.count("{B}") * item.qty blue += item.card.mana_cost.count("{U}") * item.qty red += item.card.mana_cost.count("{R}") * item.qty white += item.card.mana_cost.count("{W}") * … -
Can't make Gdal 1.11.2 work from binaries
I am trying to install GEOS for Django project and following Docs but while compiling on Ubuntu 16.04 Xenial I get this error. There was some fix for it here but it also didn't worked. Following is the error I get while I ran "make" as per official Django docs. Error: gdalserver.c: In function 'CreateSocketAndBindAndListen': gdalserver.c:125:21: error: storage size of 'sHints' isn't known struct addrinfo sHints; ^ gdalserver.c:127:31: error: invalid application of 'sizeof' to incomplete type 'struct addrinfo' memset(&sHints, 0, sizeof(struct addrinfo)); ^ gdalserver.c:130:23: error: 'AI_PASSIVE' undeclared (first use in this function) sHints.ai_flags = AI_PASSIVE; ^ gdalserver.c:130:23: note: each undeclared identifier is reported only once for each function it appears in gdalserver.c:133:12: warning: implicit declaration of function 'getaddrinfo' [-Wimplicit-function-declaration] nRet = getaddrinfo(NULL, pszService, &sHints, &psResults); ^ gdalserver.c:136:48: warning: implicit declaration of function 'gai_strerror' [-Wimplicit-function-declaration] fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(nRet)); ^ gdalserver.c:136:25: warning: format '%s' expects argument of type 'char *', but argument 3 has type 'int' [-Wformat=] fprintf(stderr, "getaddrinfo(): %s\n", gai_strerror(nRet)); ^ gdalserver.c:142:39: error: dereferencing pointer to incomplete type 'struct addrinfo' psResultsIter = psResultsIter->ai_next) ^ gdalserver.c:163:5: warning: implicit declaration of function 'freeaddrinfo' [-Wimplicit-function-declaration] freeaddrinfo(psResults); ^ gdalserver.c:125:21: warning: unused variable 'sHints' [-Wunused-variable] struct addrinfo sHints; ^ ../GDALmake.opt:565: recipe for target 'gdalserver.lo' failed … -
Django CSRF cookie not set. Stuck
I'm learning how work Django and I've bought a book for this. I try to do a connection system with method="post" for the form. And when I submit there's CSRF cookie not set etc... I saw a lot of similar problems on the forum but still a bit stuck as I don't understand all the answer and I've not found something which worked excepted @csrf_exempt but I saw it was like disabling the things and it wasn't a good idea. Here's the code : My html login.html page : <form action="." method="post">{% csrf_token %} {% if error %} <p class="error">{{ error }}</p> {% endif %} <p> <label for="email">E-mail :</label> <input name="email" id="email" size="30" type="email" /> </p> <p> <label for="password">Password :</label> <input name="password" id="password" size="30" type="password" /> </p> <p> <input type="submit" value="Log-in" /> <a href="">Créer un compte</a> </p> My views.py : from django.shortcuts import render_to_response from datetime import datetime from django.views.decorators.csrf import csrf_protect from django.http.response import HttpResponseRedirect # from django.http import HttpResponseRedirect def welcome(request): return render_to_response('welcome.html', {'curent_date_time' : datetime.now}) @csrf_protect def login(request): if len(request.POST) > 0: if 'email' not in request.POST or 'password' not in request.POST: error = "Veuillez entrer un adresse mail et un mot de passe." return render_to_response('login.html', {'error': … -
Update existing base.html path without modifying all the paths
I need to update the path for mezzanine in django. Is there a way to update {% extends "base.html" %} to {% extends "index/base.html" %} without changing all the files that include the extends? -
Where to host simple landing page with django backend
I'v got a simple landing page, and there is django backend only for sending email from form submitted data. The question, whether there is simple django hosting, where I can host simple website fast. I mean, not some VPS like Digital Ocean, where I need to setup lots of things. Or the only option nowadays is to setup VPS? -
Django queryset - Filtering related table objects before aggregation
Consider this model in Django documentation: Aggregation and Avg There is a queryset like this: Author.objects.annotate(average_rating=Avg('book__rating')) which returns all authors annotated by average rate of all of their books. What if I want to query authors annotated by average rate of their books which have been published for example in 2016. Note that I want to get results with as few queries as possible. -
djstripe (django stripe) - should I create local or remote customers first?
When I receive my stripe token after a valid form: what data should I be using to create my local customer model? Many fields returned from the stripe create customer JSON response are incompatible with the local dj.stripe Customer model. Am I supposed to be deleting and changing fields from the stripe JSON response to shoehorn it into my local model or am I missing the advantage of using djstripe?